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

The following examples show how to use org.apache.calcite.sql.SqlOperatorBinding#getOperandCount() . 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: TypeInferenceUtils.java    From Bats with Apache License 2.0 6 votes vote down vote up
private static DrillFuncHolder resolveDrillFuncHolder(final SqlOperatorBinding opBinding,
    final List<DrillFuncHolder> functions, FunctionCall functionCall) {
  final FunctionResolver functionResolver = FunctionResolverFactory.getResolver(functionCall);
  final DrillFuncHolder func = functionResolver.getBestMatch(functions, functionCall);

  // Throw an exception
  // if no DrillFuncHolder matched for the given list of operand types
  if (func == null) {
    StringBuilder operandTypes = new StringBuilder();
    for (int i = 0; i < opBinding.getOperandCount(); ++i) {
      operandTypes.append(opBinding.getOperandType(i).getSqlTypeName());
      if (i < opBinding.getOperandCount() - 1) {
        operandTypes.append(",");
      }
    }

    throw UserException
        .functionError()
        .message(String.format("%s does not support operand types (%s)",
            opBinding.getOperator().getName(),
            operandTypes.toString()))
        .build(logger);
  }
  return func;
}
 
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: OperatorBindingCallContext.java    From flink with Apache License 2.0 6 votes vote down vote up
public OperatorBindingCallContext(
		DataTypeFactory dataTypeFactory,
		FunctionDefinition definition,
		SqlOperatorBinding binding) {
	super(
		dataTypeFactory,
		definition,
		binding.getOperator().getNameAsId().toString());

	this.binding = binding;
	this.argumentDataTypes = new AbstractList<DataType>() {
		@Override
		public DataType get(int pos) {
			final LogicalType logicalType = FlinkTypeFactory.toLogicalType(binding.getOperandType(pos));
			return TypeConversions.fromLogicalToDataType(logicalType);
		}

		@Override
		public int size() {
			return binding.getOperandCount();
		}
	};
}
 
Example 5
Source File: TypeInferenceUtils.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
@Override
public RelDataType inferReturnType(SqlOperatorBinding opBinding) {
  final RelDataTypeFactory factory = opBinding.getTypeFactory();
  final SqlTypeName sqlTypeName = SqlTypeName.VARCHAR;

  for(int i = 0; i < opBinding.getOperandCount(); ++i) {
    if(opBinding.getOperandType(i).isNullable()) {
      return createCalciteTypeWithNullability(factory, sqlTypeName, true, null);
    }
  }

  return createCalciteTypeWithNullability(factory, sqlTypeName, false, null);
}
 
Example 6
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 7
Source File: SqlJsonValueFunction.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** Returns the optional explicit returning type specification. **/
private static Optional<RelDataType> explicitTypeSpec(SqlOperatorBinding opBinding) {
  if (opBinding.getOperandCount() > 2
      && opBinding.isOperandLiteral(2, false)
      && opBinding.getOperandLiteralValue(2, Object.class)
        instanceof SqlJsonValueReturning) {
    return Optional.of(opBinding.getOperandType(3));
  }
  return Optional.empty();
}
 
Example 8
Source File: SqlSubstringFunction.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Override public SqlMonotonicity getMonotonicity(SqlOperatorBinding call) {
  // SUBSTRING(x FROM 0 FOR constant) has same monotonicity as x
  if (call.getOperandCount() == 3) {
    final SqlMonotonicity mono0 = call.getOperandMonotonicity(0);
    if ((mono0 != SqlMonotonicity.NOT_MONOTONIC)
        && call.getOperandMonotonicity(1) == SqlMonotonicity.CONSTANT
        && call.getOperandLiteralValue(1, BigDecimal.class)
            .equals(BigDecimal.ZERO)
        && call.getOperandMonotonicity(2) == SqlMonotonicity.CONSTANT) {
      return mono0.unstrict();
    }
  }
  return super.getMonotonicity(call);
}
 
Example 9
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 10
Source File: PlugginRepositorySqlReturnTypeInference.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
@Override
public RelDataType inferReturnType(SqlOperatorBinding opBinding) {
  for (RelDataType type : opBinding.collectOperandTypes()) {
    final TypeProtos.MinorType minorType = TypeInferenceUtils.getMinorTypeFromCalciteType(type);
    if(minorType == TypeProtos.MinorType.LATE) {
      return opBinding.getTypeFactory()
        .createTypeWithNullability(
          opBinding.getTypeFactory().createSqlType(SqlTypeName.ANY),
          true);
    }
  }

  final FunctionCall functionCall = TypeInferenceUtils.convertSqlOperatorBindingToFunctionCall(opBinding);
  final AbstractFunctionHolder funcHolder = registry.getFunction(functionCall);
  if(funcHolder == null) {
    final StringBuilder operandTypes = new StringBuilder();
    for(int j = 0; j < opBinding.getOperandCount(); ++j) {
      operandTypes.append(opBinding.getOperandType(j).getSqlTypeName());
      if(j < opBinding.getOperandCount() - 1) {
        operandTypes.append(",");
      }
    }

    throw UserException
      .functionError()
      .message(String.format("%s does not support operand types (%s)",
        opBinding.getOperator().getName(),
        operandTypes))
      .build(logger);
  }

  return TypeInferenceUtils.createCalciteTypeWithNullability(
    opBinding.getTypeFactory(),
    TypeInferenceUtils.getCalciteTypeFromMinorType(funcHolder.getReturnType(null).toMinorType()),
    true,
    null);
}
 
