org.apache.calcite.sql.type.SqlTypeFactoryImpl Java Examples

The following examples show how to use org.apache.calcite.sql.type.SqlTypeFactoryImpl. 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#visitRangeRef(RexRangeRef)} */
@Test void testCopyRangeRef() {
  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 RexRangeRef node = builder.makeRangeReference(type, 1, true);
  final RexNode copy = builder.copy(node);
  assertTrue(copy instanceof RexRangeRef);

  final RexRangeRef result = (RexRangeRef) copy;
  assertThat(result.getOffset(), is(node.getOffset()));
  assertThat(result.getType().getSqlTypeName(), is(SqlTypeName.VARCHAR));
  assertThat(result.getType().getPrecision(), is(PRECISION));
}
 
Example #2
Source File: RexBuilderTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
/** Tests {@link RexCopier#visitDynamicParam(RexDynamicParam)} */
@Test void testCopyDynamicParam() {
  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 RexDynamicParam node = builder.makeDynamicParam(type, 0);
  final RexNode copy = builder.copy(node);
  assertTrue(copy instanceof RexDynamicParam);

  final RexDynamicParam result = (RexDynamicParam) copy;
  assertThat(result.getIndex(), is(node.getIndex()));
  assertThat(result.getType().getSqlTypeName(), is(SqlTypeName.VARCHAR));
  assertThat(result.getType().getPrecision(), is(PRECISION));
}
 
Example #3
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 #4
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 #5
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 #6
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 #7
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 #8
Source File: RexBuilderTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
/**
 * Test RexBuilder.ensureType()
 */
@Test void testEnsureTypeWithItself() {
  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.BOOLEAN), node, true);

  assertEquals(node, ensuredNode);
}
 
Example #9
Source File: KafkaRowConverterTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
/**
 * Generate row schema for a given Kafka topic.
 *
 * @param topicName, Kafka topic name;
 * @return row type
 */
@Override public RelDataType rowDataType(final String topicName) {
  final RelDataTypeFactory typeFactory =
      new SqlTypeFactoryImpl(RelDataTypeSystem.DEFAULT);
  final RelDataTypeFactory.Builder fieldInfo = typeFactory.builder();
  fieldInfo.add("TOPIC_NAME", typeFactory.createSqlType(SqlTypeName.VARCHAR)).nullable(false);
  fieldInfo.add("PARTITION_ID", typeFactory.createSqlType(SqlTypeName.INTEGER)).nullable(false);
  fieldInfo.add("TIMESTAMP_TYPE", typeFactory.createSqlType(SqlTypeName.VARCHAR)).nullable(true);

  return fieldInfo.build();
}
 
Example #10
Source File: KafkaRowConverterImpl.java    From calcite with Apache License 2.0 5 votes vote down vote up
/**
 * Generate row schema for a given Kafka topic.
 *
 * @param topicName, Kafka topic name;
 * @return row type
 */
@Override public RelDataType rowDataType(final String topicName) {
  final RelDataTypeFactory typeFactory =
      new SqlTypeFactoryImpl(RelDataTypeSystem.DEFAULT);
  final RelDataTypeFactory.Builder fieldInfo = typeFactory.builder();
  fieldInfo.add("MSG_PARTITION", typeFactory.createSqlType(SqlTypeName.INTEGER)).nullable(false);
  fieldInfo.add("MSG_TIMESTAMP", typeFactory.createSqlType(SqlTypeName.BIGINT)).nullable(false);
  fieldInfo.add("MSG_OFFSET", typeFactory.createSqlType(SqlTypeName.BIGINT)).nullable(false);
  fieldInfo.add("MSG_KEY_BYTES", typeFactory.createSqlType(SqlTypeName.VARBINARY)).nullable(true);
  fieldInfo.add("MSG_VALUE_BYTES", typeFactory.createSqlType(SqlTypeName.VARBINARY))
      .nullable(false);

  return fieldInfo.build();
}
 
