org.apache.calcite.avatica.util.TimeUnit Java Examples

The following examples show how to use org.apache.calcite.avatica.util.TimeUnit. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RexLiteral.java    From calcite with Apache License 2.0 6 votes vote down vote up
private String intervalString(BigDecimal v) {
  final List<TimeUnit> timeUnits = getTimeUnits(type.getSqlTypeName());
  final StringBuilder b = new StringBuilder();
  for (TimeUnit timeUnit : timeUnits) {
    final BigDecimal[] result = v.divideAndRemainder(timeUnit.multiplier);
    if (b.length() > 0) {
      b.append(timeUnit.separator);
    }
    final int width = b.length() == 0 ? -1 : width(timeUnit); // don't pad 1st
    pad(b, result[0].toString(), width);
    v = result[1];
  }
  if (Util.last(timeUnits) == TimeUnit.MILLISECOND) {
    while (b.toString().matches(".*\\.[0-9]*0")) {
      if (b.toString().endsWith(".0")) {
        b.setLength(b.length() - 2); // remove ".0"
      } else {
        b.setLength(b.length() - 1); // remove "0"
      }
    }
  }
  return b.toString();
}
 
Example #2
Source File: BigQuerySqlDialect.java    From calcite with Apache License 2.0 6 votes vote down vote up
private TimeUnit validate(TimeUnit timeUnit) {
  switch (timeUnit) {
  case MICROSECOND:
  case MILLISECOND:
  case SECOND:
  case MINUTE:
  case HOUR:
  case DAY:
  case WEEK:
  case MONTH:
  case QUARTER:
  case YEAR:
  case ISOYEAR:
    return timeUnit;
  default:
    throw new RuntimeException("Time unit " + timeUnit + " is not supported for BigQuery.");
  }
}
 
Example #3
Source File: RexImpTable.java    From Quicksql with MIT License 6 votes vote down vote up
private static long getFactor(TimeUnit unit) {
  switch (unit) {
  case DAY:
    return 1L;
  case HOUR:
    return TimeUnit.DAY.multiplier.longValue();
  case MINUTE:
    return TimeUnit.HOUR.multiplier.longValue();
  case SECOND:
    return TimeUnit.MINUTE.multiplier.longValue();
  case MILLISECOND:
    return TimeUnit.SECOND.multiplier.longValue();
  case MONTH:
    return TimeUnit.YEAR.multiplier.longValue();
  case QUARTER:
    return TimeUnit.YEAR.multiplier.longValue();
  case YEAR:
  case DECADE:
  case CENTURY:
  case MILLENNIUM:
    return 1L;
  default:
    throw Util.unexpected(unit);
  }
}
 
Example #4
Source File: RexInterpreter.java    From calcite with Apache License 2.0 6 votes vote down vote up
private Comparable extract(RexCall call, List<Comparable> values) {
  final Comparable v = values.get(1);
  if (v == N) {
    return N;
  }
  final TimeUnitRange timeUnitRange = (TimeUnitRange) values.get(0);
  final int v2;
  if (v instanceof Long) {
    // TIMESTAMP
    v2 = (int) (((Long) v) / TimeUnit.DAY.multiplier.longValue());
  } else {
    // DATE
    v2 = (Integer) v;
  }
  return DateTimeUtils.unixDateExtract(timeUnitRange, v2);
}
 
Example #5
Source File: SqlIntervalQualifier.java    From Quicksql with MIT License 6 votes vote down vote up
private boolean isSecondaryFieldInRange(BigDecimal field, TimeUnit unit) {
  // we should never get handed a negative field value
  assert field.compareTo(ZERO) >= 0;

  // YEAR and DAY can never be secondary units,
  // nor can unit be null.
  assert unit != null;
  switch (unit) {
  case YEAR:
  case DAY:
  default:
    throw Util.unexpected(unit);

    // Secondary field limits, as per section 4.6.3 of SQL2003 spec
  case MONTH:
  case HOUR:
  case MINUTE:
  case SECOND:
    return unit.isValidValue(field);
  }
}
 
