Java Code Examples for org.apache.calcite.sql.SqlOperatorBinding#getOperandType()

The following examples show how to use org.apache.calcite.sql.SqlOperatorBinding#getOperandType() . 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: SqlDotOperator.java    From Bats with Apache License 2.0 6 votes vote down vote up
@Override public RelDataType inferReturnType(SqlOperatorBinding opBinding) {
  final RelDataTypeFactory typeFactory = opBinding.getTypeFactory();
  final RelDataType recordType = opBinding.getOperandType(0);
  switch (recordType.getSqlTypeName()) {
  case ROW:
    final String fieldName =
        opBinding.getOperandLiteralValue(1, String.class);
    final RelDataType type = opBinding.getOperandType(0)
        .getField(fieldName, false, false)
        .getType();
    if (recordType.isNullable()) {
      return typeFactory.createTypeWithNullability(type, true);
    } else {
      return type;
    }
  default:
    throw new AssertionError();
  }
}
 
Example 2
Source File: FlinkReturnTypes.java    From flink with Apache License 2.0 6 votes vote down vote up
@Override
public RelDataType inferReturnType(SqlOperatorBinding opBinding) {
	final RelDataType numType = opBinding.getOperandType(0);
	if (numType.getSqlTypeName() != SqlTypeName.DECIMAL) {
		return numType;
	}
	final BigDecimal lenVal;
	if (opBinding.getOperandCount() == 1) {
		lenVal = BigDecimal.ZERO;
	} else if (opBinding.getOperandCount() == 2) {
		lenVal = getArg1Literal(opBinding); // may return null
	} else {
		throw new AssertionError();
	}
	if (lenVal == null) {
		return numType; //
	}
	// ROUND( decimal(p,s), r )
	final int p = numType.getPrecision();
	final int s = numType.getScale();
	final int r = lenVal.intValueExact();
	DecimalType dt = LogicalTypeMerging.findRoundDecimalType(p, s, r);
	return opBinding.getTypeFactory().createSqlType(
		SqlTypeName.DECIMAL, dt.getPrecision(), dt.getScale());
}
 
Example 3
Source File: FlinkReturnTypes.java    From flink with Apache License 2.0 6 votes vote down vote up
@Override
public RelDataType inferReturnType(SqlOperatorBinding opBinding) {
	final RelDataType numType = opBinding.getOperandType(0);
	if (numType.getSqlTypeName() != SqlTypeName.DECIMAL) {
		return numType;
	}
	final BigDecimal lenVal;
	if (opBinding.getOperandCount() == 1) {
		lenVal = BigDecimal.ZERO;
	} else if (opBinding.getOperandCount() == 2) {
		lenVal = getArg1Literal(opBinding); // may return null
	} else {
		throw new AssertionError();
	}
	if (lenVal == null) {
		return numType; //
	}
	// ROUND( decimal(p,s), r )
	final int p = numType.getPrecision();
	final int s = numType.getScale();
	final int r = lenVal.intValueExact();
	DecimalType dt = FlinkTypeSystem.inferRoundType(p, s, r);
	return opBinding.getTypeFactory().createSqlType(
		SqlTypeName.DECIMAL, dt.getPrecision(), dt.getScale());
}
 
Example 4
Source File: MatchReturnTypeInference.java    From calcite with Apache License 2.0 5 votes vote down vote up
public RelDataType inferReturnType(
    SqlOperatorBinding opBinding) {
  for (int i = start; i < opBinding.getOperandCount(); i++) {
    RelDataType argType = opBinding.getOperandType(i);
    if (SqlTypeUtil.isOfSameTypeName(typeNames, argType)) {
      return argType;
    }
  }
  return null;
}
 
Example 5
Source File: SqlDatetimePlusOperator.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Override public RelDataType inferReturnType(SqlOperatorBinding opBinding) {
  final RelDataTypeFactory typeFactory = opBinding.getTypeFactory();
  final RelDataType leftType = opBinding.getOperandType(0);
  final IntervalSqlType unitType =
      (IntervalSqlType) opBinding.getOperandType(1);
  final TimeUnit timeUnit = unitType.getIntervalQualifier().getStartUnit();
  return SqlTimestampAddFunction.deduceType(typeFactory, timeUnit,
      unitType, leftType);
}
 
