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

The following examples show how to use org.apache.calcite.sql.type.SqlTypeUtil. 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: ReduceDecimalsRule.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public RexNode expand(RexCall call) {
    ImmutableList.Builder<RexNode> opBuilder = ImmutableList.builder();
    for (RexNode operand : call.getOperands()) {
        if (SqlTypeUtil.isNumeric(operand.getType())) {
            opBuilder.add(accessValue(operand));
        } else {
            opBuilder.add(operand);
        }
    }

    RexNode newCall = builder.makeCall(call.getType(), call.getOperator(), opBuilder.build());
    if (SqlTypeUtil.isDecimal(call.getType())) {
        return encodeValue(newCall, call.getType());
    } else {
        return newCall;
    }
}
 
Example 2
Source Project: calcite   Source File: RexSimplify.java    License: Apache License 2.0 6 votes vote down vote up
public RexNode simplifyPreservingType(RexNode e, RexUnknownAs unknownAs,
    boolean matchNullability) {
  final RexNode e2 = simplifyUnknownAs(e, unknownAs);
  if (e2.getType() == e.getType()) {
    return e2;
  }
  if (!matchNullability
      && SqlTypeUtil.equalSansNullability(rexBuilder.typeFactory, e2.getType(), e.getType())) {
    return e2;
  }
  final RexNode e3 = rexBuilder.makeCast(e.getType(), e2, matchNullability);
  if (e3.equals(e)) {
    return e;
  }
  return e3;
}
 
Example 3
Source Project: Bats   Source File: RelStructuredTypeFlattener.java    License: Apache License 2.0 6 votes vote down vote up
private int calculateFlattenedOffset(RelDataType rowType, int ordinal) {
    int offset = 0;
    if (SqlTypeUtil.needsNullIndicator(rowType)) {
        // skip null indicator
        ++offset;
    }
    List<RelDataTypeField> oldFields = rowType.getFieldList();
    for (int i = 0; i < ordinal; ++i) {
        RelDataType oldFieldType = oldFields.get(i).getType();
        if (oldFieldType.isStruct()) {
            // TODO jvs 10-Feb-2005: this isn't terribly efficient;
            // keep a mapping somewhere
            RelDataType flattened = SqlTypeUtil.flattenRecordType(rexBuilder.getTypeFactory(), oldFieldType, null);
            final List<RelDataTypeField> fields = flattened.getFieldList();
            offset += fields.size();
        } else {
            ++offset;
        }
    }
    return offset;
}
 
Example 4
Source Project: Bats   Source File: StandardConvertletTable.java    License: Apache License 2.0 6 votes vote down vote up
private Pair<RexNode, RexNode> convertOverlapsOperand(SqlRexContext cx,
    SqlParserPos pos, SqlNode operand) {
  final SqlNode a0;
  final SqlNode a1;
  switch (operand.getKind()) {
  case ROW:
    a0 = ((SqlCall) operand).operand(0);
    final SqlNode a10 = ((SqlCall) operand).operand(1);
    final RelDataType t1 = cx.getValidator().getValidatedNodeType(a10);
    if (SqlTypeUtil.isInterval(t1)) {
      // make t1 = t0 + t1 when t1 is an interval.
      a1 = plus(pos, a0, a10);
    } else {
      a1 = a10;
    }
    break;
  default:
    a0 = operand;
    a1 = operand;
  }

  final RexNode r0 = cx.convertExpression(a0);
  final RexNode r1 = cx.convertExpression(a1);
  return Pair.of(r0, r1);
}
 
