Java Code Examples for org.apache.calcite.rel.type.RelDataTypeFactory#createSqlType()

The following examples show how to use org.apache.calcite.rel.type.RelDataTypeFactory#createSqlType() . 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 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 2
Source File: SqlNumericLiteral.java    From calcite with Apache License 2.0 6 votes vote down vote up
public RelDataType createSqlType(RelDataTypeFactory typeFactory) {
  if (isExact) {
    int scaleValue = scale.intValue();
    if (0 == scaleValue) {
      BigDecimal bd = (BigDecimal) value;
      SqlTypeName result;
      long l = bd.longValue();
      if ((l >= Integer.MIN_VALUE) && (l <= Integer.MAX_VALUE)) {
        result = SqlTypeName.INTEGER;
      } else {
        result = SqlTypeName.BIGINT;
      }
      return typeFactory.createSqlType(result);
    }

    // else we have a decimal
    return typeFactory.createSqlType(
        SqlTypeName.DECIMAL,
        prec.intValue(),
        scaleValue);
  }

  // else we have a a float, real or double.  make them all double for
  // now.
  return typeFactory.createSqlType(SqlTypeName.DOUBLE);
}
 
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: RecordDataType.java    From Bats with Apache License 2.0 6 votes vote down vote up
/**
 * This method constructs a {@link org.apache.calcite.rel.type.RelDataType} based on the
 * {@link org.apache.drill.exec.store.RecordDataType}'s field sql types and field names.
 *
 * @param factory helps construct a {@link org.apache.calcite.rel.type.RelDataType}
 * @return the constructed type
 */
public final RelDataType getRowType(RelDataTypeFactory factory) {
  final List<SimpleImmutableEntry<SqlTypeName, Boolean>> types = getFieldSqlTypeNames();
  final List<String> names = getFieldNames();
  final List<RelDataType> fields = new ArrayList<>();
  for (SimpleImmutableEntry<SqlTypeName, Boolean> sqlTypePair : types) {
    final SqlTypeName typeName = sqlTypePair.getKey();
    final RelDataType tempDataType;
    switch (typeName) {
      case VARCHAR:
        tempDataType = factory.createSqlType(typeName, Integer.MAX_VALUE);
        break;
      default:
        tempDataType = factory.createSqlType(typeName);
    }
    //Add [Non]Nullable RelDataType
    fields.add(factory.createTypeWithNullability(tempDataType, sqlTypePair.getValue()));
  }
  return factory.createStructType(fields, names);
}
 
Example 5
Source File: PermutationTestCase.java    From calcite with Apache License 2.0 6 votes vote down vote up
@Test void testProjectPermutation() {
  final RelDataTypeFactory typeFactory = new JavaTypeFactoryImpl();
  final RexBuilder builder = new RexBuilder(typeFactory);
  final RelDataType doubleType =
      typeFactory.createSqlType(SqlTypeName.DOUBLE);

  // A project with [1, 1] is not a permutation, so should return null
  final Permutation perm = Project.getPermutation(2,
      ImmutableList.of(builder.makeInputRef(doubleType, 1),
          builder.makeInputRef(doubleType, 1)));
  assertThat(perm, nullValue());

  // A project with [0, 1, 0] is not a permutation, so should return null
  final Permutation perm1 = Project.getPermutation(2,
      ImmutableList.of(builder.makeInputRef(doubleType, 0),
          builder.makeInputRef(doubleType, 1),
          builder.makeInputRef(doubleType, 0)));
  assertThat(perm1, nullValue());

  // A project of [1, 0] is a valid permutation!
  final Permutation perm2 = Project.getPermutation(2,
      ImmutableList.of(builder.makeInputRef(doubleType, 1),
          builder.makeInputRef(doubleType, 0)));
  assertThat(perm2, is(new Permutation(new int[]{1, 0})));
}
 
