Java Code Examples for org.apache.calcite.rel.type.RelDataTypeSystem

The following examples show how to use org.apache.calcite.rel.type.RelDataTypeSystem. These examples are extracted from open source projects. 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 Project: calcite   Source File: Frameworks.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Initializes a container then calls user-specified code with a planner
 * and statement.
 *
 * @param action Callback containing user-specified code
 * @return Return value from action
 */
public static <R> R withPrepare(FrameworkConfig config,
    BasePrepareAction<R> action) {
  try {
    final Properties info = new Properties();
    if (config.getTypeSystem() != RelDataTypeSystem.DEFAULT) {
      info.setProperty(CalciteConnectionProperty.TYPE_SYSTEM.camelName(),
          config.getTypeSystem().getClass().getName());
    }
    Connection connection =
        DriverManager.getConnection("jdbc:calcite:", info);
    final CalciteServerStatement statement =
        connection.createStatement()
            .unwrap(CalciteServerStatement.class);
    return new CalcitePrepareImpl().perform(statement, config, action);
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}
 
Example 2
Source Project: calcite   Source File: BasicSqlType.java    License: Apache License 2.0 6 votes vote down vote up
/** Internal constructor. */
private BasicSqlType(
    RelDataTypeSystem typeSystem,
    SqlTypeName typeName,
    boolean nullable,
    int precision,
    int scale,
    SqlCollation collation,
    SerializableCharset wrappedCharset) {
  super(typeName, nullable, null);
  this.typeSystem = Objects.requireNonNull(typeSystem);
  this.precision = precision;
  this.scale = scale;
  this.collation = collation;
  this.wrappedCharset = wrappedCharset;
  computeDigest();
}
 
Example 3
Source Project: Bats   Source File: Db2SqlDialect.java    License: Apache License 2.0 6 votes vote down vote up
@Override public void unparseSqlIntervalLiteral(SqlWriter writer,
    SqlIntervalLiteral literal, int leftPrec, int rightPrec) {
  // A duration is a positive or negative number representing an interval of time.
  // If one operand is a date, the other labeled duration of YEARS, MONTHS, or DAYS.
  // If one operand is a time, the other must be labeled duration of HOURS, MINUTES, or SECONDS.
  // If one operand is a timestamp, the other operand can be any of teh duration.

  SqlIntervalLiteral.IntervalValue interval =
      (SqlIntervalLiteral.IntervalValue) literal.getValue();
  if (interval.getSign() == -1) {
    writer.print("-");
  }
  writer.literal(literal.getValue().toString());
  unparseSqlIntervalQualifier(writer, interval.getIntervalQualifier(),
      RelDataTypeSystem.DEFAULT);
}
 
Example 4
Source Project: Bats   Source File: MssqlSqlDialect.java    License: Apache License 2.0 6 votes vote down vote up
@Override public void unparseSqlIntervalQualifier(SqlWriter writer,
    SqlIntervalQualifier qualifier, RelDataTypeSystem typeSystem) {
  switch (qualifier.timeUnitRange) {
  case YEAR:
  case QUARTER:
  case MONTH:
  case WEEK:
  case DAY:
  case HOUR:
  case MINUTE:
  case SECOND:
  case MILLISECOND:
  case MICROSECOND:
    final String timeUnit = qualifier.timeUnitRange.startUnit.name();
    writer.keyword(timeUnit);
    break;
  default:
    throw new AssertionError("Unsupported type: " + qualifier.timeUnitRange);
  }

  if (null != qualifier.timeUnitRange.endUnit) {
    throw new AssertionError("End unit is not supported now: "
        + qualifier.timeUnitRange.endUnit);
  }
}
 
Example 5
Source Project: Bats   Source File: BasicSqlType.java    License: Apache License 2.0 6 votes vote down vote up
/** Internal constructor. */
private BasicSqlType(
    RelDataTypeSystem typeSystem,
    SqlTypeName typeName,
    boolean nullable,
    int precision,
    int scale,
    SqlCollation collation,
    SerializableCharset wrappedCharset) {
  super(typeName, nullable, null);
  this.typeSystem = Objects.requireNonNull(typeSystem);
  this.precision = precision;
  this.scale = scale;
  this.collation = collation;
  this.wrappedCharset = wrappedCharset;
  computeDigest();
}
 
Example 6
Source Project: Bats   Source File: CalciteCatalogReader.java    License: Apache License 2.0 6 votes vote down vote up
/** Creates an operator table that contains functions in the given class.
   *
   * @see ModelHandler#addFunctions */
  public static SqlOperatorTable operatorTable(String className) {
    // Dummy schema to collect the functions
    final CalciteSchema schema =
        CalciteSchema.createRootSchema(false, false);
//    ModelHandler.addFunctions(schema.plus(), null, ImmutableList.of(),
//        className, "*", true);

    // The following is technical debt; see [CALCITE-2082] Remove
    // RelDataTypeFactory argument from SqlUserDefinedAggFunction constructor
    final SqlTypeFactoryImpl typeFactory =
        new SqlTypeFactoryImpl(RelDataTypeSystem.DEFAULT);

    final ListSqlOperatorTable table = new ListSqlOperatorTable();
    for (String name : schema.getFunctionNames()) {
      for (Function function : schema.getFunctions(name, true)) {
        final SqlIdentifier id = new SqlIdentifier(name, SqlParserPos.ZERO);
        table.add(
            toOp(typeFactory, id, function));
      }
    }
    return table;
  }
 
Example 7
Source Project: calcite   Source File: RexBuilderTest.java    License: Apache License 2.0 6 votes vote down vote up
/** Tests {@link RexCopier#visitCorrelVariable(RexCorrelVariable)} */
@Test void testCopyCorrelVariable() {
  final RelDataTypeFactory sourceTypeFactory =
      new SqlTypeFactoryImpl(RelDataTypeSystem.DEFAULT);
  RelDataType type = sourceTypeFactory.createSqlType(SqlTypeName.VARCHAR, 65536);

  final RelDataTypeFactory targetTypeFactory =
      new MySqlTypeFactoryImpl(RelDataTypeSystem.DEFAULT);
  final RexBuilder builder = new RexBuilder(targetTypeFactory);

  final RexCorrelVariable node =
      (RexCorrelVariable) builder.makeCorrel(type, new CorrelationId(0));
  final RexNode copy = builder.copy(node);
  assertTrue(copy instanceof RexCorrelVariable);

  final RexCorrelVariable result = (RexCorrelVariable) copy;
  assertThat(result.id, is(node.id));
  assertThat(result.getType().getSqlTypeName(), is(SqlTypeName.VARCHAR));
  assertThat(result.getType().getPrecision(), is(PRECISION));
}
 
Example 8
Source Project: calcite   Source File: RexBuilderTest.java    License: Apache License 2.0 6 votes vote down vote up
/** Tests {@link RexCopier#visitLocalRef(RexLocalRef)} */
@Test void testCopyLocalRef() {
  final RelDataTypeFactory sourceTypeFactory =
      new SqlTypeFactoryImpl(RelDataTypeSystem.DEFAULT);
  RelDataType type = sourceTypeFactory.createSqlType(SqlTypeName.VARCHAR, 65536);

  final RelDataTypeFactory targetTypeFactory =
      new MySqlTypeFactoryImpl(RelDataTypeSystem.DEFAULT);
  final RexBuilder builder = new RexBuilder(targetTypeFactory);

  final RexLocalRef node = new RexLocalRef(0, type);
  final RexNode copy = builder.copy(node);
  assertTrue(copy instanceof RexLocalRef);

  final RexLocalRef result = (RexLocalRef) copy;
  assertThat(result.getIndex(), is(node.getIndex()));
  assertThat(result.getType().getSqlTypeName(), is(SqlTypeName.VARCHAR));
  assertThat(result.getType().getPrecision(), is(PRECISION));
}
 
Example 9
Source Project: calcite   Source File: RexBuilderTest.java    License: Apache License 2.0 6 votes vote down vote up
/** Tests {@link RexBuilder#makeDateLiteral(DateString)}. */
@Test void testDateLiteral() {
  final RelDataTypeFactory typeFactory =
      new SqlTypeFactoryImpl(RelDataTypeSystem.DEFAULT);
  RelDataType dateType = typeFactory.createSqlType(SqlTypeName.DATE);
  final RexBuilder builder = new RexBuilder(typeFactory);

  // Old way: provide a Calendar
  final Calendar calendar = Util.calendar();
  calendar.set(1969, Calendar.JULY, 21); // one small step
  calendar.set(Calendar.MILLISECOND, 0);
  checkDate(builder.makeLiteral(calendar, dateType, false));

  // Old way #2: Provide in Integer
  checkDate(builder.makeLiteral(MOON_DAY, dateType, false));

  // The new way
  final DateString d = new DateString(1969, 7, 21);
  checkDate(builder.makeLiteral(d, dateType, false));
}
 
Example 10
Source Project: calcite   Source File: MssqlSqlDialect.java    License: Apache License 2.0 6 votes vote down vote up
@Override public void unparseSqlIntervalQualifier(SqlWriter writer,
    SqlIntervalQualifier qualifier, RelDataTypeSystem typeSystem) {
  switch (qualifier.timeUnitRange) {
  case YEAR:
  case QUARTER:
  case MONTH:
  case WEEK:
  case DAY:
  case HOUR:
  case MINUTE:
  case SECOND:
  case MILLISECOND:
  case MICROSECOND:
    final String timeUnit = qualifier.timeUnitRange.startUnit.name();
    writer.keyword(timeUnit);
    break;
  default:
    throw new AssertionError("Unsupported type: " + qualifier.timeUnitRange);
  }

  if (null != qualifier.timeUnitRange.endUnit) {
    throw new AssertionError("End unit is not supported now: "
        + qualifier.timeUnitRange.endUnit);
  }
}
 
Example 11
Source Project: quark   Source File: QuarkConnectionImpl.java    License: Apache License 2.0 6 votes vote down vote up
protected QuarkConnectionImpl(QuarkDriver driver, AvaticaFactory factory, String url,
                              Properties info, CalciteRootSchema rootSchema,
                              JavaTypeFactory typeFactory) throws SQLException {
  super(driver, factory, url, info);

  CalciteConnectionConfig cfg = new CalciteConnectionConfigImpl(info);

  if (typeFactory != null) {
    this.typeFactory = typeFactory;
  } else {
    final RelDataTypeSystem typeSystem =
        cfg.typeSystem(RelDataTypeSystem.class, RelDataTypeSystem.DEFAULT);
    this.typeFactory = new JavaTypeFactoryImpl(typeSystem);
  }

  this.properties.put(InternalProperty.CASE_SENSITIVE, cfg.caseSensitive());
  this.properties.put(InternalProperty.UNQUOTED_CASING, cfg.unquotedCasing());
  this.properties.put(InternalProperty.QUOTED_CASING, cfg.quotedCasing());
  this.properties.put(InternalProperty.QUOTING, cfg.quoting());
}
 
Example 12
Source Project: quark   Source File: QuarkMetaImpl.java    License: Apache License 2.0 6 votes vote down vote up
private ImmutableList<MetaTypeInfo> getAllDefaultType() {
  final ImmutableList.Builder<MetaTypeInfo> allTypeList =
      new ImmutableList.Builder<>();
  final RelDataTypeSystem typeSystem = getConnection().getTypeFactory().getTypeSystem();
  for (SqlTypeName sqlTypeName : SqlTypeName.values()) {
    allTypeList.add(
        new MetaTypeInfo(sqlTypeName.getName(),
            sqlTypeName.getJdbcOrdinal(),
            typeSystem.getMaxPrecision(sqlTypeName),
            typeSystem.getLiteral(sqlTypeName, true),
            typeSystem.getLiteral(sqlTypeName, false),
            // All types are nullable
            (short) DatabaseMetaData.typeNullable,
            typeSystem.isCaseSensitive(sqlTypeName),
            // Making all type searchable; we may want to
            // be specific and declare under SqlTypeName
            (short) DatabaseMetaData.typeSearchable,
            false,
            false,
            typeSystem.isAutoincrement(sqlTypeName),
            (short) sqlTypeName.getMinScale(),
            (short) typeSystem.getMaxScale(sqlTypeName),
            typeSystem.getNumTypeRadix(sqlTypeName)));
  }
  return allTypeList.build();
}
 
Example 13
Source Project: quark   Source File: SqlWorker.java    License: Apache License 2.0 6 votes vote down vote up
private Planner buildPlanner(QueryContext context) {
  final List<RelTraitDef> traitDefs = new ArrayList<RelTraitDef>();
  traitDefs.add(ConventionTraitDef.INSTANCE);
  traitDefs.add(RelCollationTraitDef.INSTANCE);
  final ChainedSqlOperatorTable opTab =
      new ChainedSqlOperatorTable(
          ImmutableList.of(SqlStdOperatorTable.instance(),
              HiveSqlOperatorTable.instance(), catalogReader));
  FrameworkConfig config = Frameworks.newConfigBuilder() //
      .parserConfig(SqlParser.configBuilder()
          .setQuotedCasing(Casing.UNCHANGED)
          .setUnquotedCasing(Casing.TO_UPPER)
          .setQuoting(Quoting.DOUBLE_QUOTE)
          .build()) //
      .defaultSchema(context.getDefaultSchema()) //
      .operatorTable(opTab) //
      .traitDefs(traitDefs) //
      .convertletTable(StandardConvertletTable.INSTANCE)//
      .programs(getPrograms()) //
      .typeSystem(RelDataTypeSystem.DEFAULT) //
      .build();
  return Frameworks.getPlanner(config);
}
 
Example 14
Source Project: calcite   Source File: CalciteCatalogReader.java    License: Apache License 2.0 6 votes vote down vote up
/** Creates an operator table that contains functions in the given class.
 *
 * @see ModelHandler#addFunctions */
public static SqlOperatorTable operatorTable(String className) {
  // Dummy schema to collect the functions
  final CalciteSchema schema =
      CalciteSchema.createRootSchema(false, false);
  ModelHandler.addFunctions(schema.plus(), null, ImmutableList.of(),
      className, "*", true);

  // The following is technical debt; see [CALCITE-2082] Remove
  // RelDataTypeFactory argument from SqlUserDefinedAggFunction constructor
  final SqlTypeFactoryImpl typeFactory =
      new SqlTypeFactoryImpl(RelDataTypeSystem.DEFAULT);

  final ListSqlOperatorTable table = new ListSqlOperatorTable();
  for (String name : schema.getFunctionNames()) {
    for (Function function : schema.getFunctions(name, true)) {
      final SqlIdentifier id = new SqlIdentifier(name, SqlParserPos.ZERO);
      table.add(
          toOp(typeFactory, id, function));
    }
  }
  return table;
}
 
Example 15
Source Project: calcite   Source File: RexBuilderTest.java    License: Apache License 2.0 5 votes vote down vote up
/** Test case for
 * <a href="https://issues.apache.org/jira/browse/CALCITE-3587">[CALCITE-3587]
 * RexBuilder may lose decimal fraction for creating literal with DECIMAL type</a>.
 */
@Test void testDecimal() {
  final RelDataTypeFactory typeFactory =
      new SqlTypeFactoryImpl(RelDataTypeSystem.DEFAULT);
  final RelDataType type = typeFactory.createSqlType(SqlTypeName.DECIMAL, 4, 2);
  final RexBuilder builder = new RexBuilder(typeFactory);
  try {
    builder.makeLiteral(12.3, type, false);
    fail();
  } catch (AssertionError e) {
    assertThat(e.getMessage(),
        is("java.lang.Double is not compatible with DECIMAL, try to use makeExactLiteral"));
  }
}
 
Example 16
Source Project: calcite   Source File: SqlIntervalQualifier.java    License: Apache License 2.0 5 votes vote down vote up
private boolean isLeadFieldInRange(RelDataTypeSystem typeSystem,
    BigDecimal value, TimeUnit unit) {
  // we should never get handed a negative field value
  assert value.compareTo(ZERO) >= 0;

  // Leading fields are only restricted by startPrecision.
  final int startPrecision = getStartPrecision(typeSystem);
  return startPrecision < POWERS10.length
      ? value.compareTo(POWERS10[startPrecision]) < 0
      : value.compareTo(INT_MAX_VALUE_PLUS_ONE) < 0;
}
 
Example 17
Source Project: Bats   Source File: SqlDialect.java    License: Apache License 2.0 5 votes vote down vote up
/** Converts an interval literal to a SQL string. The default implementation
 * returns strings such as
 * <code>INTERVAL '1 2:3:4' DAY(4) TO SECOND(4)</code>. */
public void unparseSqlIntervalLiteral(SqlWriter writer,
    SqlIntervalLiteral literal, int leftPrec, int rightPrec) {
  SqlIntervalLiteral.IntervalValue interval =
      (SqlIntervalLiteral.IntervalValue) literal.getValue();
  writer.keyword("INTERVAL");
  if (interval.getSign() == -1) {
    writer.print("-");
  }
  writer.literal("'" + literal.getValue().toString() + "'");
  unparseSqlIntervalQualifier(writer, interval.getIntervalQualifier(),
      RelDataTypeSystem.DEFAULT);
}
 
Example 18
Source Project: calcite   Source File: RexProgramBuilderBase.java    License: Apache License 2.0 5 votes vote down vote up
@BeforeEach public void setUp() {
  typeFactory = new JavaTypeFactoryImpl(RelDataTypeSystem.DEFAULT);
  rexBuilder = new RexBuilder(typeFactory);
  executor =
      new RexExecutorImpl(new DummyTestDataContext());
  simplify =
      new RexSimplify(rexBuilder, RelOptPredicateList.EMPTY, executor)
          .withParanoid(true);
  trueLiteral = rexBuilder.makeLiteral(true);
  falseLiteral = rexBuilder.makeLiteral(false);

  nonNullableInt = typeFactory.createSqlType(SqlTypeName.INTEGER);
  nullableInt = typeFactory.createTypeWithNullability(nonNullableInt, true);
  nullInt = rexBuilder.makeNullLiteral(nullableInt);

  nonNullableSmallInt = typeFactory.createSqlType(SqlTypeName.SMALLINT);
  nullableSmallInt = typeFactory.createTypeWithNullability(nonNullableSmallInt, true);
  nullSmallInt = rexBuilder.makeNullLiteral(nullableSmallInt);

  nonNullableBool = typeFactory.createSqlType(SqlTypeName.BOOLEAN);
  nullableBool = typeFactory.createTypeWithNullability(nonNullableBool, true);
  nullBool = rexBuilder.makeNullLiteral(nullableBool);

  nonNullableVarchar = typeFactory.createSqlType(SqlTypeName.VARCHAR);
  nullableVarchar = typeFactory.createTypeWithNullability(nonNullableVarchar, true);
  nullVarchar = rexBuilder.makeNullLiteral(nullableVarchar);

  nonNullableDecimal = typeFactory.createSqlType(SqlTypeName.DECIMAL);
  nullableDecimal = typeFactory.createTypeWithNullability(nonNullableDecimal, true);
  nullDecimal = rexBuilder.makeNullLiteral(nullableDecimal);
}
 
Example 19
Source Project: calcite   Source File: Db2SqlDialect.java    License: Apache License 2.0 5 votes vote down vote up
@Override public void unparseSqlIntervalQualifier(SqlWriter writer,
    SqlIntervalQualifier qualifier, RelDataTypeSystem typeSystem) {

  // DB2 supported qualifiers. Singular form of these keywords are also acceptable.
  // YEAR/YEARS
  // MONTH/MONTHS
  // DAY/DAYS
  // HOUR/HOURS
  // MINUTE/MINUTES
  // SECOND/SECONDS

  switch (qualifier.timeUnitRange) {
  case YEAR:
  case MONTH:
  case DAY:
  case HOUR:
  case MINUTE:
  case SECOND:
  case MICROSECOND:
    final String timeUnit = qualifier.timeUnitRange.startUnit.name();
    writer.keyword(timeUnit);
    break;
  default:
    throw new AssertionError("Unsupported type: " + qualifier.timeUnitRange);
  }

  if (null != qualifier.timeUnitRange.endUnit) {
    throw new AssertionError("Unsupported end unit: "
        + qualifier.timeUnitRange.endUnit);
  }
}
 
Example 20
Source Project: Bats   Source File: SqlIntervalQualifier.java    License: Apache License 2.0 5 votes vote down vote up
public static int combineFractionalSecondPrecisionPreservingDefault(
    RelDataTypeSystem typeSystem,
    SqlIntervalQualifier qual1,
    SqlIntervalQualifier qual2) {
  final int p1 = qual1.getFractionalSecondPrecision(typeSystem);
  final int p2 = qual2.getFractionalSecondPrecision(typeSystem);
  if (p1 > p2) {
    // qual1 is more precise, but if it has the default indicator
    // set, we need to return that indicator so result will also
    // use default
    return qual1.getFractionalSecondPrecisionPreservingDefault();
  } else if (p1 < p2) {
    // qual2 is more precise, but if it has the default indicator
    // set, we need to return that indicator so result will also
    // use default
    return qual2.getFractionalSecondPrecisionPreservingDefault();
  } else {
    // they are equal.  return default if both are default,
    // otherwise return exact precision
    if (qual1.useDefaultFractionalSecondPrecision()
        && qual2.useDefaultFractionalSecondPrecision()) {
      return qual1.getFractionalSecondPrecisionPreservingDefault();
    } else {
      return p1;
    }
  }
}
 
Example 21
Source Project: Bats   Source File: SqlIntervalQualifier.java    License: 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 22
Source Project: calcite   Source File: MysqlSqlDialect.java    License: 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 23
Source Project: calcite   Source File: RexBuilderTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Test RexBuilder.ensureType()
 */
@Test void testEnsureTypeWithAny() {
  final RelDataTypeFactory typeFactory = new SqlTypeFactoryImpl(RelDataTypeSystem.DEFAULT);
  RexBuilder builder = new RexBuilder(typeFactory);

  RexNode node =  new RexLiteral(
          Boolean.TRUE, typeFactory.createSqlType(SqlTypeName.BOOLEAN), SqlTypeName.BOOLEAN);
  RexNode ensuredNode = builder.ensureType(
          typeFactory.createSqlType(SqlTypeName.ANY), node, true);

  assertEquals(node, ensuredNode);
}
 
Example 24
Source Project: Bats   Source File: SqlIntervalQualifier.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Validates an INTERVAL literal against a DAY interval qualifier.
 *
 * @throws org.apache.calcite.util.CalciteContextException if the interval
 * value is illegal
 */
private int[] evaluateIntervalLiteralAsDay(
    RelDataTypeSystem typeSystem, int sign,
    String value,
    String originalValue,
    SqlParserPos pos) {
  BigDecimal day;

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

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

    // Validate individual fields
    checkLeadFieldInRange(typeSystem, sign, day, TimeUnit.DAY, pos);

    // package values up for return
    return fillIntervalValueArray(sign, day, ZERO, ZERO, ZERO, ZERO);
  } else {
    throw invalidValueException(pos, originalValue);
  }
}
 