Example 5
Source Project: Bats   Source File: SqlDialect.java    License: Apache License 2.0 6 votes vote down vote up
public SqlNode getCastSpec(RelDataType type) {
  if (type instanceof BasicSqlType) {
    int precision = type.getPrecision();
    switch (type.getSqlTypeName()) {
    case VARCHAR:
      // if needed, adjust varchar length to max length supported by the system
      int maxPrecision = getTypeSystem().getMaxPrecision(type.getSqlTypeName());
      if (type.getPrecision() > maxPrecision) {
        precision = maxPrecision;
      }
    }
    return new SqlDataTypeSpec(
        new SqlIdentifier(type.getSqlTypeName().name(), SqlParserPos.ZERO),
            precision,
            type.getScale(),
            type.getCharset() != null
                && supportsCharSet()
                ? type.getCharset().name()
                : null,
            null,
            SqlParserPos.ZERO);
  }
  return SqlTypeUtil.convertTypeToSpec(type);
}
 
Example 6
Source Project: calcite   Source File: AbstractTypeCoercion.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Sync the data type additional attributes before casting,
 * i.e. nullability, charset, collation.
 */
RelDataType syncAttributes(
    RelDataType fromType,
    RelDataType toType) {
  RelDataType syncedType = toType;
  if (fromType != null) {
    syncedType = factory.createTypeWithNullability(syncedType, fromType.isNullable());
    if (SqlTypeUtil.inCharOrBinaryFamilies(fromType)
        && SqlTypeUtil.inCharOrBinaryFamilies(toType)) {
      Charset charset = fromType.getCharset();
      SqlCollation collation = fromType.getCollation();
      if (charset != null && SqlTypeUtil.inCharFamily(syncedType)) {
        syncedType = factory.createTypeWithCharsetAndCollation(syncedType,
            charset,
            collation);
      }
    }
  }
  return syncedType;
}
 
Example 7
Source Project: Bats   Source File: SqlLiteralChainOperator.java    License: Apache License 2.0 6 votes vote down vote up
private boolean argTypesValid(SqlCallBinding callBinding) {
  if (callBinding.getOperandCount() < 2) {
    return true; // nothing to compare
  }
  RelDataType firstType = null;
  for (Ord<SqlNode> operand : Ord.zip(callBinding.operands())) {
    RelDataType type =
        callBinding.getValidator().deriveType(
            callBinding.getScope(),
            operand.e);
    if (operand.i == 0) {
      firstType = type;
    } else {
      if (!SqlTypeUtil.sameNamedType(firstType, type)) {
        return false;
      }
    }
  }
  return true;
}
 
Example 8
Source Project: calcite   Source File: SqlDialect.java    License: Apache License 2.0 6 votes vote down vote up
/** Returns SqlNode for type in "cast(column as type)", which might be
* different between databases by type name, precision etc. */
public SqlNode getCastSpec(RelDataType type) {
  if (type instanceof BasicSqlType) {
    int maxPrecision = -1;
    switch (type.getSqlTypeName()) {
    case VARCHAR:
      // if needed, adjust varchar length to max length supported by the system
      maxPrecision = getTypeSystem().getMaxPrecision(type.getSqlTypeName());
    }
    String charSet = type.getCharset() != null && supportsCharSet()
        ? type.getCharset().name()
        : null;
    return SqlTypeUtil.convertTypeToSpec(type, charSet, maxPrecision);
  }
  return SqlTypeUtil.convertTypeToSpec(type);
}
 
Example 9
Source Project: Bats   Source File: SqlMultisetValueConstructor.java    License: Apache License 2.0 6 votes vote down vote up
public boolean checkOperandTypes(
    SqlCallBinding callBinding,
    boolean throwOnFailure) {
  final List<RelDataType> argTypes =
      SqlTypeUtil.deriveAndCollectTypes(
          callBinding.getValidator(),
          callBinding.getScope(),
          callBinding.operands());
  if (argTypes.size() == 0) {
    throw callBinding.newValidationError(RESOURCE.requireAtLeastOneArg());
  }
  final RelDataType componentType =
      getComponentType(
          callBinding.getTypeFactory(),
          argTypes);
  if (null == componentType) {
    if (throwOnFailure) {
      throw callBinding.newValidationError(RESOURCE.needSameTypeParameter());
    }
    return false;
  }
  return true;
}
 