Example 6
Source File: RelDataTypeSystemTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
@Override public RelDataType deriveDecimalPlusType(RelDataTypeFactory typeFactory,
    RelDataType type1, RelDataType type2) {

  if (!SqlTypeUtil.isExactNumeric(type1)
      && !SqlTypeUtil.isExactNumeric(type2)) {
    return null;
  }
  if (!SqlTypeUtil.isDecimal(type1)
        || !SqlTypeUtil.isDecimal(type2)) {
    return null;
  }

  int resultScale = Math.max(type1.getScale(), type2.getScale());
  int resultPrecision = resultScale + Math.max(type1.getPrecision() - type1.getScale(),
          type2.getPrecision() - type2.getScale()) + 1;
  if (resultPrecision > 38) {
    int minScale = Math.min(resultScale, 6);
    int delta = resultPrecision - 38;
    resultPrecision = 38;
    resultScale = Math.max(resultScale - delta, minScale);
  }

  return typeFactory.createSqlType(SqlTypeName.DECIMAL, resultPrecision, resultScale);
}
 
Example 7
Source File: Handler.java    From calcite with Apache License 2.0 5 votes vote down vote up
private RelDataType toType(Ast.ScalarType type) {
  final RelDataTypeFactory typeFactory = builder.getTypeFactory();
  switch (type.name) {
  case "boolean":
    return typeFactory.createSqlType(SqlTypeName.BOOLEAN);
  case "int":
    return typeFactory.createSqlType(SqlTypeName.INTEGER);
  case "float":
    return typeFactory.createSqlType(SqlTypeName.REAL);
  default:
    return typeFactory.createSqlType(SqlTypeName.VARCHAR);
  }
}
 
Example 8
Source File: StreamEndpoint.java    From attic-apex-malhar with Apache License 2.0 5 votes vote down vote up
private RelDataType convertField(RelDataTypeFactory typeFactory, Class<?> type)
{
  RelDataType relDataType;

  if ((type == Boolean.class) || (type == boolean.class)) {
    relDataType = typeFactory.createSqlType(SqlTypeName.BOOLEAN);
  } else if ((type == Double.class) || (type == double.class)) {
    relDataType = typeFactory.createSqlType(SqlTypeName.DOUBLE);
  } else if ((type == Integer.class) || (type == int.class)) {
    relDataType = typeFactory.createSqlType(SqlTypeName.INTEGER);
  } else if ((type == Float.class) || (type == float.class)) {
    relDataType = typeFactory.createSqlType(SqlTypeName.FLOAT);
  } else if ((type == Long.class) || (type == long.class)) {
    relDataType = typeFactory.createSqlType(SqlTypeName.BIGINT);
  } else if ((type == Short.class) || (type == short.class)) {
    relDataType = typeFactory.createSqlType(SqlTypeName.SMALLINT);
  } else if ((type == Character.class) || (type == char.class) || (type == Byte.class) || (type == byte.class)) {
    relDataType = typeFactory.createSqlType(SqlTypeName.CHAR);
  } else if (type == String.class) {
    relDataType = typeFactory.createSqlType(SqlTypeName.VARCHAR);
  } else if (type == Date.class) {
    relDataType = typeFactory.createSqlType(SqlTypeName.TIMESTAMP);
  } else {
    relDataType = typeFactory.createSqlType(SqlTypeName.ANY);
  }
  return relDataType;
}
 
Example 9
Source File: SnapshotThreadStacksTable.java    From mat-calcite-plugin with Apache License 2.0 5 votes vote down vote up
@Override
public RelDataType getRowType(RelDataTypeFactory typeFactory) {
    RelDataTypeFactory.FieldInfoBuilder builder = typeFactory.builder();
    RelDataType anyType = typeFactory.createSqlType(SqlTypeName.ANY);
    builder.add("thread", anyType);
    builder.add("depth", typeFactory.createJavaType(int.class));
    builder.add("text", typeFactory.createJavaType(String.class));
    builder.add("objects", typeFactory.createMultisetType(anyType, -1));
    return builder.build();
}
 
