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

The following examples show how to use org.apache.calcite.sql.type.SqlTypeName. 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: dremio-oss   Source File: JoinRelBase.java    License: Apache License 2.0 6 votes vote down vote up
@Override public boolean isValid(Litmus litmus, Context context) {
  if (condition != null) {
    if (condition.getType().getSqlTypeName() != SqlTypeName.BOOLEAN) {
      return litmus.fail("condition must be boolean: {}",
        condition.getType());
    }
    // The input to the condition is a row type consisting of system
    // fields, left fields, and right fields. Very similar to the
    // output row type, except that fields have not yet been made due
    // due to outer joins.
    RexChecker checker =
      new RexChecker(
        getCluster().getTypeFactory().builder()
          .addAll(getSystemFieldList())
          .addAll(getLeft().getRowType().getFieldList())
          .addAll(getRight().getRowType().getFieldList())
          .build(),
        context, litmus);
    condition.accept(checker);
    if (checker.getFailureCount() > 0) {
      return litmus.fail(checker.getFailureCount()
        + " failures in condition " + condition);
    }
  }
  return litmus.succeed();
}
 
Example 2
Source Project: calcite   Source File: PreferredAlbumsTableFactory.java    License: Apache License 2.0 6 votes vote down vote up
@Override public AbstractQueryableTable create(
    SchemaPlus schema,
    String name,
    Map<String, Object> operand,
    RelDataType rowType) {
  return new AbstractQueryableTable(Integer.class) {
    @Override public RelDataType getRowType(RelDataTypeFactory typeFactory) {
      return typeFactory.builder().add("ID", SqlTypeName.INTEGER).build();
    }

    @Override public Queryable<Integer> asQueryable(
        QueryProvider qp,
        SchemaPlus sp,
        String string) {
      return fetchPreferredAlbums();
    }
  };
}
 
Example 3
Source Project: calcite   Source File: RexProgramTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test void testSimplifyCastLiteral2() {
  final RexLiteral literalAbc = rexBuilder.makeLiteral("abc");
  final RexLiteral literalOne = rexBuilder.makeExactLiteral(BigDecimal.ONE);
  final RelDataType intType = typeFactory.createSqlType(SqlTypeName.INTEGER);
  final RelDataType varcharType =
      typeFactory.createSqlType(SqlTypeName.VARCHAR, 10);
  final RelDataType booleanType =
      typeFactory.createSqlType(SqlTypeName.BOOLEAN);
  final RelDataType dateType = typeFactory.createSqlType(SqlTypeName.DATE);
  final RelDataType timestampType =
      typeFactory.createSqlType(SqlTypeName.TIMESTAMP);
  checkSimplifyUnchanged(cast(literalAbc, intType));
  checkSimplifyUnchanged(cast(literalOne, intType));
  checkSimplifyUnchanged(cast(literalAbc, varcharType));
  checkSimplify(cast(literalOne, varcharType), "'1':VARCHAR(10)");
  checkSimplifyUnchanged(cast(literalAbc, booleanType));
  checkSimplify(cast(literalOne, booleanType),
      "false"); // different from Hive
  checkSimplifyUnchanged(cast(literalAbc, dateType));
  checkSimplify(cast(literalOne, dateType),
      "1970-01-02"); // different from Hive
  checkSimplifyUnchanged(cast(literalAbc, timestampType));
  checkSimplify(cast(literalOne, timestampType),
      "1970-01-01 00:00:00"); // different from Hive
}
 
Example 4
Source Project: Bats   Source File: TypeInferenceUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Given a {@link SqlTypeName} and nullability, create a RelDataType from the RelDataTypeFactory
 *
 * @param typeFactory RelDataTypeFactory used to create the RelDataType
 * @param sqlTypeName the given SqlTypeName
 * @param isNullable  the nullability of the created RelDataType
 * @return RelDataType Type of call
 */
public static RelDataType createCalciteTypeWithNullability(RelDataTypeFactory typeFactory,
                                                           SqlTypeName sqlTypeName,
                                                           boolean isNullable) {
  RelDataType type;
  if (sqlTypeName.getFamily() == SqlTypeFamily.INTERVAL_DAY_TIME) {
    type = typeFactory.createSqlIntervalType(
        new SqlIntervalQualifier(
            TimeUnit.DAY,
            TimeUnit.MINUTE,
            SqlParserPos.ZERO));
  } else if (sqlTypeName.getFamily() == SqlTypeFamily.INTERVAL_YEAR_MONTH) {
    type = typeFactory.createSqlIntervalType(
        new SqlIntervalQualifier(
            TimeUnit.YEAR,
            TimeUnit.MONTH,
            SqlParserPos.ZERO));
  } else if (sqlTypeName == SqlTypeName.VARCHAR) {
    type = typeFactory.createSqlType(sqlTypeName, Types.MAX_VARCHAR_LENGTH);
  } else {
    type = typeFactory.createSqlType(sqlTypeName);
  }
  return typeFactory.createTypeWithNullability(type, isNullable);
}
 
