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

The following examples show how to use org.apache.calcite.rel.type.RelDataTypeSystem. 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: RexBuilderTest.java    From calcite with 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 #2
Source File: MssqlSqlDialect.java    From calcite with 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 #3
Source File: BasicSqlType.java    From Bats with 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 #4
Source File: MssqlSqlDialect.java    From Bats with 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 File: Frameworks.java    From calcite with 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 #6
Source File: Db2SqlDialect.java    From Bats with 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 #7
Source File: BasicSqlType.java    From calcite with 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 #8
Source File: CalciteCatalogReader.java    From Bats with 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 #9
Source File: RexBuilderTest.java    From calcite with 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 File: QuarkConnectionImpl.java    From quark with 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 #11
Source File: RexBuilderTest.java    From calcite with 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 #12
Source File: SqlWorker.java    From quark with 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 #13
Source File: QuarkMetaImpl.java    From quark with 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 #14
Source File: CalciteCatalogReader.java    From calcite with 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 File: RexBuilderTest.java    From calcite with 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 File: Db2SqlDialect.java    From Bats with 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 #17
Source File: Db2SqlDialect.java    From calcite with 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 #18
Source File: MssqlSqlDialect.java    From Bats with 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());
}
 
Example #19
Source File: CassandraEnumerator.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** Creates a CassandraEnumerator.
 *
 * @param results Cassandra result set ({@link com.datastax.driver.core.ResultSet})
 * @param protoRowType The type of resulting rows
 */
CassandraEnumerator(ResultSet results, RelProtoDataType protoRowType) {
  this.iterator = results.iterator();
  this.current = null;

  final RelDataTypeFactory typeFactory =
      new SqlTypeFactoryImpl(RelDataTypeSystem.DEFAULT);
  this.fieldTypes = protoRowType.apply(typeFactory).getFieldList();
}
 
Example #20
Source File: SqlDialect.java    From calcite with Apache License 2.0 5 votes vote down vote up
public Context withDataTypeSystem(@Nonnull RelDataTypeSystem dataTypeSystem) {
  return new ContextImpl(databaseProduct, databaseProductName,
      databaseVersion, databaseMajorVersion, databaseMinorVersion,
      literalQuoteString, literalEscapedQuoteString,
      identifierQuoteString, quotedCasing, unquotedCasing, caseSensitive,
      conformance, nullCollation, dataTypeSystem, jethroInfo);
}
 
Example #21
Source File: SqlIntervalQualifier.java    From calcite with Apache License 2.0 5 votes vote down vote up
/**
 * Validates an INTERVAL literal against an MINUTE interval qualifier.
 *
 * @throws org.apache.calcite.runtime.CalciteContextException if the interval
 * value is illegal
 */
private int[] evaluateIntervalLiteralAsMinute(
    RelDataTypeSystem typeSystem, int sign,
    String value,
    String originalValue,
    SqlParserPos pos) {
  BigDecimal minute;

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

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

    // Validate individual fields
    checkLeadFieldInRange(typeSystem, sign, minute, TimeUnit.MINUTE, pos);

    // package values up for return
    return fillIntervalValueArray(sign, ZERO, ZERO, minute, ZERO, ZERO);
  } else {
    throw invalidValueException(pos, originalValue);
  }
}
 
Example #22
Source File: SqlOperatorBindingTest.java    From calcite with 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 #23
Source File: IntervalSqlType.java    From Bats with Apache License 2.0 5 votes vote down vote up
/**
 * Constructs an IntervalSqlType. This should only be called from a factory
 * method.
 */
public IntervalSqlType(RelDataTypeSystem typeSystem,
    SqlIntervalQualifier intervalQualifier,
    boolean isNullable) {
  super(intervalQualifier.typeName(), isNullable, null);
  this.typeSystem = Objects.requireNonNull(typeSystem);
  this.intervalQualifier = Objects.requireNonNull(intervalQualifier);
  computeDigest();
}
 
Example #24
Source File: SqlIntervalQualifier.java    From calcite with Apache License 2.0 5 votes vote down vote up
public static int combineStartPrecisionPreservingDefault(
    RelDataTypeSystem typeSystem,
    SqlIntervalQualifier qual1,
    SqlIntervalQualifier qual2) {
  final int start1 = qual1.getStartPrecision(typeSystem);
  final int start2 = qual2.getStartPrecision(typeSystem);
  if (start1 > start2) {
    // 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.getStartPrecisionPreservingDefault();
  } else if (start1 < start2) {
    // 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.getStartPrecisionPreservingDefault();
  } else {
    // they are equal.  return default if both are default,
    // otherwise return exact precision
    if (qual1.useDefaultStartPrecision()
        && qual2.useDefaultStartPrecision()) {
      return qual1.getStartPrecisionPreservingDefault();
    } else {
      return start1;
    }
  }
}
 
Example #25
Source File: CheckerTest.java    From samza with Apache License 2.0 5 votes vote down vote up
@Test
public void testCheckOperandTypesShouldReturnTrueWhenArgumentCheckIsDisabled() throws NoSuchMethodException {
  Method udfMethod = TestUdfWithWrongTypes.class.getMethod("execute", String.class);
  UdfMetadata udfMetadata = new UdfMetadata("TestUdfWithWrongTypes", "TestUDFClass",
          udfMethod, new MapConfig(), ImmutableList.of(SamzaSqlFieldType.INT32), SamzaSqlFieldType.INT64, true);

  Checker operandTypeChecker = Checker.getChecker(1, 3, udfMetadata);

  SqlCallBinding callBinding = Mockito.mock(SqlCallBinding.class);
  Mockito.when(callBinding.getOperandCount()).thenReturn(1);
  Mockito.when(callBinding.getOperandType(0)).thenReturn(new BasicSqlType(RelDataTypeSystem.DEFAULT, SqlTypeName.VARCHAR, 12));

  assertTrue(operandTypeChecker.checkOperandTypes(callBinding, true));
}
 
