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

The following examples show how to use org.apache.calcite.sql.type.SqlTypeFactoryImpl. 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: 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 2
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 3
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 4
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 5
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 6
Source Project: calcite   Source File: RexBuilderTest.java    License: 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 7
Source Project: calcite   Source File: RexBuilderTest.java    License: 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 8
@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 9
@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 10
Source Project: calcite-sql-rewriter   Source File: JournalledJdbcSchema.java    License: 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 11
Source Project: kylin   Source File: KylinRelDataTypeSystemTest.java    License: 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 12
Source Project: kylin   Source File: KylinRelDataTypeSystemTest.java    License: 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 13
Source Project: calcite   Source File: GeodeEnumerator.java    License: 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 14
Source Project: calcite   Source File: CassandraEnumerator.java    License: 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 15
Source Project: calcite   Source File: JdbcSchema.java    License: 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 16
Source Project: calcite   Source File: RelOptUtilTest.java    License: 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 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 18
Source Project: calcite   Source File: RexBuilderTest.java    License: 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 19
Source Project: calcite   Source File: RexBuilderTest.java    License: 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 20
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-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 21
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 22
Source Project: calcite   Source File: RexBuilderTest.java    License: 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 23
Source Project: calcite   Source File: RexBuilderTest.java    License: 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 24
Source Project: calcite   Source File: KafkaRowConverterImpl.java    License: 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 25
Source Project: calcite   Source File: KafkaRowConverterTest.java    License: 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 26
Source Project: lucene-solr   Source File: SolrSchema.java    License: Apache License 2.0 4 votes vote down vote up
RelProtoDataType getRelDataType(String collection) {
  // 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();
  Map<String, LukeResponse.FieldInfo> luceneFieldInfoMap = getFieldInfo(collection);

  for(Map.Entry<String, LukeResponse.FieldInfo> entry : luceneFieldInfoMap.entrySet()) {
    LukeResponse.FieldInfo luceneFieldInfo = entry.getValue();

    String luceneFieldType = luceneFieldInfo.getType();
    // SOLR-13414: Luke can return a field definition with no type in rare situations
    if(luceneFieldType == null) {
      continue;
    }

    RelDataType type;
    switch (luceneFieldType) {
      case "string":
        type = typeFactory.createJavaType(String.class);
        break;
      case "tint":
      case "tlong":
      case "int":
      case "long":
      case "pint":
      case "plong":
        type = typeFactory.createJavaType(Long.class);
        break;
      case "tfloat":
      case "tdouble":
      case "float":
      case "double":
      case "pfloat":
      case "pdouble":
        type = typeFactory.createJavaType(Double.class);
        break;
      default:
        type = typeFactory.createJavaType(String.class);
    }

    /*
    EnumSet<FieldFlag> flags = luceneFieldInfo.parseFlags(luceneFieldInfo.getSchema());
    if(flags != null && flags.contains(FieldFlag.MULTI_VALUED)) {
      type = typeFactory.createArrayType(type, -1);
    }
    */

    fieldInfo.add(entry.getKey(), type).nullable(true);
  }
  fieldInfo.add("_query_",typeFactory.createJavaType(String.class));
  fieldInfo.add("score",typeFactory.createJavaType(Double.class));

  return RelDataTypeImpl.proto(fieldInfo.build());
}
 
Example 27
Source Project: calcite   Source File: MatchTest.java    License: 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 28
Source Project: calcite   Source File: SqlToRelTestBase.java    License: Apache License 2.0 4 votes vote down vote up
protected RelDataTypeFactory createTypeFactory() {
  return new SqlTypeFactoryImpl(RelDataTypeSystem.DEFAULT);
}
 
Example 29
Source Project: calcite   Source File: PlannerTests.java    License: Apache License 2.0 4 votes vote down vote up
static RelOptCluster newCluster(VolcanoPlanner planner) {
  final RelDataTypeFactory typeFactory =
      new SqlTypeFactoryImpl(org.apache.calcite.rel.type.RelDataTypeSystem.DEFAULT);
  return RelOptCluster.create(planner, new RexBuilder(typeFactory));
}
 
Example 30
Source Project: calcite   Source File: RexBuilderTest.java    License: Apache License 2.0 4 votes vote down vote up
/** Tests {@link RexBuilder#makeTimestampLiteral(TimestampString, int)}. */
@Test void testTimestampLiteral() {
  final RelDataTypeFactory typeFactory =
      new SqlTypeFactoryImpl(RelDataTypeSystem.DEFAULT);
  final RelDataType timestampType =
      typeFactory.createSqlType(SqlTypeName.TIMESTAMP);
  final RelDataType timestampType3 =
      typeFactory.createSqlType(SqlTypeName.TIMESTAMP, 3);
  final RelDataType timestampType9 =
      typeFactory.createSqlType(SqlTypeName.TIMESTAMP, 9);
  final RelDataType timestampType18 =
      typeFactory.createSqlType(SqlTypeName.TIMESTAMP, 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);
  checkTimestamp(builder.makeLiteral(calendar, timestampType, false));

  // Old way #2: Provide a Long
  checkTimestamp(builder.makeLiteral(MOON, timestampType, false));

  // The new way
  final TimestampString ts = new TimestampString(1969, 7, 21, 2, 56, 15);
  checkTimestamp(builder.makeLiteral(ts, timestampType, false));

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

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

  // Now with a very long fraction
  final TimestampString ts4 = ts.withFraction("102030405060708090102");
  final RexNode literal4 = builder.makeLiteral(ts4, 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"));
  assertThat(ts2.round(2).toString(), is("1969-07-21 02:56:15.05"));
  assertThat(ts2.round(3).toString(), is("1969-07-21 02:56:15.056"));
  assertThat(ts2.round(4).toString(), is("1969-07-21 02:56:15.056"));

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

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

  assertThat(TimestampString.fromMillisSinceEpoch(1456513560123L).toString(),
      is("2016-02-26 19:06:00.123"));
}