Example 5
Source Project: calcite   Source File: RexProgramTestBase.java    License: Apache License 2.0 6 votes vote down vote up
protected void checkSimplify3_(RexNode node, String expected,
                             String expectedFalse, String expectedTrue) {
  final RexNode simplified =
      simplify.simplifyUnknownAs(node, RexUnknownAs.UNKNOWN);
  assertThat("simplify(unknown as unknown): " + node,
      simplified.toString(), equalTo(expected));
  if (node.getType().getSqlTypeName() == SqlTypeName.BOOLEAN) {
    final RexNode simplified2 =
        simplify.simplifyUnknownAs(node, RexUnknownAs.FALSE);
    assertThat("simplify(unknown as false): " + node,
        simplified2.toString(), equalTo(expectedFalse));
    final RexNode simplified3 =
        simplify.simplifyUnknownAs(node, RexUnknownAs.TRUE);
    assertThat("simplify(unknown as true): " + node,
        simplified3.toString(), equalTo(expectedTrue));
  } else {
    assertThat("node type is not BOOLEAN, so <<expectedFalse>> should match <<expected>>",
        expectedFalse, is(expected));
    assertThat("node type is not BOOLEAN, so <<expectedTrue>> should match <<expected>>",
        expectedTrue, is(expected));
  }
}
 
Example 6
Source Project: flink   Source File: FlinkReturnTypes.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public RelDataType inferReturnType(SqlOperatorBinding opBinding) {
	RelDataType type = super.inferReturnType(opBinding);
	RelDataType newType;
	switch (type.getSqlTypeName()) {
		case CHAR:
			newType = opBinding.getTypeFactory().createSqlType(SqlTypeName.VARCHAR, type.getPrecision());
			break;
		case VARCHAR:
			newType = type;
			break;
		default:
			throw new UnsupportedOperationException("Unsupported type: " + type);
	}
	return opBinding.getTypeFactory().createTypeWithNullability(newType, true);
}
 
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
Source Project: kafka-eagle   Source File: JSqlMapData.java    License: Apache License 2.0 6 votes vote down vote up
private static void loadDatabaseType() {
	SQLTYPE_MAPPING.put("char", SqlTypeName.CHAR);
	JAVATYPE_MAPPING.put("char", Character.class);
	SQLTYPE_MAPPING.put("varchar", SqlTypeName.VARCHAR);
	JAVATYPE_MAPPING.put("varchar", String.class);
	SQLTYPE_MAPPING.put("boolean", SqlTypeName.BOOLEAN);
	SQLTYPE_MAPPING.put("integer", SqlTypeName.INTEGER);
	JAVATYPE_MAPPING.put("integer", Integer.class);
	SQLTYPE_MAPPING.put("tinyint", SqlTypeName.TINYINT);
	SQLTYPE_MAPPING.put("smallint", SqlTypeName.SMALLINT);
	SQLTYPE_MAPPING.put("bigint", SqlTypeName.BIGINT);
	JAVATYPE_MAPPING.put("bigint", Long.class);
	SQLTYPE_MAPPING.put("decimal", SqlTypeName.DECIMAL);
	SQLTYPE_MAPPING.put("numeric", SqlTypeName.DECIMAL);
	SQLTYPE_MAPPING.put("float", SqlTypeName.FLOAT);
	SQLTYPE_MAPPING.put("real", SqlTypeName.REAL);
	SQLTYPE_MAPPING.put("double", SqlTypeName.DOUBLE);
	SQLTYPE_MAPPING.put("date", SqlTypeName.DATE);
	JAVATYPE_MAPPING.put("date", Date.class);
	SQLTYPE_MAPPING.put("time", SqlTypeName.TIME);
	SQLTYPE_MAPPING.put("timestamp", SqlTypeName.TIMESTAMP);
	SQLTYPE_MAPPING.put("any", SqlTypeName.ANY);
}
 