Example #6
Source File: RexBuilder.java    From Quicksql with MIT License 6 votes vote down vote up
private RexNode makeCastIntervalToExact(RelDataType toType, RexNode exp) {
  final TimeUnit endUnit = exp.getType().getSqlTypeName().getEndUnit();
  final TimeUnit baseUnit = baseUnit(exp.getType().getSqlTypeName());
  final BigDecimal multiplier = baseUnit.multiplier;
  final int scale = 0;
  BigDecimal divider = endUnit.multiplier.scaleByPowerOfTen(-scale);
  RexNode value = multiplyDivide(decodeIntervalOrDecimal(exp),
      multiplier, divider);
  if (scale > 0) {
    RelDataType decimalType =
        typeFactory.createSqlType(SqlTypeName.DECIMAL,
            scale + exp.getType().getPrecision(), scale);
    value = encodeIntervalOrDecimal(value, decimalType, false);
  }
  return ensureType(toType, value, false);
}
 
Example #7
Source File: RexInterpreter.java    From Quicksql with MIT License 6 votes vote down vote up
private Comparable extract(RexCall call, List<Comparable> values) {
  final Comparable v = values.get(1);
  if (v == N) {
    return N;
  }
  final TimeUnitRange timeUnitRange = (TimeUnitRange) values.get(0);
  final int v2;
  if (v instanceof Long) {
    // TIMESTAMP
    v2 = (int) (((Long) v) / TimeUnit.DAY.multiplier.longValue());
  } else {
    // DATE
    v2 = (Integer) v;
  }
  return DateTimeUtils.unixDateExtract(timeUnitRange, v2);
}
 
Example #8
Source File: RelWriterTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
@Test void testInterval() {
  final FrameworkConfig config = RelBuilderTest.config().build();
  final RelBuilder builder = RelBuilder.create(config);
  SqlIntervalQualifier sqlIntervalQualifier =
      new SqlIntervalQualifier(TimeUnit.DAY, TimeUnit.DAY, SqlParserPos.ZERO);
  BigDecimal value = new BigDecimal(86400000);
  RexLiteral intervalLiteral = builder.getRexBuilder()
      .makeIntervalLiteral(value, sqlIntervalQualifier);
  final RelNode rel = builder
      .scan("EMP")
      .project(
          builder.call(
              SqlStdOperatorTable.TUMBLE_END,
              builder.field("HIREDATE"),
              intervalLiteral))
      .build();
  RelJsonWriter jsonWriter = new RelJsonWriter();
  rel.explain(jsonWriter);
  String relJson = jsonWriter.asString();
  String s = deserializeAndDumpToTextFormat(getSchema(rel), relJson);
  final String expected = ""
      + "LogicalProject($f0=[TUMBLE_END($4, 86400000:INTERVAL DAY)])\n"
      + "  LogicalTableScan(table=[[scott, EMP]])\n";
  assertThat(s, isLinux(expected));
}
 
Example #9
Source File: Views.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
public static View fieldTypesToView(String name, String sql, List<ViewFieldType> fieldTypes, List<String> context) {
  if (fieldTypes == null) {
    throw new NullPointerException();
  }
  List<FieldType> fields = new ArrayList<>();
  for (ViewFieldType sqlField : fieldTypes) {
    FieldType fieldType = new View.FieldType(
        sqlField.getName(),
        en(SqlTypeName.class, sqlField.getType()),
        sqlField.getPrecision(), sqlField.getScale(),
        en(TimeUnit.class, sqlField.getStartUnit()),
        en(TimeUnit.class, sqlField.getEndUnit()),
        sqlField.getFractionalSecondPrecision(),
        sqlField.getIsNullable()
        );
    fields.add(fieldType);
  }
  return new View(name, sql, fields, null, context);
}
 
Example #10
Source File: SqlDateTimeUtils.java    From flink with Apache License 2.0 6 votes vote down vote up
private static BigDecimal getFactor(TimeUnit unit) {
	switch (unit) {
		case DAY: return BigDecimal.ONE;
		case HOUR: return TimeUnit.DAY.multiplier;
		case MINUTE: return TimeUnit.HOUR.multiplier;
		case SECOND: return TimeUnit.MINUTE.multiplier;
		case MILLISECOND:
		case MICROSECOND:
		case NANOSECOND:
			return TimeUnit.SECOND.multiplier;
		case YEAR: return BigDecimal.ONE;
		case MONTH: return TimeUnit.YEAR.multiplier;
		case QUARTER: return TimeUnit.YEAR.multiplier;
		case DECADE:
		case CENTURY:
		case MILLENNIUM:
			return BigDecimal.ONE;
		default:
			throw new IllegalArgumentException("Invalid start unit.");
	}
}
 