Example 10
Source File: SqlTypeFactoryTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
private void checkCreateSqlTypeWithPrecision(
    RelDataTypeFactory typeFactory, SqlTypeName sqlTypeName) {
  RelDataType ts = typeFactory.createSqlType(sqlTypeName);
  RelDataType tsWithoutPrecision = typeFactory.createSqlType(sqlTypeName, -1);
  RelDataType tsWithPrecision0 = typeFactory.createSqlType(sqlTypeName, 0);
  RelDataType tsWithPrecision1 = typeFactory.createSqlType(sqlTypeName, 1);
  RelDataType tsWithPrecision2 = typeFactory.createSqlType(sqlTypeName, 2);
  RelDataType tsWithPrecision3 = typeFactory.createSqlType(sqlTypeName, 3);
  // for instance, 8 exceeds max precision for timestamp which is 3
  RelDataType tsWithPrecision8 = typeFactory.createSqlType(sqlTypeName, 8);

  assertThat(ts.toString(), is(sqlTypeName.getName() + "(0)"));
  assertThat(ts.getFullTypeString(), is(sqlTypeName.getName() + "(0) NOT NULL"));
  assertThat(tsWithoutPrecision.toString(), is(sqlTypeName.getName()));
  assertThat(tsWithoutPrecision.getFullTypeString(), is(sqlTypeName.getName() + " NOT NULL"));
  assertThat(tsWithPrecision0.toString(), is(sqlTypeName.getName() + "(0)"));
  assertThat(tsWithPrecision0.getFullTypeString(), is(sqlTypeName.getName() + "(0) NOT NULL"));
  assertThat(tsWithPrecision1.toString(), is(sqlTypeName.getName() + "(1)"));
  assertThat(tsWithPrecision1.getFullTypeString(), is(sqlTypeName.getName() + "(1) NOT NULL"));
  assertThat(tsWithPrecision2.toString(), is(sqlTypeName.getName() + "(2)"));
  assertThat(tsWithPrecision2.getFullTypeString(), is(sqlTypeName.getName() + "(2) NOT NULL"));
  assertThat(tsWithPrecision3.toString(), is(sqlTypeName.getName() + "(3)"));
  assertThat(tsWithPrecision3.getFullTypeString(), is(sqlTypeName.getName() + "(3) NOT NULL"));
  assertThat(tsWithPrecision8.toString(), is(sqlTypeName.getName() + "(3)"));
  assertThat(tsWithPrecision8.getFullTypeString(), is(sqlTypeName.getName() + "(3) NOT NULL"));

  assertThat(ts != tsWithoutPrecision, is(true));
  assertThat(ts == tsWithPrecision0, is(true));
  assertThat(tsWithPrecision3 == tsWithPrecision8, is(true));
}
 
Example 11
Source File: HBTQueryConvertor.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
public static RelDataType toType(String typeText, boolean nullable, Integer precision, Integer scale) {
    final RelDataTypeFactory typeFactory = MycatCalciteSupport.INSTANCE.TypeFactory;
    SqlTypeName sqlTypeName = HBTCalciteSupport.INSTANCE.getSqlTypeName(typeText);
    RelDataType sqlType = null;
    if (precision != null && scale != null) {
        if (sqlTypeName.allowsPrec()&&sqlTypeName.allowsScale()){
            sqlType = typeFactory.createSqlType(sqlTypeName, precision, scale);
        }else if (sqlTypeName.allowsPrec()&&!sqlTypeName.allowsScale()){
            sqlType = typeFactory.createSqlType(sqlTypeName, precision);
        }else if (sqlTypeName.allowsPrec()&&!sqlTypeName.allowsScale()){
            sqlType = typeFactory.createSqlType(sqlTypeName, precision);
        }else if (!sqlTypeName.allowsPrec()&&!sqlTypeName.allowsScale()){
            sqlType = typeFactory.createSqlType(sqlTypeName);
        }else {
            throw new IllegalArgumentException("sqlTypeName:"+sqlTypeName+" precision:"+precision+" scale:"+scale);
        }
    }
    if (precision != null && scale == null) {
        if (sqlTypeName.allowsPrec()){
            sqlType = typeFactory.createSqlType(sqlTypeName, precision);
        }else {
            sqlType = typeFactory.createSqlType(sqlTypeName);
        }
    }
    if (precision == null && scale == null) {
        sqlType = typeFactory.createSqlType(sqlTypeName);
    }
    if (sqlType == null) {
        throw new IllegalArgumentException("sqlTypeName:"+sqlTypeName);
    }

    return typeFactory.createTypeWithNullability(sqlType, nullable);
}
 