Example 9
Source Project: calcite   Source File: RelDataTypeSystemImpl.java    License: Apache License 2.0 6 votes vote down vote up
public int getMaxScale(SqlTypeName typeName) {
  switch (typeName) {
  case DECIMAL:
    return getMaxNumericScale();
  case INTERVAL_YEAR:
  case INTERVAL_YEAR_MONTH:
  case INTERVAL_MONTH:
  case INTERVAL_DAY:
  case INTERVAL_DAY_HOUR:
  case INTERVAL_DAY_MINUTE:
  case INTERVAL_DAY_SECOND:
  case INTERVAL_HOUR:
  case INTERVAL_HOUR_MINUTE:
  case INTERVAL_HOUR_SECOND:
  case INTERVAL_MINUTE:
  case INTERVAL_MINUTE_SECOND:
  case INTERVAL_SECOND:
    return SqlTypeName.MAX_INTERVAL_FRACTIONAL_SECOND_PRECISION;
  default:
    return -1;
  }
}
 
Example 10
Source Project: dremio-oss   Source File: FlattenConvertlet.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public RexNode convertCall(SqlRexContext cx, SqlCall call) {
  SqlFlattenOperator operator = (SqlFlattenOperator) call.getOperator();
  final List<RexNode> exprs = new LinkedList<>();

  for (SqlNode node : call.getOperandList()) {
    exprs.add(cx.convertExpression(node));
  }

  SqlFlattenOperator indexedOperator = operator.withIndex(((SqlValidatorImpl)cx.getValidator()).nextFlattenIndex());
  final RexBuilder rexBuilder = cx.getRexBuilder();
  // Since we don't have any way of knowing if the output of the flatten is nullable, we should always assume it is.
  // This is especially important when accelerating a count(column) query, because the normalizer will convert it to
  // a count(1) if it thinks this column is non-nullable, and then remove the flatten altogether. This is actually a
  // problem with the fact that flatten is not really a project operator (because it can output more than one row per input).
  RelDataType type = rexBuilder
    .getTypeFactory()
    .createTypeWithNullability(
      rexBuilder
        .getTypeFactory()
        .createSqlType(SqlTypeName.ANY),
      true
    );
  return rexBuilder.makeCall(type, indexedOperator, exprs);

}
 
Example 11
Source Project: flink   Source File: SqlValidatorImpl.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates a validator.
 *
 * @param opTab         Operator table
 * @param catalogReader Catalog reader
 * @param typeFactory   Type factory
 * @param conformance   Compatibility mode
 */
protected SqlValidatorImpl(
	SqlOperatorTable opTab,
	SqlValidatorCatalogReader catalogReader,
	RelDataTypeFactory typeFactory,
	SqlConformance conformance) {
	this.opTab = Objects.requireNonNull(opTab);
	this.catalogReader = Objects.requireNonNull(catalogReader);
	this.typeFactory = Objects.requireNonNull(typeFactory);
	this.conformance = Objects.requireNonNull(conformance);

	unknownType = typeFactory.createUnknownType();
	booleanType = typeFactory.createSqlType(SqlTypeName.BOOLEAN);

	rewriteCalls = true;
	expandColumnReferences = true;
	final SqlNameMatcher nameMatcher = catalogReader.nameMatcher();
	aggFinder = new AggFinder(opTab, false, true, false, null, nameMatcher);
	aggOrOverFinder = new AggFinder(opTab, true, true, false, null, nameMatcher);
	overFinder = new AggFinder(opTab, true, false, false, aggOrOverFinder, nameMatcher);
	groupFinder = new AggFinder(opTab, false, false, true, null, nameMatcher);
	aggOrOverOrGroupFinder = new AggFinder(opTab, true, true, true, null, nameMatcher);
}
 
Example 12
Source Project: calcite   Source File: SqlTumbleTableFunction.java    License: Apache License 2.0 6 votes vote down vote up
@Override public boolean checkOperandTypes(SqlCallBinding callBinding,
    boolean throwOnFailure) {
  // There should only be three operands, and number of operands are checked before
  // this call.
  final SqlNode operand0 = callBinding.operand(0);
  final SqlValidator validator = callBinding.getValidator();
  final RelDataType type = validator.getValidatedNodeType(operand0);
  if (type.getSqlTypeName() != SqlTypeName.ROW) {
    return throwValidationSignatureErrorOrReturnFalse(callBinding, throwOnFailure);
  }
  final SqlNode operand1 = callBinding.operand(1);
  if (operand1.getKind() != SqlKind.DESCRIPTOR) {
    return throwValidationSignatureErrorOrReturnFalse(callBinding, throwOnFailure);
  }
  validateColumnNames(validator, type.getFieldNames(), ((SqlCall) operand1).getOperandList());
  final RelDataType type2 = validator.getValidatedNodeType(callBinding.operand(2));
  if (!SqlTypeUtil.isInterval(type2)) {
    return throwValidationSignatureErrorOrReturnFalse(callBinding, throwOnFailure);
  }
  return true;
}
 