Example 11
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 12
Source File: TypeInferenceUtils.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
private static AbstractFunctionHolder resolveFunctionHolder(final SqlOperatorBinding opBinding,
                                                        final List<AbstractFunctionHolder>  functions,
                                                        boolean isDecimalV2On) {
  final FunctionCall functionCall = convertSqlOperatorBindingToFunctionCall(opBinding);
  final FunctionResolver functionResolver = FunctionResolverFactory.getResolver(functionCall);
  final AbstractFunctionHolder func = functionResolver.getBestMatch(functions, functionCall);

  // Throw an exception
  // if no BaseFunctionHolder matched for the given list of operand types
  if(func == null) {
    String operandTypes = "";
    for(int i = 0; i < opBinding.getOperandCount(); ++i) {
      operandTypes += opBinding.getOperandType(i).getSqlTypeName();
      if(i < opBinding.getOperandCount() - 1) {
        operandTypes += ",";
      }
    }

    throw UserException
        .functionError()
        .message(String.format("%s does not support operand types (%s)",
            opBinding.getOperator().getName(),
            operandTypes))
        .build(logger);
  }
  return func;
}
 
Example 13
Source File: SqlSubstringFunction.java    From Bats with Apache License 2.0 5 votes vote down vote up
@Override public SqlMonotonicity getMonotonicity(SqlOperatorBinding call) {
  // SUBSTRING(x FROM 0 FOR constant) has same monotonicity as x
  if (call.getOperandCount() == 3) {
    final SqlMonotonicity mono0 = call.getOperandMonotonicity(0);
    if ((mono0 != SqlMonotonicity.NOT_MONOTONIC)
        && call.getOperandMonotonicity(1) == SqlMonotonicity.CONSTANT
        && call.getOperandLiteralValue(1, BigDecimal.class)
            .equals(BigDecimal.ZERO)
        && call.getOperandMonotonicity(2) == SqlMonotonicity.CONSTANT) {
      return mono0.unstrict();
    }
  }
  return super.getMonotonicity(call);
}
 
Example 14
Source File: TypeInferenceUtils.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
@Override
public RelDataType inferReturnType(SqlOperatorBinding opBinding) {
  final RelDataTypeFactory factory = opBinding.getTypeFactory();
  final SqlTypeName sqlTypeName = SqlTypeName.VARCHAR;

  for(int i = 0; i < opBinding.getOperandCount(); ++i) {
    if(opBinding.getOperandType(i).isNullable()) {
      return createCalciteTypeWithNullability(factory, sqlTypeName, true, null);
    }
  }

  return createCalciteTypeWithNullability(factory, sqlTypeName, false, 65536);
}
 
Example 15
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 16
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 17
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 18
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 19
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 20
Source File: TypeInferenceUtils.java    From Bats with Apache License 2.0 4 votes vote down vote up
private static RelDataType getReturnType(final SqlOperatorBinding opBinding,
    final TypeProtos.MajorType returnType, FunctionTemplate.NullHandling nullHandling) {
  final RelDataTypeFactory factory = opBinding.getTypeFactory();

  // least restrictive type (nullable ANY type)
  final RelDataType nullableAnyType = factory.createTypeWithNullability(
      factory.createSqlType(SqlTypeName.ANY),
      true);

  if (UNKNOWN_TYPE.equals(returnType)) {
    return nullableAnyType;
  }

  final TypeProtos.MinorType minorType = returnType.getMinorType();
  final SqlTypeName sqlTypeName = getCalciteTypeFromDrillType(minorType);
  if (sqlTypeName == null) {
    return nullableAnyType;
  }

  final boolean isNullable;
  switch (returnType.getMode()) {
    case REPEATED:
    case OPTIONAL:
      isNullable = true;
      break;

    case REQUIRED:
      switch (nullHandling) {
        case INTERNAL:
          isNullable = false;
          break;

        case NULL_IF_NULL:
          boolean isNull = false;
          for (int i = 0; i < opBinding.getOperandCount(); ++i) {
            if (opBinding.getOperandType(i).isNullable()) {
              isNull = true;
              break;
            }
          }

          isNullable = isNull;
          break;
        default:
          throw new UnsupportedOperationException();
      }
      break;

    default:
      throw new UnsupportedOperationException();
  }

  return convertToCalciteType(factory, returnType, isNullable);
}