Example 6
Source File: SqlItemOperator.java    From calcite with 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 7
Source File: NumericOrDefaultReturnTypeInference.java    From flink with Apache License 2.0 5 votes vote down vote up
@Override
public RelDataType inferReturnType(SqlOperatorBinding opBinding) {
	int nOperands = opBinding.getOperandCount();
	List<RelDataType> types = new ArrayList<>();
	for (int i = startTypeIdx; i < nOperands; i++) {
		RelDataType type = opBinding.getOperandType(i);
		if (SqlTypeUtil.isNumeric(type)) {
			types.add(type);
		} else {
			return opBinding.getOperandType(defaultTypeIdx);
		}
	}
	return opBinding.getTypeFactory().leastRestrictive(types);
}
 
Example 8
Source File: TypeInferenceUtils.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Given a SqlOperatorBinding, convert it to FunctionCall
 * @param  opBinding    the given SqlOperatorBinding
 * @return FunctionCall the converted FunctionCall
 */
public static FunctionCall convertSqlOperatorBindingToFunctionCall(final SqlOperatorBinding opBinding) {
  final List<LogicalExpression> args = Lists.newArrayList();

  for (int i = 0; i < opBinding.getOperandCount(); ++i) {
    final RelDataType type = opBinding.getOperandType(i);
    final TypeProtos.MinorType minorType = getMinorTypeFromCalciteType(type);
    CompleteType completeType = CompleteType.fromMinorType(minorType);
    args.add(new CompleteTypeInLogicalExpression(completeType));
  }

  final String funcName = FunctionCallFactory.replaceOpWithFuncName(opBinding.getOperator().getName());
  final FunctionCall functionCall = new FunctionCall(funcName, args);
  return functionCall;
}
 