Example #26
Source File: SqlIntervalQualifier.java    From calcite with Apache License 2.0 5 votes vote down vote up
public int getStartPrecision(RelDataTypeSystem typeSystem) {
  if (startPrecision == RelDataType.PRECISION_NOT_SPECIFIED) {
    return typeSystem.getDefaultPrecision(typeName());
  } else {
    return startPrecision;
  }
}
 
Example #27
Source File: CheckerTest.java    From samza with Apache License 2.0 5 votes vote down vote up
@Test
public void testCheckOperandTypesShouldReturnTrueOnTypeMatch() throws NoSuchMethodException {
  Method udfMethod = MyTestPolyUdf.class.getMethod("execute", String.class);
  UdfMetadata udfMetadata = new UdfMetadata("MyTestPoly", "Test Polymorphism UDF.",
          udfMethod, new MapConfig(), ImmutableList.of(SamzaSqlFieldType.STRING), SamzaSqlFieldType.INT32, false);

  Checker operandTypeChecker = Checker.getChecker(1, 3, udfMetadata);

  SqlCallBinding callBinding = Mockito.mock(SqlCallBinding.class);
  Mockito.when(callBinding.getOperandCount()).thenReturn(1);
  Mockito.when(callBinding.getOperandType(0)).thenReturn(new BasicSqlType(RelDataTypeSystem.DEFAULT, SqlTypeName.VARCHAR, 12));

  assertTrue(operandTypeChecker.checkOperandTypes(callBinding, true));
}
 
Example #28
Source File: CheckerTest.java    From samza with Apache License 2.0 5 votes vote down vote up
@Test(expected = SamzaSqlValidatorException.class)
public void testCheckOperandTypesShouldFailOnTypeMisMatch() throws NoSuchMethodException {
  Method udfMethod = TestUdfWithWrongTypes.class.getMethod("execute", String.class);
  UdfMetadata udfMetadata = new UdfMetadata("TestUdfWithWrongTypes", "TestUDFClass",
          udfMethod, new MapConfig(), ImmutableList.of(SamzaSqlFieldType.INT32), SamzaSqlFieldType.INT64, false);

  Checker operandTypeChecker = Checker.getChecker(1, 3, udfMetadata);

  SqlCallBinding callBinding = Mockito.mock(SqlCallBinding.class);
  Mockito.when(callBinding.getOperandCount()).thenReturn(1);
  Mockito.when(callBinding.getOperandType(0)).thenReturn(new BasicSqlType(RelDataTypeSystem.DEFAULT, SqlTypeName.VARCHAR, 12));

  operandTypeChecker.checkOperandTypes(callBinding, true);
}
 
Example #29
Source File: SqlIntervalQualifier.java    From calcite with Apache License 2.0 5 votes vote down vote up
public int getFractionalSecondPrecision(RelDataTypeSystem typeSystem) {
  if (fractionalSecondPrecision == RelDataType.PRECISION_NOT_SPECIFIED) {
    return typeName().getDefaultScale();
  } else {
    return fractionalSecondPrecision;
  }
}
 
Example #30
Source File: ArrayTableTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Test void testLoadSorted() {
  final JavaTypeFactoryImpl typeFactory =
      new JavaTypeFactoryImpl(RelDataTypeSystem.DEFAULT);
  final RelDataType rowType =
      typeFactory.builder()
          .add("empid", typeFactory.createType(int.class))
          .add("deptno", typeFactory.createType(int.class))
          .add("name", typeFactory.createType(String.class))
          .build();
  final Enumerable<Object[]> enumerable =
      Linq4j.asEnumerable(
          Arrays.asList(
              new Object[]{100, 10, "Bill"},
              new Object[]{200, 20, "Eric"},
              new Object[]{150, 10, "Sebastian"},
              new Object[]{160, 10, "Theodore"}));
  final ColumnLoader<Object[]> loader =
      new ColumnLoader<Object[]>(typeFactory, enumerable,
          RelDataTypeImpl.proto(rowType), null);
  checkColumn(
      loader.representationValues.get(0),
      ArrayTable.RepresentationType.BIT_SLICED_PRIMITIVE_ARRAY,
      "Column(representation=BitSlicedPrimitiveArray(ordinal=0, bitCount=8, primitive=INT, signed=false), value=[100, 150, 160, 200, 0, 0, 0, 0])");
  checkColumn(
      loader.representationValues.get(1),
      ArrayTable.RepresentationType.BIT_SLICED_PRIMITIVE_ARRAY,
      "Column(representation=BitSlicedPrimitiveArray(ordinal=1, bitCount=5, primitive=INT, signed=false), value=[10, 10, 10, 20, 0, 0, 0, 0, 0, 0, 0, 0])");
  checkColumn(
      loader.representationValues.get(2),
      ArrayTable.RepresentationType.OBJECT_ARRAY,
      "Column(representation=ObjectArray(ordinal=2), value=[Bill, Sebastian, Theodore, Eric])");
}