Example 13
Source Project: calcite   Source File: RelToSqlConverterStructsTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Table schema is as following:
 *  myTable(
 *          a: BIGINT,
 *          n1: STRUCT<
 *                n11: STRUCT<b: BIGINT>,
 *                n12: STRUCT<c: BIGINT>
 *              >,
 *          n2: STRUCT<d: BIGINT>,
 *          e: BIGINT
 *  )
 */
@Override public RelDataType getRowType(RelDataTypeFactory tf) {
  RelDataType bigint = tf.createSqlType(SqlTypeName.BIGINT);
  RelDataType n1Type = tf.createStructType(
      ImmutableList.of(
          tf.createStructType(ImmutableList.of(bigint),
              ImmutableList.of("b")),
          tf.createStructType(ImmutableList.of(bigint),
              ImmutableList.of("c"))),
      ImmutableList.of("n11", "n12"));
  RelDataType n2Type = tf.createStructType(
      ImmutableList.of(bigint),
      ImmutableList.of("d"));
  return tf.createStructType(
      ImmutableList.of(bigint, n1Type, n2Type, bigint),
      ImmutableList.of("a", "n1", "n2", "e"));
}
 
Example 14
Source Project: Bats   Source File: UnnestPrel.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Prel prepareForLateralUnnestPipeline(List<RelNode> children) {
  RelDataTypeFactory typeFactory = this.getCluster().getTypeFactory();
  List<String> fieldNames = new ArrayList<>();
  List<RelDataType> fieldTypes = new ArrayList<>();

  fieldNames.add(IMPLICIT_COLUMN);
  fieldTypes.add(typeFactory.createSqlType(SqlTypeName.INTEGER));

  for (RelDataTypeField field : this.rowType.getFieldList()) {
    fieldNames.add(field.getName());
    fieldTypes.add(field.getType());
  }

  RelDataType newRowType = typeFactory.createStructType(fieldTypes, fieldNames);
  return new UnnestPrel(this.getCluster(), this.getTraitSet(), newRowType, ref);
}
 
Example 15
Source Project: samza   Source File: JoinTranslator.java    License: Apache License 2.0 5 votes vote down vote up
private void validateJoinKeyType(RexInputRef ref) {
  SqlTypeName sqlTypeName = ref.getType().getSqlTypeName();

  // Primitive types and ANY (for the record key) are supported in the key
  if (sqlTypeName != SqlTypeName.BOOLEAN && sqlTypeName != SqlTypeName.TINYINT && sqlTypeName != SqlTypeName.SMALLINT
      && sqlTypeName != SqlTypeName.INTEGER && sqlTypeName != SqlTypeName.CHAR && sqlTypeName != SqlTypeName.BIGINT
      && sqlTypeName != SqlTypeName.VARCHAR && sqlTypeName != SqlTypeName.DOUBLE && sqlTypeName != SqlTypeName.FLOAT
      && sqlTypeName != SqlTypeName.ANY && sqlTypeName != SqlTypeName.OTHER) {
    log.error("Unsupported key type " + sqlTypeName + " used in join condition.");
    throw new SamzaException("Unsupported key type used in join condition.");
  }
}
 
Example 16
Source Project: flink   Source File: StructuredRelDataType.java    License: Apache License 2.0 5 votes vote down vote up
private StructuredRelDataType(StructuredType structuredType, List<RelDataTypeField> fields) {
	super(
		SqlTypeName.STRUCTURED,
		createSqlIdentifier(structuredType),
		structuredType.isNullable(),
		fields,
		createRelDataTypeComparability(structuredType));
	this.structuredType = structuredType;
	computeDigest(); // recompute digest
}
 
Example 17
Source Project: Bats   Source File: RexSimplify.java    License: Apache License 2.0 5 votes vote down vote up
private RexNode simplifyCast(RexCall e) {
    RexNode operand = e.getOperands().get(0);
    operand = simplify(operand, UNKNOWN);
    if (sameTypeOrNarrowsNullability(e.getType(), operand.getType())) {
        return operand;
    }
    switch (operand.getKind()) {
    case LITERAL:
        final RexLiteral literal = (RexLiteral) operand;
        final Comparable value = literal.getValueAs(Comparable.class);
        final SqlTypeName typeName = literal.getTypeName();

        // First, try to remove the cast without changing the value.
        // makeCast and canRemoveCastFromLiteral have the same logic, so we are
        // sure to be able to remove the cast.
        if (rexBuilder.canRemoveCastFromLiteral(e.getType(), value, typeName)) {
            return rexBuilder.makeCast(e.getType(), operand);
        }

        // Next, try to convert the value to a different type,
        // e.g. CAST('123' as integer)
        switch (literal.getTypeName()) {
        case TIME:
            switch (e.getType().getSqlTypeName()) {
            case TIMESTAMP:
                return e;
            }
            break;
        }
        final List<RexNode> reducedValues = new ArrayList<>();
        executor.reduce(rexBuilder, ImmutableList.of(e), reducedValues);
        return Objects.requireNonNull(Iterables.getOnlyElement(reducedValues));
    default:
        if (operand == e.getOperands().get(0)) {
            return e;
        } else {
            return rexBuilder.makeCast(e.getType(), operand);
        }
    }
}
 