Example #11
Source File: RexLiteral.java    From Quicksql with MIT License 6 votes vote down vote up
private String intervalString(BigDecimal v) {
  final List<TimeUnit> timeUnits = getTimeUnits(type.getSqlTypeName());
  final StringBuilder b = new StringBuilder();
  for (TimeUnit timeUnit : timeUnits) {
    final BigDecimal[] result = v.divideAndRemainder(timeUnit.multiplier);
    if (b.length() > 0) {
      b.append(timeUnit.separator);
    }
    final int width = b.length() == 0 ? -1 : width(timeUnit); // don't pad 1st
    pad(b, result[0].toString(), width);
    v = result[1];
  }
  if (Util.last(timeUnits) == TimeUnit.MILLISECOND) {
    while (b.toString().matches(".*\\.[0-9]*0")) {
      if (b.toString().endsWith(".0")) {
        b.setLength(b.length() - 2); // remove ".0"
      } else {
        b.setLength(b.length() - 1); // remove "0"
      }
    }
  }
  return b.toString();
}
 
Example #12
Source File: RexImpTable.java    From calcite with Apache License 2.0 6 votes vote down vote up
private static long getFactor(TimeUnit unit) {
  switch (unit) {
  case DAY:
    return 1L;
  case HOUR:
    return TimeUnit.DAY.multiplier.longValue();
  case MINUTE:
    return TimeUnit.HOUR.multiplier.longValue();
  case SECOND:
    return TimeUnit.MINUTE.multiplier.longValue();
  case MILLISECOND:
    return TimeUnit.SECOND.multiplier.longValue();
  case MONTH:
    return TimeUnit.YEAR.multiplier.longValue();
  case QUARTER:
    return TimeUnit.YEAR.multiplier.longValue();
  case YEAR:
  case DECADE:
  case CENTURY:
  case MILLENNIUM:
    return 1L;
  default:
    throw Util.unexpected(unit);
  }
}
 
Example #13
Source File: SqlDateTimeUtils.java    From flink with Apache License 2.0 6 votes vote down vote up
private static BigDecimal getFactory(TimeUnit unit) {
	switch (unit) {
		case DAY: return BigDecimal.ONE;
		case HOUR: return TimeUnit.DAY.multiplier;
		case MINUTE: return TimeUnit.HOUR.multiplier;
		case SECOND: return TimeUnit.MINUTE.multiplier;
		case YEAR: return BigDecimal.ONE;
		case MONTH: return TimeUnit.YEAR.multiplier;
		case QUARTER: return TimeUnit.YEAR.multiplier;
		case DECADE:
		case CENTURY:
		case MILLENNIUM:
			return BigDecimal.ONE;
		default:
			throw new IllegalArgumentException("Invalid start unit.");
	}
}
 
Example #14
Source File: SqlDateTimeUtils.java    From flink with Apache License 2.0 5 votes vote down vote up
private static long convertExtract(TimeUnitRange range, long ts, LogicalType type, TimeZone tz) {
	TimeUnit startUnit = range.startUnit;
	long offset = tz.getOffset(ts);
	long utcTs = ts + offset;

	switch (startUnit) {
		case MILLENNIUM:
		case CENTURY:
		case YEAR:
		case QUARTER:
		case MONTH:
		case DAY:
		case DOW:
		case DOY:
		case WEEK:
			if (type instanceof TimestampType) {
				long d = divide(utcTs, TimeUnit.DAY.multiplier);
				return DateTimeUtils.unixDateExtract(range, d);
			} else if (type instanceof DateType) {
				return divide(utcTs, TimeUnit.DAY.multiplier);
			} else {
				// TODO support it
				throw new TableException(type + " is unsupported now.");
			}
		case DECADE:
			// TODO support it
			throw new TableException("DECADE is unsupported now.");
		case EPOCH:
			// TODO support it
			throw new TableException("EPOCH is unsupported now.");
		default:
			// fall through
	}

	long res = mod(utcTs, getFactory(startUnit));
	res = divide(res, startUnit.multiplier);
	return res;

}
 
Example #15
Source File: SqlIntervalQualifier.java    From calcite with Apache License 2.0 5 votes vote down vote up
private void checkLeadFieldInRange(RelDataTypeSystem typeSystem, int sign,
    BigDecimal value, TimeUnit unit, SqlParserPos pos) {
  if (!isLeadFieldInRange(typeSystem, value, unit)) {
    throw fieldExceedsPrecisionException(
        pos, sign, value, unit, getStartPrecision(typeSystem));
  }
}
 
Example #16
Source File: SqlIntervalQualifier.java    From calcite with Apache License 2.0 5 votes vote down vote up
/**
 * Validates an INTERVAL literal against a MONTH interval qualifier.
 *
 * @throws org.apache.calcite.runtime.CalciteContextException if the interval
 * value is illegal
 */