Example 25
Source Project: calcite   Source File: SqlIntervalQualifier.java    License: 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 26
Source Project: Bats   Source File: SqlIntervalQualifier.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Validates an INTERVAL literal against an HOUR interval qualifier.
 *
 * @throws org.apache.calcite.util.CalciteContextException if the interval
 * value is illegal
 */
private int[] evaluateIntervalLiteralAsHour(
    RelDataTypeSystem typeSystem, int sign,
    String value,
    String originalValue,
    SqlParserPos pos) {
  BigDecimal hour;

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

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

    // Validate individual fields
    checkLeadFieldInRange(typeSystem, sign, hour, TimeUnit.HOUR, pos);

    // package values up for return
    return fillIntervalValueArray(sign, ZERO, hour, ZERO, ZERO, ZERO);
  } else {
    throw invalidValueException(pos, originalValue);
  }
}
 
Example 27
Source Project: calcite   Source File: BigQuerySqlDialect.java    License: Apache License 2.0 5 votes vote down vote up
@Override public void unparseSqlIntervalQualifier(
        SqlWriter writer, SqlIntervalQualifier qualifier, RelDataTypeSystem typeSystem) {
  final String start = validate(qualifier.timeUnitRange.startUnit).name();
  if (qualifier.timeUnitRange.endUnit == null) {
    writer.keyword(start);
  } else {
    throw new RuntimeException("Range time unit is not supported for BigQuery.");
  }
}
 