Example 18
Source Project: calcite   Source File: RelDataTypeSystemImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override public String getLiteral(SqlTypeName typeName, boolean isPrefix) {
  switch (typeName) {
  case VARBINARY:
  case VARCHAR:
  case CHAR:
    return "'";
  case BINARY:
    return isPrefix ? "x'" : "'";
  case TIMESTAMP:
    return isPrefix ? "TIMESTAMP '" : "'";
  case TIMESTAMP_WITH_LOCAL_TIME_ZONE:
    return isPrefix ? "TIMESTAMP WITH LOCAL TIME ZONE '" : "'";
  case INTERVAL_DAY:
  case INTERVAL_DAY_HOUR:
  case INTERVAL_DAY_MINUTE:
  case INTERVAL_DAY_SECOND:
  case INTERVAL_HOUR:
  case INTERVAL_HOUR_MINUTE:
  case INTERVAL_HOUR_SECOND:
  case INTERVAL_MINUTE:
  case INTERVAL_MINUTE_SECOND:
  case INTERVAL_SECOND:
    return isPrefix ? "INTERVAL '" : "' DAY";
  case INTERVAL_YEAR:
  case INTERVAL_YEAR_MONTH:
  case INTERVAL_MONTH:
    return isPrefix ? "INTERVAL '" : "' YEAR TO MONTH";
  case TIME:
    return isPrefix ? "TIME '" : "'";
  case TIME_WITH_LOCAL_TIME_ZONE:
    return isPrefix ? "TIME WITH LOCAL TIME ZONE '" : "'";
  case DATE:
    return isPrefix ? "DATE '" : "'";
  case ARRAY:
    return isPrefix ? "(" : ")";
  default:
    return null;
  }
}
 
Example 19
Source Project: Bats   Source File: DrillExtractConvertlet.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public RexNode convertCall(SqlRexContext cx, SqlCall call) {
  final RexBuilder rexBuilder = cx.getRexBuilder();
  final List<SqlNode> operands = call.getOperandList();
  final List<RexNode> exprs = new LinkedList<>();

  String timeUnit = ((SqlIntervalQualifier) operands.get(0)).timeUnitRange.toString();

  RelDataTypeFactory typeFactory = cx.getTypeFactory();

  //RelDataType nullableReturnType =

  for (SqlNode node: operands) {
     exprs.add(cx.convertExpression(node));
  }

  final RelDataType returnType;
  if(call.getOperator() == SqlStdOperatorTable.EXTRACT) {
    // Legacy code:
    // The return type is wrong!
    // Legacy code choose SqlTypeName.BIGINT simply to avoid conflicting against Calcite's inference mechanism
    // (, which chose BIGINT in validation phase already)
    // Determine NULL-able using 2nd argument's Null-able.
    returnType = typeFactory.createTypeWithNullability(typeFactory.createSqlType(SqlTypeName.BIGINT), exprs.get(1).getType().isNullable());
  } else {
    // Determine NULL-able using 2nd argument's Null-able.
    returnType = typeFactory.createTypeWithNullability(
        typeFactory.createSqlType(
            TypeInferenceUtils.getSqlTypeNameForTimeUnit(timeUnit)),
        exprs.get(1).getType().isNullable());
  }

  return rexBuilder.makeCall(returnType, call.getOperator(), exprs);
}
 
Example 20
Source Project: dremio-oss   Source File: RelDataTypeSystemImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public RelDataType deriveDecimalTruncateType(RelDataTypeFactory typeFactory, RelDataType type1,
  Integer scale2) {
  if (!SqlTypeUtil.isExactNumeric(type1) || !SqlTypeUtil.isDecimal(type1)) {
    return null;
  }

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

  return typeFactory.createSqlType(SqlTypeName.DECIMAL, finalPrecisionScale.getPrecision(),
    finalPrecisionScale.getScale());
}
 