Example 10
Source Project: calcite   Source File: AbstractTypeCoercion.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Promote all the way to VARCHAR.
 */
private RelDataType promoteToVarChar(RelDataType type1, RelDataType type2) {
  RelDataType resultType = null;
  // No promotion for char and varchar.
  if (SqlTypeUtil.isCharacter(type1) && SqlTypeUtil.isCharacter(type2)) {
    return null;
  }
  // 1. Do not distinguish CHAR and VARCHAR, i.e. (INTEGER + CHAR(3))
  //    and (INTEGER + VARCHAR(5)) would both deduce VARCHAR type.
  // 2. VARCHAR has 65536 as default precision.
  // 3. Following MS-SQL: BINARY or BOOLEAN can be casted to VARCHAR.
  if (SqlTypeUtil.isAtomic(type1) && SqlTypeUtil.isCharacter(type2)) {
    resultType = factory.createSqlType(SqlTypeName.VARCHAR);
  }

  if (SqlTypeUtil.isCharacter(type1) && SqlTypeUtil.isAtomic(type2)) {
    resultType = factory.createSqlType(SqlTypeName.VARCHAR);
  }
  return resultType;
}
 
Example 11
Source Project: Bats   Source File: SqlJsonObjectFunction.java    License: Apache License 2.0 6 votes vote down vote up
@Override public boolean checkOperandTypes(SqlCallBinding callBinding,
    boolean throwOnFailure) {
  final int count = callBinding.getOperandCount();
  for (int i = 1; i < count; i += 2) {
    RelDataType nameType = callBinding.getOperandType(i);
    if (!SqlTypeUtil.inCharFamily(nameType)) {
      if (throwOnFailure) {
        throw callBinding.newError(RESOURCE.expectedCharacter());
      }
      return false;
    }
    if (nameType.isNullable()) {
      if (throwOnFailure) {
        throw callBinding.newError(
            RESOURCE.argumentMustNotBeNull(
                callBinding.operand(i).toString()));
      }
      return false;
    }
  }
  return true;
}
 
Example 12
Source Project: Bats   Source File: SqlMapValueConstructor.java    License: Apache License 2.0 6 votes vote down vote up
public boolean checkOperandTypes(
    SqlCallBinding callBinding,
    boolean throwOnFailure) {
  final List<RelDataType> argTypes =
      SqlTypeUtil.deriveAndCollectTypes(
          callBinding.getValidator(),
          callBinding.getScope(),
          callBinding.operands());
  if (argTypes.size() == 0) {
    throw callBinding.newValidationError(RESOURCE.mapRequiresTwoOrMoreArgs());
  }
  if (argTypes.size() % 2 > 0) {
    throw callBinding.newValidationError(RESOURCE.mapRequiresEvenArgCount());
  }
  final Pair<RelDataType, RelDataType> componentType =
      getComponentTypes(
          callBinding.getTypeFactory(), argTypes);
  if (null == componentType.left || null == componentType.right) {
    if (throwOnFailure) {
      throw callBinding.newValidationError(RESOURCE.needSameTypeParameter());
    }
    return false;
  }
  return true;
}
 
Example 13
Source Project: calcite   Source File: SqlSessionTableFunction.java    License: Apache License 2.0 6 votes vote down vote up
@Override public boolean checkOperandTypes(SqlCallBinding callBinding,
    boolean throwOnFailure) {
  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 SqlNode operand2 = callBinding.operand(2);
  if (operand2.getKind() != SqlKind.DESCRIPTOR) {
    return throwValidationSignatureErrorOrReturnFalse(callBinding, throwOnFailure);
  }
  validateColumnNames(validator, type.getFieldNames(), ((SqlCall) operand2).getOperandList());
  final RelDataType type3 = validator.getValidatedNodeType(callBinding.operand(3));
  if (!SqlTypeUtil.isInterval(type3)) {
    return throwValidationSignatureErrorOrReturnFalse(callBinding, throwOnFailure);
  }
  return true;
}
 