private int[] evaluateIntervalLiteralAsMonth(
    RelDataTypeSystem typeSystem, int sign,
    String value,
    String originalValue,
    SqlParserPos pos) {
  BigDecimal month;

  // validate as MONTH(startPrecision), e.g. 'MM'
  String intervalPattern = "(\\d+)";

  Matcher m = Pattern.compile(intervalPattern).matcher(value);
  if (m.matches()) {
    // Break out  field values
    try {
      month = parseField(m, 1);
    } catch (NumberFormatException e) {
      throw invalidValueException(pos, originalValue);
    }

    // Validate individual fields
    checkLeadFieldInRange(typeSystem, sign, month, TimeUnit.MONTH, pos);

    // package values up for return
    return fillIntervalValueArray(sign, ZERO, month);
  } else {
    throw invalidValueException(pos, originalValue);
  }
}
 
Example #17
Source File: SqlIntervalQualifier.java    From calcite with Apache License 2.0 5 votes vote down vote up
/**
 * Validates an INTERVAL literal against a YEAR TO MONTH interval qualifier.
 *
 * @throws org.apache.calcite.runtime.CalciteContextException if the interval
 * value is illegal
 */
private int[] evaluateIntervalLiteralAsYearToMonth(
    RelDataTypeSystem typeSystem, int sign,
    String value,
    String originalValue,
    SqlParserPos pos) {
  BigDecimal year;
  BigDecimal month;

  // validate as YEAR(startPrecision) TO MONTH, e.g. 'YY-DD'
  String intervalPattern = "(\\d+)-(\\d{1,2})";

  Matcher m = Pattern.compile(intervalPattern).matcher(value);
  if (m.matches()) {
    // Break out  field values
    try {
      year = parseField(m, 1);
      month = parseField(m, 2);
    } catch (NumberFormatException e) {
      throw invalidValueException(pos, originalValue);
    }

    // Validate individual fields
    checkLeadFieldInRange(typeSystem, sign, year, TimeUnit.YEAR, pos);
    if (!(isSecondaryFieldInRange(month, TimeUnit.MONTH))) {
      throw invalidValueException(pos, originalValue);
    }

    // package values up for return
    return fillIntervalValueArray(sign, year, month);
  } else {
    throw invalidValueException(pos, originalValue);
  }
}
 
Example #18
Source File: SqlIntervalQualifier.java    From calcite with Apache License 2.0 5 votes vote down vote up
/**
 * Validates an INTERVAL literal against a YEAR interval qualifier.
 *
 * @throws org.apache.calcite.runtime.CalciteContextException if the interval
 * value is illegal
 */
private int[] evaluateIntervalLiteralAsYear(
    RelDataTypeSystem typeSystem, int sign,
    String value,
    String originalValue,
    SqlParserPos pos) {
  BigDecimal year;

  // validate as YEAR(startPrecision), e.g. 'YY'
  String intervalPattern = "(\\d+)";

  Matcher m = Pattern.compile(intervalPattern).matcher(value);
  if (m.matches()) {
    // Break out  field values
    try {
      year = parseField(m, 1);
    } catch (NumberFormatException e) {
      throw invalidValueException(pos, originalValue);
    }

    // Validate individual fields
    checkLeadFieldInRange(typeSystem, sign, year, TimeUnit.YEAR, pos);

    // package values up for return
    return fillIntervalValueArray(sign, year, ZERO);
  } else {
    throw invalidValueException(pos, originalValue);
  }
}
 
Example #19
Source File: RexBuilder.java    From calcite with Apache License 2.0 5 votes vote down vote up
private RexNode makeCastIntervalToExact(RelDataType toType, RexNode exp) {
  final TimeUnit endUnit = exp.getType().getSqlTypeName().getEndUnit();
  final TimeUnit baseUnit = baseUnit(exp.getType().getSqlTypeName());
  final BigDecimal multiplier = baseUnit.multiplier;
  final BigDecimal divider = endUnit.multiplier;
  RexNode value = multiplyDivide(decodeIntervalOrDecimal(exp),
      multiplier, divider);
  return ensureType(toType, value, false);
}
 