Example 21
Source Project: calcite   Source File: MysqlSqlDialect.java    License: Apache License 2.0 5 votes vote down vote up
@Override public SqlNode getCastSpec(RelDataType type) {
  switch (type.getSqlTypeName()) {
  case VARCHAR:
    // MySQL doesn't have a VARCHAR type, only CHAR.
    int vcMaxPrecision = this.getTypeSystem().getMaxPrecision(SqlTypeName.CHAR);
    int precision = type.getPrecision();
    if (vcMaxPrecision > 0 && precision > vcMaxPrecision) {
      precision = vcMaxPrecision;
    }
    return new SqlDataTypeSpec(
        new SqlBasicTypeNameSpec(SqlTypeName.CHAR, precision, SqlParserPos.ZERO),
        SqlParserPos.ZERO);
  case INTEGER:
  case BIGINT:
    return new SqlDataTypeSpec(
        new SqlAlienSystemTypeNameSpec(
            "SIGNED",
            type.getSqlTypeName(),
            SqlParserPos.ZERO),
        SqlParserPos.ZERO);
  case TIMESTAMP:
    return new SqlDataTypeSpec(
        new SqlAlienSystemTypeNameSpec(
            "DATETIME",
            type.getSqlTypeName(),
            SqlParserPos.ZERO),
        SqlParserPos.ZERO);
  }
  return super.getCastSpec(type);
}
 
Example 22
Source Project: Bats   Source File: RexUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns whether the input is a 'loss-less' cast, that is, a cast from which
 * the original value of the field can be certainly recovered.
 *
 * <p>For instance, int &rarr; bigint is loss-less (as you can cast back to
 * int without loss of information), but bigint &rarr; int is not loss-less.
 *
 * <p>The implementation of this method does not return false positives.
 * However, it is not complete.
 */
public static boolean isLosslessCast(RexNode node) {
    if (!node.isA(SqlKind.CAST)) {
        return false;
    }
    final RelDataType source = ((RexCall) node).getOperands().get(0).getType();
    final SqlTypeName sourceSqlTypeName = source.getSqlTypeName();
    final RelDataType target = node.getType();
    final SqlTypeName targetSqlTypeName = target.getSqlTypeName();
    // 1) Both INT numeric types
    if (SqlTypeFamily.INTEGER.getTypeNames().contains(sourceSqlTypeName)
            && SqlTypeFamily.INTEGER.getTypeNames().contains(targetSqlTypeName)) {
        return targetSqlTypeName.compareTo(sourceSqlTypeName) >= 0;
    }
    // 2) Both CHARACTER types: it depends on the precision (length)
    if (SqlTypeFamily.CHARACTER.getTypeNames().contains(sourceSqlTypeName)
            && SqlTypeFamily.CHARACTER.getTypeNames().contains(targetSqlTypeName)) {
        return targetSqlTypeName.compareTo(sourceSqlTypeName) >= 0
                && source.getPrecision() <= target.getPrecision();
    }
    // 3) From NUMERIC family to CHARACTER family: it depends on the precision/scale
    if (sourceSqlTypeName.getFamily() == SqlTypeFamily.NUMERIC
            && targetSqlTypeName.getFamily() == SqlTypeFamily.CHARACTER) {
        int sourceLength = source.getPrecision() + 1; // include sign
        if (source.getScale() != -1 && source.getScale() != 0) {
            sourceLength += source.getScale() + 1; // include decimal mark
        }
        return target.getPrecision() >= sourceLength;
    }
    // Return FALSE by default
    return false;
}
 
Example 23
Source Project: calcite   Source File: RexUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns whether the conversion from {@code source} to {@code target} type
 * is a 'loss-less' cast, that is, a cast from which
 * the original value of the field can be certainly recovered.
 *
 * <p>For instance, int &rarr; bigint is loss-less (as you can cast back to
 * int without loss of information), but bigint &rarr; int is not loss-less.
 *
 * <p>The implementation of this method does not return false positives.
 * However, it is not complete.
 * @param source source type
 * @param target target type
 * @return true iff the conversion is a loss-less cast
 */