Example 28
Source Project: calcite   Source File: SqlOperatorBindingTest.java    License: Apache License 2.0 5 votes vote down vote up
@BeforeEach
public void setUp() {
  JavaTypeFactory typeFactory = new JavaTypeFactoryImpl(RelDataTypeSystem.DEFAULT);
  integerDataType = typeFactory.createSqlType(SqlTypeName.INTEGER);
  integerType = SqlTypeUtil.convertTypeToSpec(integerDataType);
  rexBuilder = new RexBuilder(typeFactory);
}
 
Example 29
Source Project: Bats   Source File: Db2SqlDialect.java    License: Apache License 2.0 5 votes vote down vote up
@Override public void unparseSqlIntervalQualifier(SqlWriter writer,
    SqlIntervalQualifier qualifier, RelDataTypeSystem typeSystem) {

  // DB2 supported qualifiers. Singular form of these keywords are also acceptable.
  // YEAR/YEARS
  // MONTH/MONTHS
  // DAY/DAYS
  // HOUR/HOURS
  // MINUTE/MINUTES
  // SECOND/SECONDS

  switch (qualifier.timeUnitRange) {
  case YEAR:
  case MONTH:
  case DAY:
  case HOUR:
  case MINUTE:
  case SECOND:
  case MICROSECOND:
    final String timeUnit = qualifier.timeUnitRange.startUnit.name();
    writer.keyword(timeUnit);
    break;
  default:
    throw new AssertionError("Unsupported type: " + qualifier.timeUnitRange);
  }

  if (null != qualifier.timeUnitRange.endUnit) {
    throw new AssertionError("Unsupported end unit: "
        + qualifier.timeUnitRange.endUnit);
  }
}
 
Example 30
Source Project: Bats   Source File: MssqlSqlDialect.java    License: Apache License 2.0 5 votes vote down vote up
private void unparseSqlIntervalLiteralMssql(
    SqlWriter writer, SqlIntervalLiteral literal, int sign) {
  final SqlIntervalLiteral.IntervalValue interval =
      (SqlIntervalLiteral.IntervalValue) literal.getValue();
  unparseSqlIntervalQualifier(writer, interval.getIntervalQualifier(),
      RelDataTypeSystem.DEFAULT);
  writer.sep(",", true);
  if (interval.getSign() * sign == -1) {
    writer.print("-");
  }
  writer.literal(literal.getValue().toString());
}