Example 9
Source File: HiveSqlUDAFReturnTypeInference.java    From marble with Apache License 2.0 5 votes vote down vote up
@Override public RelDataType inferReturnType(
    final SqlOperatorBinding opBinding) {
  try {
    RelDataTypeFactory factory = opBinding.getTypeFactory();
    SqlOperator sqlOperator = opBinding.getOperator();
    String opName = sqlOperator.getName();
    Class hiveUDAFClass = HiveSqlOperatorTable.instance()
        .getHiveUDAFClass(opName);
    List<RelDataTypeHolder> argsType = new ArrayList<>();

    for (int i = 0; i < opBinding.getOperandCount(); i++) {
      RelDataTypeHolder relDataTypeHolder;
      if (TypeInferenceUtil.isOperandConstantForHiveUDAF(hiveUDAFClass, i)) {
        //we use a pre-defined fake value here to getGenericUDAFReturnType
        Object constantValue = TypeInferenceUtil
            .HIVE_UDAF_CONSTANT_OBJECT_INSPECT_CONTEXT_MAP
            .get(hiveUDAFClass).get(i);
        relDataTypeHolder = new RelDataTypeHolder(opBinding.getOperandType(i),
            true, constantValue);
      } else {
        relDataTypeHolder = new RelDataTypeHolder(
            opBinding.getOperandType(i));
      }
      argsType.add(relDataTypeHolder);
    }
    RelDataType resultType = getGenericUDAFReturnType(
        hiveUDAFClass,
        argsType.toArray(new RelDataTypeHolder[0]), factory);
    return resultType;
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}
 
Example 10
Source File: NumericOrDefaultReturnTypeInference.java    From flink with Apache License 2.0 5 votes vote down vote up
@Override
public RelDataType inferReturnType(SqlOperatorBinding opBinding) {
	int nOperands = opBinding.getOperandCount();
	List<RelDataType> types = new ArrayList<>();
	for (int i = startTypeIdx; i < nOperands; i++) {
		RelDataType type = opBinding.getOperandType(i);
		if (SqlTypeUtil.isNumeric(type)) {
			types.add(type);
		} else {
			return opBinding.getOperandType(defaultTypeIdx);
		}
	}
	return opBinding.getTypeFactory().leastRestrictive(types);
}
 
Example 11
Source File: TypeInferenceUtils.java    From Bats with Apache License 2.0 5 votes vote down vote up
/**
 * Given a SqlOperatorBinding, convert it to FunctionCall
 * @param  opBinding    the given SqlOperatorBinding
 * @return FunctionCall the converted FunctionCall
 */
public static FunctionCall convertSqlOperatorBindingToFunctionCall(final SqlOperatorBinding opBinding) {
  final List<LogicalExpression> args = Lists.newArrayList();

  for (int i = 0; i < opBinding.getOperandCount(); ++i) {
    final RelDataType type = opBinding.getOperandType(i);
    final TypeProtos.MinorType minorType = getDrillTypeFromCalciteType(type);
    TypeProtos.DataMode dataMode =
        type.isNullable() ? TypeProtos.DataMode.OPTIONAL : TypeProtos.DataMode.REQUIRED;

    TypeProtos.MajorType.Builder builder =
        TypeProtos.MajorType.newBuilder()
            .setMode(dataMode)
            .setMinorType(minorType);

    if (Types.isDecimalType(minorType)) {
      builder
          .setScale(type.getScale())
          .setPrecision(type.getPrecision());
    }

    args.add(new MajorTypeInLogicalExpression(builder.build()));
  }

  final String drillFuncName = FunctionCallFactory.replaceOpWithFuncName(opBinding.getOperator().getName());
  return new FunctionCall(
      drillFuncName,
      args,
      ExpressionPosition.UNKNOWN);
}
 
Example 12
Source File: TypeInferenceUtils.java    From Bats with Apache License 2.0 5 votes vote down vote up
@Override
public RelDataType inferReturnType(SqlOperatorBinding opBinding) {
  if (preserveNullability) {
    return opBinding.getOperandType(0);
  }
  return opBinding.getTypeFactory().createTypeWithNullability(opBinding.getOperandType(0), true);
}
 
Example 13
Source File: ComparableOperandTypeChecker.java    From Bats with Apache License 2.0 5 votes vote down vote up
/**
 * Similar functionality to
 * {@link #checkOperandTypes(SqlCallBinding, boolean)}, but not part of the
 * interface, and cannot throw an error.
 */
public boolean checkOperandTypes(
    SqlOperatorBinding callBinding) {
  boolean b = true;
  for (int i = 0; i < nOperands; ++i) {
    RelDataType type = callBinding.getOperandType(i);
    if (type.getComparability().ordinal() < requiredComparability.ordinal()) {
      b = false;
    }
  }
  if (b) {
    b = super.checkOperandTypes(callBinding);
  }
  return b;
}
 
Example 14
Source File: MatchReturnTypeInference.java    From Bats with Apache License 2.0 5 votes vote down vote up
public RelDataType inferReturnType(
    SqlOperatorBinding opBinding) {
  for (int i = start; i < opBinding.getOperandCount(); i++) {
    RelDataType argType = opBinding.getOperandType(i);
    if (SqlTypeUtil.isOfSameTypeName(typeNames, argType)) {
      return argType;
    }
  }
  return null;
}
 
Example 15
Source File: SqlDatetimePlusOperator.java    From Bats with Apache License 2.0 5 votes vote down vote up
@Override public RelDataType inferReturnType(SqlOperatorBinding opBinding) {
  final RelDataTypeFactory typeFactory = opBinding.getTypeFactory();
  final RelDataType leftType = opBinding.getOperandType(0);
  final IntervalSqlType unitType =
      (IntervalSqlType) opBinding.getOperandType(1);
  final TimeUnit timeUnit = unitType.getIntervalQualifier().getStartUnit();
  return SqlTimestampAddFunction.deduceType(typeFactory, timeUnit,
      unitType, leftType);
}
 
Example 16
Source File: TypeInferenceUtils.java    From Bats with Apache License 2.0 4 votes vote down vote up
@Override
public RelDataType inferReturnType(SqlOperatorBinding opBinding) {
  final RelDataTypeFactory factory = opBinding.getTypeFactory();
  // If there is group-by and the imput type is Non-nullable,
  // the output is Non-nullable;
  // Otherwise, the output is nullable.
  final boolean isNullable = opBinding.getGroupCount() == 0
      || opBinding.getOperandType(0).isNullable();

  if (getDrillTypeFromCalciteType(opBinding.getOperandType(0)) == TypeProtos.MinorType.LATE) {
    return createCalciteTypeWithNullability(
        factory,
        SqlTypeName.ANY,
        isNullable);
  }

  // Determines SqlTypeName of the result.
  // For the case when input may be implicitly casted to FLOAT4, the type of result is DOUBLE.
  // Else for the case when input may be implicitly casted to VARDECIMAL, the type of result is DECIMAL
  // with scale max(6, input) and max allowed numeric precision.
  // Else for the case when input may be implicitly casted to FLOAT8, the type of result is DOUBLE.
  // When none of these conditions is satisfied, error is thrown.
  // This order of checks is caused by the order of types in ResolverTypePrecedence.precedenceMap
  final RelDataType operandType = opBinding.getOperandType(0);
  final TypeProtos.MinorType inputMinorType = getDrillTypeFromCalciteType(operandType);
  if (TypeCastRules.getLeastRestrictiveType(Lists.newArrayList(inputMinorType, TypeProtos.MinorType.FLOAT4))
      == TypeProtos.MinorType.FLOAT4) {
    return createCalciteTypeWithNullability(
        factory,
        SqlTypeName.DOUBLE,
        isNullable);
  } else if (TypeCastRules.getLeastRestrictiveType(Lists.newArrayList(inputMinorType, TypeProtos.MinorType.VARDECIMAL))
      == TypeProtos.MinorType.VARDECIMAL) {
    RelDataType sqlType = factory.createSqlType(SqlTypeName.DECIMAL,
        DrillRelDataTypeSystem.DRILL_REL_DATATYPE_SYSTEM.getMaxNumericPrecision(),
        Math.min(Math.max(6, operandType.getScale()),
            DrillRelDataTypeSystem.DRILL_REL_DATATYPE_SYSTEM.getMaxNumericScale()));
    return factory.createTypeWithNullability(sqlType, isNullable);
  } else if (TypeCastRules.getLeastRestrictiveType(Lists.newArrayList(inputMinorType, TypeProtos.MinorType.FLOAT8))
      == TypeProtos.MinorType.FLOAT8) {
    return createCalciteTypeWithNullability(
        factory,
        SqlTypeName.DOUBLE,
        isNullable);
  } else {
    throw UserException
        .functionError()
        .message(String.format("%s does not support operand types (%s)",
            opBinding.getOperator().getName(),
            opBinding.getOperandType(0).getSqlTypeName()))
        .build(logger);
  }
}
 
Example 17
Source File: TypeInferenceUtils.java    From Bats with Apache License 2.0 4 votes vote down vote up
@Override
public RelDataType inferReturnType(SqlOperatorBinding opBinding) {
  RelDataTypeFactory factory = opBinding.getTypeFactory();
  // operands count ond order is checked at parsing stage
  RelDataType inputType = opBinding.getOperandType(2);
  boolean isNullable = inputType.isNullable() || opBinding.getOperandType(1).isNullable();

  SqlTypeName inputTypeName = inputType.getSqlTypeName();

  TimeUnit qualifier = ((SqlLiteral) ((SqlCallBinding) opBinding).operand(0)).getValueAs(TimeUnit.class);

  SqlTypeName sqlTypeName;

  // follow up with type inference of reduced expression
  switch (qualifier) {
    case DAY:
    case WEEK:
    case MONTH:
    case QUARTER:
    case YEAR:
    case NANOSECOND:  // NANOSECOND is not supported by Calcite SqlTimestampAddFunction.
                      // Once it is fixed, NANOSECOND should be moved to the group below.
      sqlTypeName = inputTypeName;
      break;
    case MICROSECOND:
    case MILLISECOND:
      // precision should be specified for MICROSECOND and MILLISECOND
      return factory.createTypeWithNullability(
          factory.createSqlType(SqlTypeName.TIMESTAMP, 3),
          isNullable);
    case SECOND:
    case MINUTE:
    case HOUR:
      if (inputTypeName == SqlTypeName.TIME) {
        sqlTypeName = SqlTypeName.TIME;
      } else {
        sqlTypeName = SqlTypeName.TIMESTAMP;
      }
      break;
    default:
      sqlTypeName = SqlTypeName.ANY;
  }

  // preserves precision of input type if it was specified
  if (inputType.getSqlTypeName().allowsPrecNoScale()) {
    RelDataType type = factory.createSqlType(sqlTypeName, inputType.getPrecision());
    return factory.createTypeWithNullability(type, isNullable);
  }
  return createCalciteTypeWithNullability(
      opBinding.getTypeFactory(),
      sqlTypeName,
      isNullable);
}
 
Example 18
Source File: HiveSqlUDFReturnTypeInference.java    From marble with Apache License 2.0 4 votes vote down vote up
@Override public RelDataType inferReturnType(
    final SqlOperatorBinding opBinding) {
  try {
    SqlOperator sqlOperator = opBinding.getOperator();
    List<RelDataTypeHolder> argsType = new ArrayList<>();
    for (int i = 0; i < opBinding.getOperandCount(); i++) {
      RelDataTypeHolder relDataTypeHolder;
      boolean isSqlCallBinding = opBinding instanceof SqlCallBinding;
      if (isSqlCallBinding) {
        List<SqlNode> operands = ((SqlCallBinding) opBinding).operands();
        if (operands.get(i) instanceof SqlLiteral) {
          relDataTypeHolder = new RelDataTypeHolder(
              opBinding.getOperandType(i), true,
              ((SqlLiteral) operands.get(i)).getValue());
        } else {
          relDataTypeHolder = new RelDataTypeHolder(
              opBinding.getOperandType(i));
        }

      } else {
        relDataTypeHolder = new RelDataTypeHolder(
            opBinding.getOperandType(i));
      }
      argsType.add(relDataTypeHolder);
    }
    String opName = sqlOperator.getName();
    GenericUDF udfInstance = HiveUDFImplementor.newGenericUDF(
        opName, sqlOperator.getSyntax());
    ObjectInspector[] inputObjectInspector =
        TypeInferenceUtil.getObjectInspector(
            argsType.toArray(new RelDataTypeHolder[0]));
    ObjectInspector outputObjectInspector = udfInstance.initialize(
        inputObjectInspector);
    RelDataType resultType = TypeInferenceUtil.getRelDataType(
        outputObjectInspector,
        opBinding.getTypeFactory());
    return resultType;

  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}
 
Example 19
Source File: TypeInferenceUtils.java    From Bats with Apache License 2.0 4 votes vote down vote up
@Override
public RelDataType inferReturnType(SqlOperatorBinding opBinding) {
  final RelDataTypeFactory factory = opBinding.getTypeFactory();
  // If there is group-by and the imput type is Non-nullable,
  // the output is Non-nullable;
  // Otherwise, the output is nullable.
  final boolean isNullable = opBinding.getGroupCount() == 0
      || opBinding.getOperandType(0).isNullable();

  if(getDrillTypeFromCalciteType(opBinding.getOperandType(0)) == TypeProtos.MinorType.LATE) {
    return createCalciteTypeWithNullability(
        factory,
        SqlTypeName.ANY,
        isNullable);
  }

  // Determines SqlTypeName of the result.
  // For the case when input may be implicitly casted to BIGINT, the type of result is BIGINT.
  // Else for the case when input may be implicitly casted to FLOAT4, the type of result is DOUBLE.
  // Else for the case when input may be implicitly casted to VARDECIMAL, the type of result is DECIMAL
  // with the same scale as input and max allowed numeric precision.
  // Else for the case when input may be implicitly casted to FLOAT8, the type of result is DOUBLE.
  // When none of these conditions is satisfied, error is thrown.
  // This order of checks is caused by the order of types in ResolverTypePrecedence.precedenceMap
  final RelDataType operandType = opBinding.getOperandType(0);
  final TypeProtos.MinorType inputMinorType = getDrillTypeFromCalciteType(operandType);
  if (TypeCastRules.getLeastRestrictiveType(Lists.newArrayList(inputMinorType, TypeProtos.MinorType.BIGINT))
      == TypeProtos.MinorType.BIGINT) {
    return createCalciteTypeWithNullability(
        factory,
        SqlTypeName.BIGINT,
        isNullable);
  } else if (TypeCastRules.getLeastRestrictiveType(Lists.newArrayList(inputMinorType, TypeProtos.MinorType.FLOAT4))
      == TypeProtos.MinorType.FLOAT4) {
    return createCalciteTypeWithNullability(
        factory,
        SqlTypeName.DOUBLE,
        isNullable);
  } else if (TypeCastRules.getLeastRestrictiveType(Lists.newArrayList(inputMinorType, TypeProtos.MinorType.VARDECIMAL))
      == TypeProtos.MinorType.VARDECIMAL) {
    RelDataType sqlType = factory.createSqlType(SqlTypeName.DECIMAL,
      DrillRelDataTypeSystem.DRILL_REL_DATATYPE_SYSTEM.getMaxNumericPrecision(),
      Math.min(operandType.getScale(),
        DrillRelDataTypeSystem.DRILL_REL_DATATYPE_SYSTEM.getMaxNumericScale()));
    return factory.createTypeWithNullability(sqlType, isNullable);
  } else if (TypeCastRules.getLeastRestrictiveType(Lists.newArrayList(inputMinorType, TypeProtos.MinorType.FLOAT8))
      == TypeProtos.MinorType.FLOAT8) {
    return createCalciteTypeWithNullability(
        factory,
        SqlTypeName.DOUBLE,
        isNullable);
  } else {
    throw UserException
        .functionError()
        .message(String.format("%s does not support operand types (%s)",
            opBinding.getOperator().getName(),
            opBinding.getOperandType(0).getSqlTypeName()))
        .build(logger);
  }
}
 
Example 20
Source File: OrdinalReturnTypeInference.java    From calcite with Apache License 2.0 4 votes vote down vote up
public RelDataType inferReturnType(
    SqlOperatorBinding opBinding) {
  return opBinding.getOperandType(ordinal);
}