@API(since = "1.22", status = API.Status.EXPERIMENTAL)
public static boolean isLosslessCast(RelDataType source, RelDataType target) {
  final SqlTypeName sourceSqlTypeName = source.getSqlTypeName();
  final SqlTypeName targetSqlTypeName = target.getSqlTypeName();
  // 1) Both INT numeric types
  if (SqlTypeFamily.INTEGER.getTypeNames().contains(sourceSqlTypeName)
      && SqlTypeFamily.INTEGER.getTypeNames().contains(targetSqlTypeName)) {
    return targetSqlTypeName.compareTo(sourceSqlTypeName) >= 0;
  }
  // 2) Both CHARACTER types: it depends on the precision (length)
  if (SqlTypeFamily.CHARACTER.getTypeNames().contains(sourceSqlTypeName)
      && SqlTypeFamily.CHARACTER.getTypeNames().contains(targetSqlTypeName)) {
    return targetSqlTypeName.compareTo(sourceSqlTypeName) >= 0
        && source.getPrecision() <= target.getPrecision();
  }
  // 3) From NUMERIC family to CHARACTER family: it depends on the precision/scale
  if (sourceSqlTypeName.getFamily() == SqlTypeFamily.NUMERIC
      && targetSqlTypeName.getFamily() == SqlTypeFamily.CHARACTER) {
    int sourceLength = source.getPrecision() + 1; // include sign
    if (source.getScale() != -1 && source.getScale() != 0) {
      sourceLength += source.getScale() + 1; // include decimal mark
    }
    return target.getPrecision() >= sourceLength;
  }
  // Return FALSE by default
  return false;
}
 
Example 24
Source Project: calcite   Source File: SqlItemOperator.java    License: Apache License 2.0 5 votes vote down vote up
@Override public RelDataType inferReturnType(SqlOperatorBinding opBinding) {
  final RelDataTypeFactory typeFactory = opBinding.getTypeFactory();
  final RelDataType operandType = opBinding.getOperandType(0);
  switch (operandType.getSqlTypeName()) {
  case ARRAY:
    return typeFactory.createTypeWithNullability(
        operandType.getComponentType(), true);
  case MAP:
    return typeFactory.createTypeWithNullability(operandType.getValueType(),
        true);
  case ROW:
    String fieldName = opBinding.getOperandLiteralValue(1, String.class);
    RelDataTypeField field = operandType.getField(fieldName, false, false);
    if (field == null) {
      throw new AssertionError("Cannot infer type of field '"
          + fieldName + "' within ROW type: " + operandType);
    } else {
      return field.getType();
    }
  case ANY:
  case DYNAMIC_STAR:
    return typeFactory.createTypeWithNullability(
        typeFactory.createSqlType(SqlTypeName.ANY), true);
  default:
    throw new AssertionError();
  }
}
 
Example 25
Source Project: calcite   Source File: BigQuerySqlDialect.java    License: Apache License 2.0 5 votes vote down vote up
/** BigQuery data type reference:
 * <a href="https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types">
 * BigQuery Standard SQL Data Types</a>
 */
@Override public SqlNode getCastSpec(final RelDataType type) {
  if (type instanceof BasicSqlType) {
    final SqlTypeName typeName = type.getSqlTypeName();
    switch (typeName) {
    // BigQuery only supports INT64 for integer types.
    case TINYINT:
    case SMALLINT:
    case INTEGER:
    case BIGINT:
      return createSqlDataTypeSpecByName("INT64", typeName);
    // BigQuery only supports FLOAT64(aka. Double) for floating point types.
    case FLOAT:
    case DOUBLE:
      return createSqlDataTypeSpecByName("FLOAT64", typeName);
    case DECIMAL:
      return createSqlDataTypeSpecByName("NUMERIC", typeName);
    case BOOLEAN:
      return createSqlDataTypeSpecByName("BOOL", typeName);
    case CHAR:
    case VARCHAR:
      return createSqlDataTypeSpecByName("STRING", typeName);
    case BINARY:
    case VARBINARY:
      return createSqlDataTypeSpecByName("BYTES", typeName);
    case DATE:
      return createSqlDataTypeSpecByName("DATE", typeName);
    case TIME:
      return createSqlDataTypeSpecByName("TIME", typeName);
    case TIMESTAMP:
      return createSqlDataTypeSpecByName("TIMESTAMP", typeName);
    }
  }
  return super.getCastSpec(type);
}
 