Example #11
Source File: RexBuilderTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** Tests {@link RexCopier#visitOver(RexOver)} */
@Test void testCopyOver() {
  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 RexOver node = (RexOver) builder.makeOver(type,
      SqlStdOperatorTable.COUNT,
      ImmutableList.of(builder.makeInputRef(type, 0)),
      ImmutableList.of(builder.makeInputRef(type, 1)),
      ImmutableList.of(
          new RexFieldCollation(
              builder.makeInputRef(type, 2), ImmutableSet.of())),
      RexWindowBounds.UNBOUNDED_PRECEDING,
      RexWindowBounds.CURRENT_ROW,
      true, true, false, false, false);
  final RexNode copy = builder.copy(node);
  assertTrue(copy instanceof RexOver);

  RexOver result = (RexOver) copy;
  assertThat(result.getType().getSqlTypeName(), is(SqlTypeName.VARCHAR));
  assertThat(result.getType().getPrecision(), is(PRECISION));
  assertThat(result.getWindow(), is(node.getWindow()));
  assertThat(result.getAggOperator(), is(node.getAggOperator()));
  assertThat(result.getAggOperator(), is(node.getAggOperator()));
  assertEquals(node.isDistinct(), result.isDistinct());
  assertEquals(node.ignoreNulls(), result.ignoreNulls());
  for (int i = 0; i < node.getOperands().size(); i++) {
    assertThat(result.getOperands().get(i).getType().getSqlTypeName(),
        is(node.getOperands().get(i).getType().getSqlTypeName()));
    assertThat(result.getOperands().get(i).getType().getPrecision(),
        is(PRECISION));
  }
}
 
Example #12
Source File: RexBuilderTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** Tests {@link RexBuilder#makeExactLiteral(java.math.BigDecimal)}. */
@Test void testBigDecimalLiteral() {
  final RelDataTypeFactory typeFactory =
      new SqlTypeFactoryImpl(RelDataTypeSystem.DEFAULT);
  final RexBuilder builder = new RexBuilder(typeFactory);
  checkBigDecimalLiteral(builder, "25");
  checkBigDecimalLiteral(builder, "9.9");
  checkBigDecimalLiteral(builder, "0");
  checkBigDecimalLiteral(builder, "-75.5");
  checkBigDecimalLiteral(builder, "10000000");
  checkBigDecimalLiteral(builder, "100000.111111111111111111");
  checkBigDecimalLiteral(builder, "-100000.111111111111111111");
  checkBigDecimalLiteral(builder, "73786976294838206464"); // 2^66
  checkBigDecimalLiteral(builder, "-73786976294838206464");
}
 
Example #13
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 #14
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-2306">[CALCITE-2306]
 * AssertionError in {@link RexLiteral#getValue3} with null literal of type
 * DECIMAL</a>. */
@Test void testDecimalLiteral() {
  final RelDataTypeFactory typeFactory =
      new SqlTypeFactoryImpl(RelDataTypeSystem.DEFAULT);
  final RelDataType type = typeFactory.createSqlType(SqlTypeName.DECIMAL);
  final RexBuilder builder = new RexBuilder(typeFactory);
  final RexLiteral literal = builder.makeExactLiteral(null, type);
  assertThat(literal.getValue3(), nullValue());
}
 
Example #15
Source File: RexBuilderTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
/**
 * Test RexBuilder.ensureType()
 */
@Test void testEnsureTypeWithDifference() {
  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.INTEGER), node, true);

  assertNotEquals(node, ensuredNode);
  assertEquals(ensuredNode.getType(), typeFactory.createSqlType(SqlTypeName.INTEGER));
}
 
Example #16
Source File: RelOptUtilTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Test void testTypeDump() {
  RelDataTypeFactory typeFactory =
      new SqlTypeFactoryImpl(RelDataTypeSystem.DEFAULT);
  RelDataType t1 =
      typeFactory.builder()
          .add("f0", SqlTypeName.DECIMAL, 5, 2)
          .add("f1", SqlTypeName.VARCHAR, 10)
          .build();
  TestUtil.assertEqualsVerbose(
      TestUtil.fold(
          "f0 DECIMAL(5, 2) NOT NULL,",
          "f1 VARCHAR(10) NOT NULL"),
      Util.toLinux(RelOptUtil.dumpType(t1) + "\n"));

  RelDataType t2 =
      typeFactory.builder()
          .add("f0", t1)
          .add("f1", typeFactory.createMultisetType(t1, -1))
          .build();
  TestUtil.assertEqualsVerbose(
      TestUtil.fold(
          "f0 RECORD (",
          "  f0 DECIMAL(5, 2) NOT NULL,",
          "  f1 VARCHAR(10) NOT NULL) NOT NULL,",
          "f1 RECORD (",
          "  f0 DECIMAL(5, 2) NOT NULL,",
          "  f1 VARCHAR(10) NOT NULL) NOT NULL MULTISET NOT NULL"),
      Util.toLinux(RelOptUtil.dumpType(t2) + "\n"));
}
 
Example #17
Source File: KylinRelDataTypeSystemTest.java    From kylin-on-parquet-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testLegalDecimalType() {
    RelDataTypeSystem typeSystem = new KylinRelDataTypeSystem();
    RelDataTypeFactory typeFactory = new SqlTypeFactoryImpl(typeSystem);
    
    DataType dataType = DataType.getType("decimal(30, 10)");
    RelDataType relDataType = OLAPTable.createSqlType(typeFactory, dataType, true);
    
    Assert.assertTrue(relDataType instanceof BasicSqlType);
    Assert.assertEquals(relDataType.getSqlTypeName(), SqlTypeName.DECIMAL);
    Assert.assertEquals(relDataType.getPrecision(), 30);
    Assert.assertTrue(relDataType.getPrecision() <= typeSystem.getMaxNumericPrecision());
    Assert.assertEquals(relDataType.getScale(), 10);
    Assert.assertTrue(relDataType.getScale() <= typeSystem.getMaxNumericScale());
}
 
Example #18
Source File: KylinRelDataTypeSystemTest.java    From kylin-on-parquet-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testIllegalDecimalType() {
    RelDataTypeSystem typeSystem = new KylinRelDataTypeSystem();
    RelDataTypeFactory typeFactory = new SqlTypeFactoryImpl(typeSystem);
    
    DataType dataType = DataType.getType("decimal(40, 10)");
    RelDataType relDataType = OLAPTable.createSqlType(typeFactory, dataType, true);
    
    Assert.assertTrue(relDataType instanceof BasicSqlType);
    Assert.assertEquals(relDataType.getSqlTypeName(), SqlTypeName.DECIMAL);
    Assert.assertTrue(typeSystem.getMaxNumericPrecision() < 40);
    Assert.assertEquals(relDataType.getPrecision(), typeSystem.getMaxNumericPrecision());
    Assert.assertEquals(relDataType.getScale(), 10);
    Assert.assertTrue(relDataType.getScale() <= typeSystem.getMaxNumericScale());
}
 
Example #19
Source File: JournalledJdbcSchema.java    From calcite-sql-rewriter with Apache License 2.0 5 votes vote down vote up
@Override
RelProtoDataType getRelDataType(
		DatabaseMetaData metaData,
		String catalogName,
		String schemaName,
		String tableName
) throws SQLException {
	if (journalledTableKeys.containsKey(tableName)) {
		// 1: Find columns for journal table
		RelDataType relDataType = super
				.getRelDataType(metaData, catalogName, schemaName, journalNameFor(tableName))
				.apply(new SqlTypeFactoryImpl(RelDataTypeSystem.DEFAULT) {
					@Override
					public RelDataType copyType(RelDataType type) {
						return type;
					}
				});

		RelDataTypeFactory.FieldInfoBuilder fieldInfo = new SqlTypeFactoryImpl(RelDataTypeSystem.DEFAULT).builder();

		// 2: Filter out journal-implementation columns
		for (RelDataTypeField field : relDataType.getFieldList()) {
			String fieldName = field.getName();
			if (fieldName.equals(versionField) || fieldName.equals(subsequentVersionField)) {
				continue;
			}
			fieldInfo.add(field);
		}

		return RelDataTypeImpl.proto(fieldInfo.build());
	} else {
		return super.getRelDataType(metaData, catalogName, schemaName, tableName);
	}
}
 
Example #20
Source File: KylinRelDataTypeSystemTest.java    From kylin with Apache License 2.0 5 votes vote down vote up
@Test
public void testLegalDecimalType() {
    RelDataTypeSystem typeSystem = new KylinRelDataTypeSystem();
    RelDataTypeFactory typeFactory = new SqlTypeFactoryImpl(typeSystem);
    
    DataType dataType = DataType.getType("decimal(30, 10)");
    RelDataType relDataType = OLAPTable.createSqlType(typeFactory, dataType, true);
    
    Assert.assertTrue(relDataType instanceof BasicSqlType);
    Assert.assertEquals(relDataType.getSqlTypeName(), SqlTypeName.DECIMAL);
    Assert.assertEquals(relDataType.getPrecision(), 30);
    Assert.assertTrue(relDataType.getPrecision() <= typeSystem.getMaxNumericPrecision());
    Assert.assertEquals(relDataType.getScale(), 10);
    Assert.assertTrue(relDataType.getScale() <= typeSystem.getMaxNumericScale());
}
 
Example #21
Source File: KylinRelDataTypeSystemTest.java    From kylin with Apache License 2.0 5 votes vote down vote up
@Test
public void testIllegalDecimalType() {
    RelDataTypeSystem typeSystem = new KylinRelDataTypeSystem();
    RelDataTypeFactory typeFactory = new SqlTypeFactoryImpl(typeSystem);
    
    DataType dataType = DataType.getType("decimal(40, 10)");
    RelDataType relDataType = OLAPTable.createSqlType(typeFactory, dataType, true);
    
    Assert.assertTrue(relDataType instanceof BasicSqlType);
    Assert.assertEquals(relDataType.getSqlTypeName(), SqlTypeName.DECIMAL);
    Assert.assertTrue(typeSystem.getMaxNumericPrecision() < 40);
    Assert.assertEquals(relDataType.getPrecision(), typeSystem.getMaxNumericPrecision());
    Assert.assertEquals(relDataType.getScale(), 10);
    Assert.assertTrue(relDataType.getScale() <= typeSystem.getMaxNumericScale());
}
 
Example #22
Source File: GeodeEnumerator.java    From calcite with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a GeodeEnumerator.
 *
 * @param results      Geode result set ({@link SelectResults})
 * @param protoRowType The type of resulting rows
 */
GeodeEnumerator(SelectResults results, RelProtoDataType protoRowType) {
  if (results == null) {
    LOGGER.warn("Null OQL results!");
  }
  this.iterator = (results == null) ? Collections.emptyIterator() : results.iterator();
  this.current = null;

  final RelDataTypeFactory typeFactory =
      new SqlTypeFactoryImpl(RelDataTypeSystem.DEFAULT);
  this.fieldTypes = protoRowType.apply(typeFactory).getFieldList();
}
 
Example #23
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 #24
Source File: JdbcSchema.java    From calcite with Apache License 2.0 5 votes vote down vote up
RelProtoDataType getRelDataType(DatabaseMetaData metaData, String catalogName,
    String schemaName, String tableName) throws SQLException {
  final ResultSet resultSet =
      metaData.getColumns(catalogName, schemaName, tableName, null);

  // Temporary type factory, just for the duration of this method. Allowable
  // because we're creating a proto-type, not a type; before being used, the
  // proto-type will be copied into a real type factory.
  final RelDataTypeFactory typeFactory =
      new SqlTypeFactoryImpl(RelDataTypeSystem.DEFAULT);
  final RelDataTypeFactory.Builder fieldInfo = typeFactory.builder();
  while (resultSet.next()) {
    final String columnName = resultSet.getString(4);
    final int dataType = resultSet.getInt(5);
    final String typeString = resultSet.getString(6);
    final int precision;
    final int scale;
    switch (SqlType.valueOf(dataType)) {
    case TIMESTAMP:
    case TIME:
      precision = resultSet.getInt(9); // SCALE
      scale = 0;
      break;
    default:
      precision = resultSet.getInt(7); // SIZE
      scale = resultSet.getInt(9); // SCALE
      break;
    }
    RelDataType sqlType =
        sqlType(typeFactory, dataType, precision, scale, typeString);
    boolean nullable = resultSet.getInt(11) != DatabaseMetaData.columnNoNulls;
    fieldInfo.add(columnName, sqlType).nullable(nullable);
  }
  resultSet.close();
  return RelDataTypeImpl.proto(fieldInfo.build());
}
 
Example #25
Source File: RexBuilderTest.java    From calcite with 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 #26
Source File: MatchTest.java    From calcite with Apache License 2.0 4 votes vote down vote up
/**
 * Tests the ElasticSearch match query. The match query is translated from
 * CONTAINS query which is build using RelBuilder, RexBuilder because the
 * normal SQL query assumes CONTAINS query is for date/period range.
 *
 * <p>Equivalent SQL query:
 *
 * <blockquote>
 * <code>select * from zips where city contains 'waltham'</code>
 * </blockquote>
 *
 * <p>ElasticSearch query for it:
 *
 * <blockquote><code>
 * {"query":{"constant_score":{"filter":{"match":{"city":"waltham"}}}}}
 * </code></blockquote>
 */
@Test void testMatchQuery() throws Exception {

  CalciteConnection con = (CalciteConnection) newConnectionFactory()
      .createConnection();
  SchemaPlus postSchema = con.getRootSchema().getSubSchema("elastic");

  FrameworkConfig postConfig = Frameworks.newConfigBuilder()
      .parserConfig(SqlParser.Config.DEFAULT)
      .defaultSchema(postSchema)
      .build();

  final RelBuilder builder = RelBuilder.create(postConfig);
  builder.scan(ZIPS);

  final RelDataTypeFactory typeFactory =
      new SqlTypeFactoryImpl(RelDataTypeSystem.DEFAULT);
  final RexBuilder rexBuilder = new RexBuilder(typeFactory);

  RexNode nameRexNode = rexBuilder.makeCall(SqlStdOperatorTable.ITEM,
      rexBuilder.makeInputRef(typeFactory.createSqlType(SqlTypeName.ANY), 0),
      rexBuilder.makeCharLiteral(
          new NlsString("city", typeFactory.getDefaultCharset().name(),
              SqlCollation.COERCIBLE)));

  RelDataType mapType = typeFactory.createMapType(
      typeFactory.createSqlType(SqlTypeName.VARCHAR),
      typeFactory.createTypeWithNullability(
          typeFactory.createSqlType(SqlTypeName.ANY), true));

  List<RexNode> namedList =
      ImmutableList.of(rexBuilder.makeInputRef(mapType, 0),
          nameRexNode);

  // Add fields in builder stack so it is accessible while filter preparation
  builder.projectNamed(namedList, Arrays.asList("_MAP", "city"), true);

  RexNode filterRexNode = builder
      .call(SqlStdOperatorTable.CONTAINS, builder.field("city"),
          builder.literal("waltham"));
  builder.filter(filterRexNode);

  String builderExpected = ""
      + "LogicalFilter(condition=[CONTAINS($1, 'waltham')])\n"
      + "  LogicalProject(_MAP=[$0], city=[ITEM($0, 'city')])\n"
      + "    ElasticsearchTableScan(table=[[elastic, " + ZIPS + "]])\n";

  RelNode root = builder.build();

  RelRunner ru = (RelRunner) con.unwrap(Class.forName("org.apache.calcite.tools.RelRunner"));
  try (PreparedStatement preparedStatement = ru.prepare(root)) {

    String s = CalciteAssert.toString(preparedStatement.executeQuery());
    final String result = ""
        + "_MAP={id=02154, city=NORTH WALTHAM, loc=[-71.236497, 42.382492], "
        + "pop=57871, state=MA}; city=NORTH WALTHAM\n";

    // Validate query prepared
    assertThat(root, hasTree(builderExpected));

    // Validate result returned from ES
    assertThat(s, is(result));
  }
}
 
Example #27
Source File: RexBuilderTest.java    From calcite with Apache License 2.0 4 votes vote down vote up
/**
 * Test string literal encoding.
 */
@Test void testStringLiteral() {
  final RelDataTypeFactory typeFactory =
      new SqlTypeFactoryImpl(RelDataTypeSystem.DEFAULT);
  final RelDataType varchar =
      typeFactory.createSqlType(SqlTypeName.VARCHAR);
  final RexBuilder builder = new RexBuilder(typeFactory);

  final NlsString latin1 = new NlsString("foobar", "LATIN1", SqlCollation.IMPLICIT);
  final NlsString utf8 = new NlsString("foobar", "UTF8", SqlCollation.IMPLICIT);

  RexNode literal = builder.makePreciseStringLiteral("foobar");
  assertEquals("'foobar'", literal.toString());
  literal = builder.makePreciseStringLiteral(
      new ByteString(new byte[] { 'f', 'o', 'o', 'b', 'a', 'r'}),
      "UTF8",
      SqlCollation.IMPLICIT);
  assertEquals("_UTF8'foobar'", literal.toString());
  assertEquals("_UTF8'foobar':CHAR(6) CHARACTER SET \"UTF-8\"",
      ((RexLiteral) literal).computeDigest(RexDigestIncludeType.ALWAYS));
  literal = builder.makePreciseStringLiteral(
      new ByteString("\u82f1\u56fd".getBytes(StandardCharsets.UTF_8)),
      "UTF8",
      SqlCollation.IMPLICIT);
  assertEquals("_UTF8'\u82f1\u56fd'", literal.toString());
  // Test again to check decode cache.
  literal = builder.makePreciseStringLiteral(
      new ByteString("\u82f1".getBytes(StandardCharsets.UTF_8)),
      "UTF8",
      SqlCollation.IMPLICIT);
  assertEquals("_UTF8'\u82f1'", literal.toString());
  try {
    literal = builder.makePreciseStringLiteral(
        new ByteString("\u82f1\u56fd".getBytes(StandardCharsets.UTF_8)),
        "GB2312",
        SqlCollation.IMPLICIT);
    fail("expected exception, got " + literal);
  } catch (RuntimeException e) {
    assertThat(e.getMessage(), containsString("Failed to encode"));
  }
  literal = builder.makeLiteral(latin1, varchar, false);
  assertEquals("_LATIN1'foobar'", literal.toString());
  literal = builder.makeLiteral(utf8, varchar, false);
  assertEquals("_UTF8'foobar'", literal.toString());
}
 
Example #28
Source File: SqlToRelTestBase.java    From calcite with Apache License 2.0 4 votes vote down vote up
protected RelDataTypeFactory createTypeFactory() {
  return new SqlTypeFactoryImpl(RelDataTypeSystem.DEFAULT);
}
 
Example #29
Source File: RexBuilderTest.java    From calcite with Apache License 2.0 4 votes vote down vote up
/** Tests {@link RexBuilder#makeTimeLiteral(TimeString, int)}. */
@Test void testTimeLiteral() {
  final RelDataTypeFactory typeFactory =
      new SqlTypeFactoryImpl(RelDataTypeSystem.DEFAULT);
  RelDataType timeType = typeFactory.createSqlType(SqlTypeName.TIME);
  final RelDataType timeType3 =
      typeFactory.createSqlType(SqlTypeName.TIME, 3);
  final RelDataType timeType9 =
      typeFactory.createSqlType(SqlTypeName.TIME, 9);
  final RelDataType timeType18 =
      typeFactory.createSqlType(SqlTypeName.TIME, 18);
  final RexBuilder builder = new RexBuilder(typeFactory);

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

  // Old way #2: Provide a Long
  checkTime(builder.makeLiteral(MOON_TIME, timeType, false));

  // The new way
  final TimeString t = new TimeString(2, 56, 15);
  assertThat(t.getMillisOfDay(), is(10575000));
  checkTime(builder.makeLiteral(t, timeType, false));

  // Now with milliseconds
  final TimeString t2 = t.withMillis(56);
  assertThat(t2.getMillisOfDay(), is(10575056));
  assertThat(t2.toString(), is("02:56:15.056"));
  final RexNode literal2 = builder.makeLiteral(t2, timeType3, false);
  assertThat(((RexLiteral) literal2).getValueAs(TimeString.class)
      .toString(), is("02:56:15.056"));

  // Now with nanoseconds
  final TimeString t3 = t.withNanos(2345678);
  assertThat(t3.getMillisOfDay(), is(10575002));
  final RexNode literal3 = builder.makeLiteral(t3, timeType9, false);
  assertThat(((RexLiteral) literal3).getValueAs(TimeString.class)
      .toString(), is("02:56:15.002"));

  // Now with a very long fraction
  final TimeString t4 = t.withFraction("102030405060708090102");
  assertThat(t4.getMillisOfDay(), is(10575102));
  final RexNode literal4 = builder.makeLiteral(t4, timeType18, false);
  assertThat(((RexLiteral) literal4).getValueAs(TimeString.class)
      .toString(), is("02:56:15.102"));

  // toString
  assertThat(t2.round(1).toString(), is("02:56:15"));
  assertThat(t2.round(2).toString(), is("02:56:15.05"));
  assertThat(t2.round(3).toString(), is("02:56:15.056"));
  assertThat(t2.round(4).toString(), is("02:56:15.056"));

  assertThat(t2.toString(6), is("02:56:15.056000"));
  assertThat(t2.toString(1), is("02:56:15.0"));
  assertThat(t2.toString(0), is("02:56:15"));

  assertThat(t2.round(0).toString(), is("02:56:15"));
  assertThat(t2.round(0).toString(0), is("02:56:15"));
  assertThat(t2.round(0).toString(1), is("02:56:15.0"));
  assertThat(t2.round(0).toString(2), is("02:56:15.00"));

  assertThat(TimeString.fromMillisOfDay(53560123).toString(),
      is("14:52:40.123"));
}
 
Example #30
Source File: RexBuilderTest.java    From calcite with Apache License 2.0 4 votes vote down vote up
/** Tests
 * {@link RexBuilder#makeTimestampWithLocalTimeZoneLiteral(TimestampString, int)}. */
@Test void testTimestampWithLocalTimeZoneLiteral() {
  final RelDataTypeFactory typeFactory =
      new SqlTypeFactoryImpl(RelDataTypeSystem.DEFAULT);
  final RelDataType timestampType =
      typeFactory.createSqlType(SqlTypeName.TIMESTAMP_WITH_LOCAL_TIME_ZONE);
  final RelDataType timestampType3 =
      typeFactory.createSqlType(SqlTypeName.TIMESTAMP_WITH_LOCAL_TIME_ZONE, 3);
  final RelDataType timestampType9 =
      typeFactory.createSqlType(SqlTypeName.TIMESTAMP_WITH_LOCAL_TIME_ZONE, 9);
  final RelDataType timestampType18 =
      typeFactory.createSqlType(SqlTypeName.TIMESTAMP_WITH_LOCAL_TIME_ZONE, 18);
  final RexBuilder builder = new RexBuilder(typeFactory);

  // The new way
  final TimestampWithTimeZoneString ts = new TimestampWithTimeZoneString(
      1969, 7, 21, 2, 56, 15, TimeZone.getTimeZone("PST").getID());
  checkTimestampWithLocalTimeZone(
      builder.makeLiteral(ts.getLocalTimestampString(), timestampType, false));

  // Now with milliseconds
  final TimestampWithTimeZoneString ts2 = ts.withMillis(56);
  assertThat(ts2.toString(), is("1969-07-21 02:56:15.056 PST"));
  final RexNode literal2 = builder.makeLiteral(
      ts2.getLocalTimestampString(), timestampType3, false);
  assertThat(((RexLiteral) literal2).getValue().toString(), is("1969-07-21 02:56:15.056"));

  // Now with nanoseconds
  final TimestampWithTimeZoneString ts3 = ts.withNanos(56);
  final RexNode literal3 = builder.makeLiteral(
      ts3.getLocalTimestampString(), timestampType9, false);
  assertThat(((RexLiteral) literal3).getValueAs(TimestampString.class)
          .toString(), is("1969-07-21 02:56:15"));
  final TimestampWithTimeZoneString ts3b = ts.withNanos(2345678);
  final RexNode literal3b = builder.makeLiteral(
      ts3b.getLocalTimestampString(), timestampType9, false);
  assertThat(((RexLiteral) literal3b).getValueAs(TimestampString.class)
          .toString(), is("1969-07-21 02:56:15.002"));

  // Now with a very long fraction
  final TimestampWithTimeZoneString ts4 = ts.withFraction("102030405060708090102");
  final RexNode literal4 = builder.makeLiteral(
      ts4.getLocalTimestampString(), timestampType18, false);
  assertThat(((RexLiteral) literal4).getValueAs(TimestampString.class)
          .toString(), is("1969-07-21 02:56:15.102"));

  // toString
  assertThat(ts2.round(1).toString(), is("1969-07-21 02:56:15 PST"));
  assertThat(ts2.round(2).toString(), is("1969-07-21 02:56:15.05 PST"));
  assertThat(ts2.round(3).toString(), is("1969-07-21 02:56:15.056 PST"));
  assertThat(ts2.round(4).toString(), is("1969-07-21 02:56:15.056 PST"));

  assertThat(ts2.toString(6), is("1969-07-21 02:56:15.056000 PST"));
  assertThat(ts2.toString(1), is("1969-07-21 02:56:15.0 PST"));
  assertThat(ts2.toString(0), is("1969-07-21 02:56:15 PST"));

  assertThat(ts2.round(0).toString(), is("1969-07-21 02:56:15 PST"));
  assertThat(ts2.round(0).toString(0), is("1969-07-21 02:56:15 PST"));
  assertThat(ts2.round(0).toString(1), is("1969-07-21 02:56:15.0 PST"));
  assertThat(ts2.round(0).toString(2), is("1969-07-21 02:56:15.00 PST"));
}