Example #20
Source File: MysqlSqlDialect.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Override public void unparseSqlIntervalQualifier(SqlWriter writer,
    SqlIntervalQualifier qualifier, RelDataTypeSystem typeSystem) {

  //  Unit Value         | Expected Format
  // --------------------+-------------------------------------------
  //  MICROSECOND        | MICROSECONDS
  //  SECOND             | SECONDS
  //  MINUTE             | MINUTES
  //  HOUR               | HOURS
  //  DAY                | DAYS
  //  WEEK               | WEEKS
  //  MONTH              | MONTHS
  //  QUARTER            | QUARTERS
  //  YEAR               | YEARS
  //  MINUTE_SECOND      | 'MINUTES:SECONDS'
  //  HOUR_MINUTE        | 'HOURS:MINUTES'
  //  DAY_HOUR           | 'DAYS HOURS'
  //  YEAR_MONTH         | 'YEARS-MONTHS'
  //  MINUTE_MICROSECOND | 'MINUTES:SECONDS.MICROSECONDS'
  //  HOUR_MICROSECOND   | 'HOURS:MINUTES:SECONDS.MICROSECONDS'
  //  SECOND_MICROSECOND | 'SECONDS.MICROSECONDS'
  //  DAY_MINUTE         | 'DAYS HOURS:MINUTES'
  //  DAY_MICROSECOND    | 'DAYS HOURS:MINUTES:SECONDS.MICROSECONDS'
  //  DAY_SECOND         | 'DAYS HOURS:MINUTES:SECONDS'
  //  HOUR_SECOND        | 'HOURS:MINUTES:SECONDS'

  if (!qualifier.useDefaultFractionalSecondPrecision()) {
    throw new AssertionError("Fractional second precision is not supported now ");
  }

  final String start = validate(qualifier.timeUnitRange.startUnit).name();
  if (qualifier.timeUnitRange.startUnit == TimeUnit.SECOND
      || qualifier.timeUnitRange.endUnit == null) {
    writer.keyword(start);
  } else {
    writer.keyword(start + "_" + qualifier.timeUnitRange.endUnit.name());
  }
}
 
Example #21
Source File: MergeTableLikeUtilTest.java    From flink with Apache License 2.0 5 votes vote down vote up
private SqlNode boundedStrategy(String rowtimeColumn, String delay) {
	return new SqlBasicCall(
		SqlStdOperatorTable.MINUS,
		new SqlNode[]{
			identifier(rowtimeColumn),
			SqlLiteral.createInterval(
				1,
				delay,
				new SqlIntervalQualifier(TimeUnit.SECOND, TimeUnit.SECOND, SqlParserPos.ZERO),
				SqlParserPos.ZERO)
		},
		SqlParserPos.ZERO
	);
}
 
Example #22
Source File: RelDataTypeFactory.java    From Quicksql with MIT License 5 votes vote down vote up
/**
 * Adds a field with an interval type.
 */
public Builder add(String name, TimeUnit startUnit, int startPrecision,
    TimeUnit endUnit, int fractionalSecondPrecision) {
  final SqlIntervalQualifier q =
      new SqlIntervalQualifier(startUnit, startPrecision, endUnit,
          fractionalSecondPrecision, SqlParserPos.ZERO);
  add(name, typeFactory.createSqlIntervalType(q));
  return this;
}
 
Example #23
Source File: RexImpTable.java    From Quicksql with MIT License 5 votes vote down vote up
private Expression call(Expression operand, Type type,
    TimeUnit timeUnit) {
  return Expressions.call(SqlFunctions.class, methodName,
      Types.castIfNecessary(type, operand),
      Types.castIfNecessary(type,
          Expressions.constant(timeUnit.multiplier)));
}
 
Example #24
Source File: RexLiteral.java    From calcite with Apache License 2.0 5 votes vote down vote up
private static int width(TimeUnit timeUnit) {
  switch (timeUnit) {
  case MILLISECOND:
    return 3;
  case HOUR:
  case MINUTE:
  case SECOND:
    return 2;
  default:
    return -1;
  }
}
 
Example #25
Source File: MycatCalciteMySqlNodeVisitor.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean visit(SQLExtractExpr x) {
    x.getValue().accept(this);
    TimeUnit timeUnits[] = getTimeUnit(x.getUnit());

    sqlNode = SqlStdOperatorTable.EXTRACT
            .createCall(SqlParserPos.ZERO
                    , new SqlIntervalQualifier(timeUnits[0], timeUnits[1], SqlParserPos.ZERO)
                    , sqlNode);
    return false;
}
 