Example 14
Source Project: calcite   Source File: SqlLiteralChainOperator.java    License: Apache License 2.0 6 votes vote down vote up
private boolean argTypesValid(SqlCallBinding callBinding) {
  if (callBinding.getOperandCount() < 2) {
    return true; // nothing to compare
  }
  RelDataType firstType = null;
  for (Ord<SqlNode> operand : Ord.zip(callBinding.operands())) {
    RelDataType type =
        callBinding.getValidator().deriveType(
            callBinding.getScope(),
            operand.e);
    if (operand.i == 0) {
      firstType = type;
    } else {
      if (!SqlTypeUtil.sameNamedType(firstType, type)) {
        return false;
      }
    }
  }
  return true;
}
 
Example 15
Source Project: flink   Source File: SqlValidatorImpl.java    License: Apache License 2.0 6 votes vote down vote up
protected void validateWhereOrOn(
	SqlValidatorScope scope,
	SqlNode condition,
	String clause) {
	validateNoAggs(aggOrOverOrGroupFinder, condition, clause);
	inferUnknownTypes(
		booleanType,
		scope,
		condition);
	condition.validate(this, scope);

	final RelDataType type = deriveType(scope, condition);
	if (!SqlTypeUtil.inBooleanFamily(type)) {
		throw newValidationError(condition, RESOURCE.condMustBeBoolean(clause));
	}
}
 
Example 16
Source Project: calcite   Source File: SqlHopTableFunction.java    License: Apache License 2.0 6 votes vote down vote up
@Override public boolean checkOperandTypes(SqlCallBinding callBinding,
    boolean throwOnFailure) {
  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);
  }
  final RelDataType type3 = validator.getValidatedNodeType(callBinding.operand(3));
  if (!SqlTypeUtil.isInterval(type3)) {
    return throwValidationSignatureErrorOrReturnFalse(callBinding, throwOnFailure);
  }
  return true;
}
 
Example 17
Source Project: calcite   Source File: SqlMapValueConstructor.java    License: Apache License 2.0 6 votes vote down vote up
public boolean checkOperandTypes(
    SqlCallBinding callBinding,
    boolean throwOnFailure) {
  final List<RelDataType> argTypes =
      SqlTypeUtil.deriveAndCollectTypes(
          callBinding.getValidator(),
          callBinding.getScope(),
          callBinding.operands());
  if (argTypes.size() == 0) {
    throw callBinding.newValidationError(RESOURCE.mapRequiresTwoOrMoreArgs());
  }
  if (argTypes.size() % 2 > 0) {
    throw callBinding.newValidationError(RESOURCE.mapRequiresEvenArgCount());
  }
  final Pair<RelDataType, RelDataType> componentType =
      getComponentTypes(
          callBinding.getTypeFactory(), argTypes);
  if (null == componentType.left || null == componentType.right) {
    if (throwOnFailure) {
      throw callBinding.newValidationError(RESOURCE.needSameTypeParameter());
    }
    return false;
  }
  return true;
}
 
Example 18
Source Project: dremio-oss   Source File: ValuesRel.java    License: Apache License 2.0 6 votes vote down vote up
private static void verifyRowType(final ImmutableList<ImmutableList<RexLiteral>> tuples, RelDataType rowType){
    for (List<RexLiteral> tuple : tuples) {
      assert (tuple.size() == rowType.getFieldCount());

      for (Pair<RexLiteral, RelDataTypeField> pair : Pair.zip(tuple, rowType.getFieldList())) {
        RexLiteral literal = pair.left;
        RelDataType fieldType = pair.right.getType();

        if ((!(RexLiteral.isNullLiteral(literal)))
            && (!(SqlTypeUtil.canAssignFrom(fieldType, literal.getType())))) {
          throw new AssertionError("to " + fieldType + " from " + literal);
        }
      }
    }

}
 