Example 12
Source File: JavaTypeFactoryImpl.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** Converts a type in Java format to a SQL-oriented type. */
public static RelDataType toSql(final RelDataTypeFactory typeFactory,
    RelDataType type) {
  if (type instanceof RelRecordType) {
    return typeFactory.createTypeWithNullability(
        typeFactory.createStructType(
            type.getFieldList()
                .stream()
                .map(field -> toSql(typeFactory, field.getType()))
                .collect(Collectors.toList()),
            type.getFieldNames()),
        type.isNullable());
  } else if (type instanceof JavaType) {
    SqlTypeName sqlTypeName = type.getSqlTypeName();
    final RelDataType relDataType;
    if (SqlTypeUtil.isArray(type)) {
      // Transform to sql type, take care for two cases:
      // 1. type.getJavaClass() is collection with erased generic type
      // 2. ElementType returned by JavaType is also of JavaType,
      // and needs conversion using typeFactory
      final RelDataType elementType = toSqlTypeWithNullToAny(
          typeFactory, type.getComponentType());
      relDataType = typeFactory.createArrayType(elementType, -1);
    } else if (SqlTypeUtil.isMap(type)) {
      final RelDataType keyType = toSqlTypeWithNullToAny(
          typeFactory, type.getKeyType());
      final RelDataType valueType = toSqlTypeWithNullToAny(
          typeFactory, type.getValueType());
      relDataType = typeFactory.createMapType(keyType, valueType);
    } else {
      relDataType = typeFactory.createSqlType(sqlTypeName);
    }
    return typeFactory.createTypeWithNullability(relDataType, type.isNullable());
  }
  return type;
}
 
Example 13
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 14
Source File: RelDataTypeSystemImpl.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
@Override
public RelDataType deriveDecimalRoundType(RelDataTypeFactory typeFactory, RelDataType type1,
  Integer scale2) {
  if (!SqlTypeUtil.isExactNumeric(type1) || !SqlTypeUtil.isDecimal(type1)) {
    return null;
  }

  ArrowType.Decimal finalPrecisionScale = OutputDerivation.getDecimalOutputTypeForRound(type1.getPrecision(),
    type1.getScale(), scale2);

  return typeFactory.createSqlType(SqlTypeName.DECIMAL, finalPrecisionScale.getPrecision(),
    finalPrecisionScale.getScale());
}
 
Example 15
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 16
Source File: RexSubQuery.java    From Bats with Apache License 2.0 4 votes vote down vote up
/** Creates an EXISTS sub-query. */
public static RexSubQuery exists(RelNode rel) {
    final RelDataTypeFactory typeFactory = rel.getCluster().getTypeFactory();
    final RelDataType type = typeFactory.createSqlType(SqlTypeName.BOOLEAN);
    return RexBuilder.getRexFactory().makeSubQuery(type, SqlStdOperatorTable.EXISTS, ImmutableList.of(), rel);
}
 
Example 17
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 18
Source File: SqlListAggFunction.java    From flink with Apache License 2.0 4 votes vote down vote up
@Override
public RelDataType getReturnType(RelDataTypeFactory typeFactory) {
	return typeFactory.createSqlType(SqlTypeName.VARCHAR);
}
 
Example 19
Source File: MockSqlOperatorTable.java    From calcite with Apache License 2.0 4 votes vote down vote up
public RelDataType inferReturnType(SqlOperatorBinding opBinding) {
  final RelDataTypeFactory typeFactory =
      opBinding.getTypeFactory();
  return typeFactory.createSqlType(SqlTypeName.BIGINT);
}
 
Example 20
Source File: DynamicType.java    From Bats with Apache License 2.0 4 votes vote down vote up
@Override
  public RelDataType apply(RelDataTypeFactory factory) {
    return factory.createSqlType(SqlTypeName.ANY);
//    return new RelDataTypeDrillImpl(new RelDataTypeHolder(), factory);
  }