Example #26
Source File: RexLiteral.java    From Quicksql with MIT License 5 votes vote down vote up
private static int width(TimeUnit timeUnit) {
  switch (timeUnit) {
  case MILLISECOND:
    return 3;
  case HOUR:
  case MINUTE:
  case SECOND:
    return 2;
  default:
    return -1;
  }
}
 
Example #27
Source File: RexLiteral.java    From Quicksql with MIT License 5 votes vote down vote up
/** Returns a list of the time units covered by an interval type such
 * as HOUR TO SECOND. Adds MILLISECOND if the end is SECOND, to deal with
 * fractional seconds. */
private static List<TimeUnit> getTimeUnits(SqlTypeName typeName) {
  final TimeUnit start = typeName.getStartUnit();
  final TimeUnit end = typeName.getEndUnit();
  final ImmutableList<TimeUnit> list =
      TIME_UNITS.subList(start.ordinal(), end.ordinal() + 1);
  if (end == TimeUnit.SECOND) {
    return CompositeList.of(list, ImmutableList.of(TimeUnit.MILLISECOND));
  }
  return list;
}
 
Example #28
Source File: StandardConvertletTable.java    From Quicksql with MIT License 5 votes vote down vote up
public RexNode convertCall(SqlRexContext cx, SqlCall call) {
  // TIMESTAMPADD(unit, count, timestamp)
  //  => timestamp + count * INTERVAL '1' UNIT
  final RexBuilder rexBuilder = cx.getRexBuilder();
  final SqlLiteral unitLiteral = call.operand(0);
  final TimeUnit unit = unitLiteral.symbolValue(TimeUnit.class);
  RexNode interval2Add;
  SqlIntervalQualifier qualifier =
      new SqlIntervalQualifier(unit, null, unitLiteral.getParserPosition());
  RexNode op1 = cx.convertExpression(call.operand(1));
  switch (unit) {
  case MICROSECOND:
  case NANOSECOND:
    interval2Add =
        divide(rexBuilder,
            multiply(rexBuilder,
                rexBuilder.makeIntervalLiteral(BigDecimal.ONE, qualifier), op1),
            BigDecimal.ONE.divide(unit.multiplier,
                RoundingMode.UNNECESSARY));
    break;
  default:
    interval2Add = multiply(rexBuilder,
        rexBuilder.makeIntervalLiteral(unit.multiplier, qualifier), op1);
  }

  return rexBuilder.makeCall(SqlStdOperatorTable.DATETIME_PLUS,
      cx.convertExpression(call.operand(2)), interval2Add);
}
 
Example #29
Source File: SqlIntervalQualifier.java    From calcite with Apache License 2.0 5 votes vote down vote up
/**
 * Validates an INTERVAL literal against an HOUR TO MINUTE interval
 * qualifier.
 *
 * @throws org.apache.calcite.runtime.CalciteContextException if the interval
 * value is illegal
 */
private int[] evaluateIntervalLiteralAsHourToMinute(
    RelDataTypeSystem typeSystem, int sign,
    String value,
    String originalValue,
    SqlParserPos pos) {
  BigDecimal hour;
  BigDecimal minute;

  // validate as HOUR(startPrecision) TO MINUTE, e.g. 'HH:MM'
  String intervalPattern = "(\\d+):(\\d{1,2})";

  Matcher m = Pattern.compile(intervalPattern).matcher(value);
  if (m.matches()) {
    // Break out  field values
    try {
      hour = parseField(m, 1);
      minute = parseField(m, 2);
    } catch (NumberFormatException e) {
      throw invalidValueException(pos, originalValue);
    }

    // Validate individual fields
    checkLeadFieldInRange(typeSystem, sign, hour, TimeUnit.HOUR, pos);
    if (!(isSecondaryFieldInRange(minute, TimeUnit.MINUTE))) {
      throw invalidValueException(pos, originalValue);
    }

    // package values up for return
    return fillIntervalValueArray(sign, ZERO, hour, minute, ZERO, ZERO);
  } else {
    throw invalidValueException(pos, originalValue);
  }
}
 
Example #30
Source File: RelDataTypeFactory.java    From calcite with Apache License 2.0 5 votes vote down vote up
/**
 * Adds a field with an interval type.
 */
public Builder add(String name, TimeUnit startUnit, int startPrecision,
    TimeUnit endUnit, int fractionalSecondPrecision) {
  final SqlIntervalQualifier q =
      new SqlIntervalQualifier(startUnit, startPrecision, endUnit,
          fractionalSecondPrecision, SqlParserPos.ZERO);
  add(name, typeFactory.createSqlIntervalType(q));
  return this;
}