Example 19
Source Project: calcite   Source File: TypeCoercionImpl.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Datetime and STRING equality: cast STRING type to datetime type, SqlToRelConverter already
 * makes the conversion but we still keep this interface overridable
 * so user can have their custom implementation.
 */
protected boolean dateTimeStringEquality(
    SqlCallBinding binding,
    RelDataType left,
    RelDataType right) {
  // REVIEW Danny 2018-05-23 we do not need to coerce type for EQUALS
  // because SqlToRelConverter already does this.
  // REVIEW Danny 2019-09-23, we should unify the coercion rules in TypeCoercion
  // instead of SqlToRelConverter.
  if (SqlTypeUtil.isCharacter(left)
      && SqlTypeUtil.isDatetime(right)) {
    return coerceOperandType(binding.getScope(), binding.getCall(), 0, right);
  }
  if (SqlTypeUtil.isCharacter(right)
      && SqlTypeUtil.isDatetime(left)) {
    return coerceOperandType(binding.getScope(), binding.getCall(), 1, left);
  }
  return false;
}
 
Example 20
Source Project: calcite   Source File: RelDataTypeFactoryImpl.java    License: Apache License 2.0 6 votes vote down vote up
private RelDataType copySimpleType(
    RelDataType type,
    boolean nullable) {
  if (type instanceof JavaType) {
    JavaType javaType = (JavaType) type;
    if (SqlTypeUtil.inCharFamily(javaType)) {
      return new JavaType(
          javaType.clazz,
          nullable,
          javaType.charset,
          javaType.collation);
    } else {
      return new JavaType(
          nullable
              ? Primitive.box(javaType.clazz)
              : Primitive.unbox(javaType.clazz),
          nullable);
    }
  } else {
    // REVIEW: RelCrossType if it stays around; otherwise get rid of
    // this comment
    return type;
  }
}
 
Example 21
Source Project: calcite   Source File: AggregateCall.java    License: Apache License 2.0 6 votes vote down vote up
/** Creates an AggregateCall, inferring its type if {@code type} is null. */
public static AggregateCall create(SqlAggFunction aggFunction,
    boolean distinct, boolean approximate, boolean ignoreNulls,
    List<Integer> argList, int filterArg, RelCollation collation,
    int groupCount,
    RelNode input, RelDataType type, String name) {
  if (type == null) {
    final RelDataTypeFactory typeFactory =
        input.getCluster().getTypeFactory();
    final List<RelDataType> types =
        SqlTypeUtil.projectTypes(input.getRowType(), argList);
    final Aggregate.AggCallBinding callBinding =
        new Aggregate.AggCallBinding(typeFactory, aggFunction, types,
            groupCount, filterArg >= 0);
    type = aggFunction.inferReturnType(callBinding);
  }
  return create(aggFunction, distinct, approximate, ignoreNulls, argList,
      filterArg, collation, type, name);
}
 
Example 22
Source Project: calcite   Source File: TypeCoercionImpl.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Coerces operands in binary arithmetic expressions to NUMERIC types.
 *
 * <p>For binary arithmetic operators like [+, -, *, /, %]:
 * If the operand is VARCHAR,
 * coerce it to data type of the other operand if its data type is NUMERIC;
 * If the other operand is DECIMAL,
 * coerce the STRING operand to max precision/scale DECIMAL.
 */
public boolean binaryArithmeticCoercion(SqlCallBinding binding) {
  // Assume the operator has NUMERIC family operand type checker.
  SqlOperator operator = binding.getOperator();
  SqlKind kind = operator.getKind();
  boolean coerced = false;
  // Binary operator
  if (binding.getOperandCount() == 2) {
    final RelDataType type1 = binding.getOperandType(0);
    final RelDataType type2 = binding.getOperandType(1);
    // Special case for datetime + interval or datetime - interval
    if (kind == SqlKind.PLUS || kind == SqlKind.MINUS) {
      if (SqlTypeUtil.isInterval(type1) || SqlTypeUtil.isInterval(type2)) {
        return false;
      }
    }
    // Binary arithmetic operator like: + - * / %
    if (kind.belongsTo(SqlKind.BINARY_ARITHMETIC)) {
      coerced = binaryArithmeticWithStrings(binding, type1, type2);
    }
  }
  return coerced;
}
 