Example 26
Source Project: Bats   Source File: View.java    License: Apache License 2.0 5 votes vote down vote up
@JsonCreator
public Field(
    @JsonProperty("name")                       String name,
    @JsonProperty("type")                       SqlTypeName type,
    @JsonProperty("precision")                  Integer precision,
    @JsonProperty("scale")                      Integer scale,
    @JsonProperty("startUnit")                  TimeUnit startUnit,
    @JsonProperty("endUnit")                    TimeUnit endUnit,
    @JsonProperty("fractionalSecondPrecision")  Integer fractionalSecondPrecision,
    @JsonProperty("isNullable")                 Boolean isNullable,
    @JsonProperty("keyType") Field keyType,
    @JsonProperty("valueType") Field valueType) {
  // Fix for views which were created on Calcite 1.4.
  // After Calcite upgrade star "*" was changed on dynamic star "**" (SchemaPath.DYNAMIC_STAR)
  // and type of star was changed to SqlTypeName.DYNAMIC_STAR
  this.name = "*".equals(name) ? SchemaPath.DYNAMIC_STAR : name;
  this.type = "*".equals(name) && type == SqlTypeName.ANY ? SqlTypeName.DYNAMIC_STAR : type;
  this.precision = precision;
  this.scale = scale;
  this.intervalQualifier =
      null == startUnit
      ? null
      : new SqlIntervalQualifier(
          startUnit, precision, endUnit, fractionalSecondPrecision, SqlParserPos.ZERO );

  // Property "isNullable" is not part of the initial view definition and
  // was added in DRILL-2342.  If the default value is null, consider it as
  // "true".  It is safe to default to "nullable" than "required" type.
  this.isNullable = isNullable == null || isNullable;
  this.keyType = keyType;
  this.valueType = valueType;
}
 
Example 27
Source Project: calcite   Source File: RexProgramTest.java    License: Apache License 2.0 5 votes vote down vote up
/** Unit test for
 * <a href="https://issues.apache.org/jira/browse/CALCITE-1289">[CALCITE-1289]
 * RexUtil.simplifyCase() should account for nullability</a>. */
@Test void testSimplifyCaseNotNullableBoolean() {
  RexNode condition = eq(vVarchar(), literal("S"));
  RexCall caseNode = (RexCall) case_(condition, trueLiteral, falseLiteral);

  final RexCall result = (RexCall) simplify.simplifyUnknownAs(caseNode, RexUnknownAs.UNKNOWN);
  assertThat("The case should be nonNullable", caseNode.getType().isNullable(), is(false));
  assertThat("Expected a nonNullable type", result.getType().isNullable(), is(false));
  assertThat(result.getType().getSqlTypeName(), is(SqlTypeName.BOOLEAN));
  assertThat(result.getOperator(), is((SqlOperator) SqlStdOperatorTable.IS_TRUE));
  assertThat(result.getOperands().get(0), is(condition));
}
 
Example 28
Source Project: flink   Source File: SqlTimestampType.java    License: Apache License 2.0 5 votes vote down vote up
private static String getTypeName(boolean withLocalTimeZone) {
	if (withLocalTimeZone) {
		return SqlTypeName.TIMESTAMP_WITH_LOCAL_TIME_ZONE.name();
	} else {
		return SqlTypeName.TIMESTAMP.name();
	}
}
 
Example 29
Source Project: marble   Source File: TypeInferenceUtil.java    License: Apache License 2.0 5 votes vote down vote up
private static ObjectInspector getPrimitiveObjectInspector(
    RelDataTypeHolder relDataTypeHolder) {
  SqlTypeName sqlTypeName = relDataTypeHolder.getSqlTypeName();

  //FIXME Hive TypeInfoFactory.decimalTypeInfo use a default scale and
  // precision
  PrimitiveTypeInfo primitiveTypeInfo = CALCITE_SQL_TYPE_2_HIVE_TYPE_INFO.get(
      sqlTypeName);
  if (primitiveTypeInfo == null) {
    throw new IllegalArgumentException(
        "can't find hive primitiveTypeInfo for Calcite SqlType: "
            + sqlTypeName);
  }
  ObjectInspector result;
  if (relDataTypeHolder.isConstant()) {
    Object value = relDataTypeHolder.getValue();
    Object hiveWritableValue = convertCalciteObject2HiveWritableObject(
        relDataTypeHolder,
        value);
    result =
        PrimitiveObjectInspectorFactory
            .getPrimitiveWritableConstantObjectInspector(
                primitiveTypeInfo, hiveWritableValue);
  } else {
    result =
        PrimitiveObjectInspectorFactory.getPrimitiveWritableObjectInspector(
            primitiveTypeInfo);
  }

  return result;
}
 
Example 30
Source Project: calcite   Source File: JdbcToEnumerableConverter.java    License: Apache License 2.0 5 votes vote down vote up
private Method getMethod2(SqlTypeName sqlTypeName) {
  switch (sqlTypeName) {
  case DATE:
    return BuiltInMethod.RESULT_SET_GET_DATE2.method;
  case TIME:
    return BuiltInMethod.RESULT_SET_GET_TIME2.method;
  case TIMESTAMP:
    return BuiltInMethod.RESULT_SET_GET_TIMESTAMP2.method;
  default:
    throw new AssertionError(sqlTypeName);
  }
}