Example 23
Source Project: calcite   Source File: SqlMultisetQueryConstructor.java    License: Apache License 2.0 6 votes vote down vote up
public boolean checkOperandTypes(
    SqlCallBinding callBinding,
    boolean throwOnFailure) {
  final List<RelDataType> argTypes =
      SqlTypeUtil.deriveAndCollectTypes(
          callBinding.getValidator(),
          callBinding.getScope(),
          callBinding.operands());
  final RelDataType componentType =
      getComponentType(
          callBinding.getTypeFactory(),
          argTypes);
  if (null == componentType) {
    if (throwOnFailure) {
      throw callBinding.newValidationError(RESOURCE.needSameTypeParameter());
    }
    return false;
  }
  return true;
}
 
Example 24
Source Project: Bats   Source File: RelDataTypeFactoryImpl.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 *
 * <p>Implement RelDataTypeFactory with SQL 2003 compliant behavior. Let p1,
 * s1 be the precision and scale of the first operand Let p2, s2 be the
 * precision and scale of the second operand Let p, s be the precision and
 * scale of the result, Then the result type is a decimal with:
 *
 * <ul>
 * <li>p = p1 + p2</li>
 * <li>s = s1 + s2</li>
 * </ul>
 *
 * <p>p and s are capped at their maximum values
 *
 * @see Glossary#SQL2003 SQL:2003 Part 2 Section 6.26
 */
public RelDataType createDecimalProduct(
    RelDataType type1,
    RelDataType type2) {
  if (SqlTypeUtil.isExactNumeric(type1)
      && SqlTypeUtil.isExactNumeric(type2)) {
    if (SqlTypeUtil.isDecimal(type1)
        || SqlTypeUtil.isDecimal(type2)) {
      int p1 = type1.getPrecision();
      int p2 = type2.getPrecision();
      int s1 = type1.getScale();
      int s2 = type2.getScale();

      int scale = s1 + s2;
      scale = Math.min(scale, typeSystem.getMaxNumericScale());
      int precision = p1 + p2;
      precision =
          Math.min(
              precision,
              typeSystem.getMaxNumericPrecision());

      RelDataType ret;
      ret =
          createSqlType(
              SqlTypeName.DECIMAL,
              precision,
              scale);

      return ret;
    }
  }

  return null;
}
 
Example 25
Source Project: calcite   Source File: StandardConvertletTable.java    License: Apache License 2.0 5 votes vote down vote up
private SqlNode getCastedSqlNode(SqlNode argInput, RelDataType varType,
    SqlParserPos pos, RexNode argRex) {
  SqlNode arg;
  if (argRex != null && !argRex.getType().equals(varType)) {
    arg = SqlStdOperatorTable.CAST.createCall(
        pos, argInput, SqlTypeUtil.convertTypeToSpec(varType));
  } else {
    arg = argInput;
  }
  return arg;
}
 
Example 26
Source Project: Bats   Source File: RelStructuredTypeFlattener.java    License: Apache License 2.0 5 votes vote down vote up
private void flattenNullLiteral(RelDataType type, List<Pair<RexNode, String>> flattenedExps) {
    RelDataType flattenedType = SqlTypeUtil.flattenRecordType(rexBuilder.getTypeFactory(), type, null);
    for (RelDataTypeField field : flattenedType.getFieldList()) {
        flattenedExps
                .add(Pair.of(rexBuilder.makeCast(field.getType(), rexBuilder.constantNull()), field.getName()));
    }
}
 
Example 27
Source Project: Bats   Source File: RelStructuredTypeFlattener.java    License: Apache License 2.0 5 votes vote down vote up
public void rewriteRel(TableScan rel) {
    RelNode newRel = rel.getTable().toRel(toRelContext);
    if (!SqlTypeUtil.isFlat(rel.getRowType())) {
        final List<Pair<RexNode, String>> flattenedExpList = new ArrayList<>();
        flattenInputs(rel.getRowType().getFieldList(), rexBuilder.makeRangeReference(newRel), flattenedExpList);
        newRel = relBuilder.push(newRel)
                .projectNamed(Pair.left(flattenedExpList), Pair.right(flattenedExpList), true).build();
    }
    setNewForOldRel(rel, newRel);
}
 
Example 28
Source Project: Bats   Source File: StandardConvertletTable.java    License: Apache License 2.0 5 votes vote down vote up
private static RelDataType consistentType(SqlRexContext cx,
    SqlOperandTypeChecker.Consistency consistency, List<RelDataType> types) {
  switch (consistency) {
  case COMPARE:
    if (SqlTypeUtil.areSameFamily(types)) {
      // All arguments are of same family. No need for explicit casts.
      return null;
    }
    final List<RelDataType> nonCharacterTypes = new ArrayList<>();
    for (RelDataType type : types) {
      if (type.getFamily() != SqlTypeFamily.CHARACTER) {
        nonCharacterTypes.add(type);
      }
    }
    if (!nonCharacterTypes.isEmpty()) {
      final int typeCount = types.size();
      types = nonCharacterTypes;
      if (nonCharacterTypes.size() < typeCount) {
        final RelDataTypeFamily family =
            nonCharacterTypes.get(0).getFamily();
        if (family instanceof SqlTypeFamily) {
          // The character arguments might be larger than the numeric
          // argument. Give ourselves some headroom.
          switch ((SqlTypeFamily) family) {
          case INTEGER:
          case NUMERIC:
            nonCharacterTypes.add(
                cx.getTypeFactory().createSqlType(SqlTypeName.BIGINT));
          }
        }
      }
    }
    // fall through
  case LEAST_RESTRICTIVE:
    return cx.getTypeFactory().leastRestrictive(types);
  default:
    return null;
  }
}
 
Example 29
Source Project: Bats   Source File: StandardConvertletTable.java    License: Apache License 2.0 5 votes vote down vote up
private SqlNode getCastedSqlNode(SqlNode argInput, RelDataType varType,
    SqlParserPos pos, RexNode argRex) {
  SqlNode arg;
  if (argRex != null && !argRex.getType().equals(varType)) {
    arg = SqlStdOperatorTable.CAST.createCall(
        pos, argInput, SqlTypeUtil.convertTypeToSpec(varType));
  } else {
    arg = argInput;
  }
  return arg;
}
 
Example 30
Source Project: calcite   Source File: SqlOverlapsOperator.java    License: Apache License 2.0 5 votes vote down vote up
public boolean checkOperandTypes(SqlCallBinding callBinding,
    boolean throwOnFailure) {
  if (!OperandTypes.PERIOD.checkSingleOperandType(callBinding,
      callBinding.operand(0), 0, throwOnFailure)) {
    return false;
  }
  final SqlSingleOperandTypeChecker rightChecker;
  switch (kind) {
  case CONTAINS:
    rightChecker = OperandTypes.PERIOD_OR_DATETIME;
    break;
  default:
    rightChecker = OperandTypes.PERIOD;
    break;
  }
  if (!rightChecker.checkSingleOperandType(callBinding,
      callBinding.operand(1), 0, throwOnFailure)) {
    return false;
  }
  final RelDataType t0 = callBinding.getOperandType(0);
  final RelDataType t1 = callBinding.getOperandType(1);
  if (!SqlTypeUtil.isDatetime(t1)) {
    final RelDataType t00 = t0.getFieldList().get(0).getType();
    final RelDataType t10 = t1.getFieldList().get(0).getType();
    if (!SqlTypeUtil.sameNamedType(t00, t10)) {
      if (throwOnFailure) {
        throw callBinding.newValidationSignatureError();
      }
      return false;
    }
  }
  return true;
}