Java Code Examples for org.apache.calcite.sql.SqlFunction

The following examples show how to use org.apache.calcite.sql.SqlFunction. 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: StandardConvertletTable.java    License: Apache License 2.0 6 votes vote down vote up
public RexNode convertFunction(
    SqlRexContext cx,
    SqlFunction fun,
    SqlCall call) {
  final List<SqlNode> operands = call.getOperandList();
  final List<RexNode> exprs = convertExpressionList(cx, operands,
      SqlOperandTypeChecker.Consistency.NONE);
  if (fun.getFunctionType() == SqlFunctionCategory.USER_DEFINED_CONSTRUCTOR) {
    return makeConstructorCall(cx, fun, exprs);
  }
  RelDataType returnType =
      cx.getValidator().getValidatedNodeTypeIfKnown(call);
  if (returnType == null) {
    returnType = cx.getRexBuilder().deriveReturnType(fun, exprs);
  }
  return cx.getRexBuilder().makeCall(returnType, fun, exprs);
}
 
Example 2
Source Project: calcite   Source File: SqlFloorFunction.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Most dialects that natively support datetime floor will use this.
 * In those cases the call will look like TRUNC(datetime, 'year').
 *
 * @param writer SqlWriter
 * @param call SqlCall
 * @param funName Name of the sql function to call
 * @param datetimeFirst Specify the order of the datetime &amp; timeUnit
 * arguments
 */
public static void unparseDatetimeFunction(SqlWriter writer, SqlCall call,
    String funName, Boolean datetimeFirst) {
  SqlFunction func = new SqlFunction(funName, SqlKind.OTHER_FUNCTION,
      ReturnTypes.ARG0_NULLABLE_VARYING, null, null,
      SqlFunctionCategory.STRING);

  SqlCall call1;
  if (datetimeFirst) {
    call1 = call;
  } else {
    // switch order of operands
    SqlNode op1 = call.operand(0);
    SqlNode op2 = call.operand(1);

    call1 = call.getOperator().createCall(call.getParserPosition(), op2, op1);
  }

  SqlUtil.unparseFunctionSyntax(func, writer, call1);
}
 
Example 3
Source Project: Bats   Source File: SqlFloorFunction.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Most dialects that natively support datetime floor will use this.
 * In those cases the call will look like TRUNC(datetime, 'year').
 *
 * @param writer SqlWriter
 * @param call SqlCall
 * @param funName Name of the sql function to call
 * @param datetimeFirst Specify the order of the datetime &amp; timeUnit
 * arguments
 */
public static void unparseDatetimeFunction(SqlWriter writer, SqlCall call,
    String funName, Boolean datetimeFirst) {
  SqlFunction func = new SqlFunction(funName, SqlKind.OTHER_FUNCTION,
      ReturnTypes.ARG0_NULLABLE_VARYING, null, null,
      SqlFunctionCategory.STRING);

  SqlCall call1;
  if (datetimeFirst) {
    call1 = call;
  } else {
    // switch order of operands
    SqlNode op1 = call.operand(0);
    SqlNode op2 = call.operand(1);

    call1 = call.getOperator().createCall(call.getParserPosition(), op2, op1);
  }

  SqlUtil.unparseFunctionSyntax(func, writer, call1);
}
 
Example 4
Source Project: calcite   Source File: DocumentationTest.java    License: Apache License 2.0 6 votes vote down vote up
private void addOperators(Map<String, PatternOp> map, String prefix,
    List<SqlOperator> operatorList) {
  for (SqlOperator op : operatorList) {
    final String name = op.getName().equals("TRANSLATE3") ? "TRANSLATE"
        : op.getName();
    if (op instanceof SqlSpecialOperator
        || !name.matches("^[a-zA-Z][a-zA-Z0-9_]*$")) {
      continue;
    }
    final String regex;
    if (op instanceof SqlOverlapsOperator) {
      regex = "[ ]*<td>period1 " + name + " period2</td>";
    } else if (op instanceof SqlFunction
        && (op.getOperandTypeChecker() == null
            || op.getOperandTypeChecker().getOperandCountRange().getMin()
                != 0)) {
      regex = prefix + "\\| .*" + name + "\\(.*";
    } else {
      regex = prefix + "\\| .*" + name + ".*";
    }
    map.put(regex, new PatternOp(Pattern.compile(regex), name));
  }
}
 
Example 5
Source Project: flink   Source File: FunctionCatalogOperatorTable.java    License: Apache License 2.0 6 votes vote down vote up
private Optional<SqlFunction> convertToSqlFunction(
		SqlFunctionCategory category,
		String name,
		FunctionDefinition functionDefinition) {
	if (functionDefinition instanceof AggregateFunctionDefinition) {
		return convertAggregateFunction(name, (AggregateFunctionDefinition) functionDefinition);
	} else if (functionDefinition instanceof ScalarFunctionDefinition) {
		return convertScalarFunction(name, (ScalarFunctionDefinition) functionDefinition);
	} else if (functionDefinition instanceof TableFunctionDefinition &&
			category != null &&
			category.isTableFunction()) {
		return convertTableFunction(name, (TableFunctionDefinition) functionDefinition);
	}

	return Optional.empty();
}
 
Example 6
Source Project: flink   Source File: LegacyScalarFunctionConvertRule.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Optional<RexNode> convert(CallExpression call, ConvertContext context) {
	FunctionDefinition def = call.getFunctionDefinition();
	if (def instanceof ScalarFunctionDefinition) {
		ScalarFunction scalaFunc = ((ScalarFunctionDefinition) def).getScalarFunction();
		FunctionIdentifier identifier = call.getFunctionIdentifier()
			.orElse(FunctionIdentifier.of(scalaFunc.functionIdentifier()));
		SqlFunction sqlFunction = UserDefinedFunctionUtils.createScalarSqlFunction(
			identifier,
			scalaFunc.toString(),
			scalaFunc,
			context.getTypeFactory());
		return Optional.of(context.getRelBuilder()
			.call(sqlFunction, toRexNodes(context, call.getChildren())));
	}
	return Optional.empty();
}
 
Example 7
Source Project: mat-calcite-plugin   Source File: ClassRowTypeCache.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public RexNode apply(RexBuilderContext context) {
	RelOptCluster cluster = context.getCluster();
	RelDataTypeFactory typeFactory = cluster.getTypeFactory();
	final SqlFunction UDF =
			new SqlUserDefinedFunction(
					new SqlIdentifier("RESOLVE_SIMPLE", SqlParserPos.ZERO),
					ReturnTypes.explicit(typeFactory.createJavaType(Object.class)),
					null,
					OperandTypes.ANY_ANY,
					ImmutableList.of(typeFactory.createTypeWithNullability(typeFactory.createJavaType(IObject.class), false),
							typeFactory.createJavaType(int.class)),
					ScalarFunctionImpl.create(IObjectMethods.class, "resolveSimpleValue"));
	RexBuilder b = context.getBuilder();
	RexNode rexNode = b.makeCall(UDF, context.getIObject(), b.makeLiteral(name));
	return b.makeCast(dataType, rexNode);
}
 
Example 8
Source Project: mat-calcite-plugin   Source File: ClassRowTypeCache.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public RexNode apply(RexBuilderContext context) {
	RelOptCluster cluster = context.getCluster();
	RelDataTypeFactory typeFactory = cluster.getTypeFactory();
	final SqlFunction UDF =
			new SqlUserDefinedFunction(
					new SqlIdentifier("RESOLVE_REFERENCE", SqlParserPos.ZERO),
					ReturnTypes.explicit(typeFactory.createJavaType(HeapReference.class)),
					null,
					OperandTypes.ANY_ANY,
					ImmutableList.of(typeFactory.createTypeWithNullability(typeFactory.createJavaType(IObject.class), false),
							typeFactory.createJavaType(String.class)),
					ScalarFunctionImpl.create(IObjectMethods.class, "resolveReferenceValue"));
	RexBuilder b = context.getBuilder();
	return b.makeCall(UDF, context.getIObject(), b.makeLiteral(name));
}
 
Example 9
@Override
public RexNode getSnapshot() {
    if (snapshot == null) {
        RelDataTypeFactory typeFactory = getCluster().getTypeFactory();
        RexBuilder b = getBuilder();
        final SqlFunction UDF =
                new SqlUserDefinedFunction(
                        new SqlIdentifier("GET_SNAPSHOT", SqlParserPos.ZERO),
                        ReturnTypes.explicit(typeFactory.createTypeWithNullability(typeFactory.createJavaType(ISnapshot.class), false)),
                        null,
                        OperandTypes.NUMERIC,
                        ImmutableList.of(typeFactory.createJavaType(Integer.class)),
                        ScalarFunctionImpl.create(SnapshotHolder.class, "get"));
        snapshot = b.makeCall(UDF, b.makeLiteral(snapshotId, typeFactory.createSqlType(SqlTypeName.INTEGER), false));
    }
    return snapshot;
}
 
Example 10
Source Project: mat-calcite-plugin   Source File: RexBuilderContext.java    License: Apache License 2.0 6 votes vote down vote up
public RexNode getIObject() {
    if (object == null) {
        RelDataTypeFactory typeFactory = getCluster().getTypeFactory();
        RexBuilder b = getBuilder();
        final SqlFunction GET_IOBJECT =
                new SqlUserDefinedFunction(
                        new SqlIdentifier("GET_IOBJECT", SqlParserPos.ZERO),
                        ReturnTypes.explicit(typeFactory.createTypeWithNullability(typeFactory.createJavaType(IObject.class), false)),
                        null,
                        OperandTypes.ANY_ANY,
                        ImmutableList.of(typeFactory.createTypeWithNullability(typeFactory.createJavaType(ISnapshot.class), false),
                                typeFactory.createJavaType(int.class)),
                        ScalarFunctionImpl.create(ISnapshotMethods.class, "getIObject"));
        object = b.makeCall(GET_IOBJECT, getSnapshot(), getIObjectId());
    }
    return object;
}
 
Example 11
Source Project: calcite   Source File: StandardConvertletTable.java    License: Apache License 2.0 6 votes vote down vote up
public RexNode convertFunction(
    SqlRexContext cx,
    SqlFunction fun,
    SqlCall call) {
  final List<SqlNode> operands = call.getOperandList();
  final List<RexNode> exprs = convertExpressionList(cx, operands,
      SqlOperandTypeChecker.Consistency.NONE);
  if (fun.getFunctionType() == SqlFunctionCategory.USER_DEFINED_CONSTRUCTOR) {
    return makeConstructorCall(cx, fun, exprs);
  }
  RelDataType returnType =
      cx.getValidator().getValidatedNodeTypeIfKnown(call);
  if (returnType == null) {
    returnType = cx.getRexBuilder().deriveReturnType(fun, exprs);
  }
  return cx.getRexBuilder().makeCall(returnType, fun, exprs);
}
 
Example 12
Source Project: calcite   Source File: TypeCoercionImpl.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Type coercion for user defined functions(UDFs).
 */
public boolean userDefinedFunctionCoercion(SqlValidatorScope scope,
    SqlCall call, SqlFunction function) {
  final List<RelDataType> paramTypes = function.getParamTypes();
  assert paramTypes != null;
  boolean coerced = false;
  for (int i = 0; i < call.operandCount(); i++) {
    SqlNode operand = call.operand(i);
    if (operand.getKind() == SqlKind.ARGUMENT_ASSIGNMENT) {
      final List<SqlNode> operandList = ((SqlCall) operand).getOperandList();
      String name = ((SqlIdentifier) operandList.get(1)).getSimple();
      int formalIndex = function.getParamNames().indexOf(name);
      if (formalIndex < 0) {
        return false;
      }
      // Column list operand type is not supported now.
      coerced = coerceOperandType(scope, (SqlCall) operand, 0,
          paramTypes.get(formalIndex)) || coerced;
    } else {
      coerced = coerceOperandType(scope, call, i, paramTypes.get(i)) || coerced;
    }
  }
  return coerced;
}
 
Example 13
Source Project: Bats   Source File: StandardConvertletTable.java    License: Apache License 2.0 5 votes vote down vote up
protected RexNode convertFloorCeil(SqlRexContext cx, SqlCall call) {
  final boolean floor = call.getKind() == SqlKind.FLOOR;
  // Rewrite floor, ceil of interval
  if (call.operandCount() == 1
      && call.operand(0) instanceof SqlIntervalLiteral) {
    final SqlIntervalLiteral literal = call.operand(0);
    SqlIntervalLiteral.IntervalValue interval =
        (SqlIntervalLiteral.IntervalValue) literal.getValue();
    BigDecimal val =
        interval.getIntervalQualifier().getStartUnit().multiplier;
    RexNode rexInterval = cx.convertExpression(literal);

    final RexBuilder rexBuilder = cx.getRexBuilder();
    RexNode zero = rexBuilder.makeExactLiteral(BigDecimal.valueOf(0));
    RexNode cond = ge(rexBuilder, rexInterval, zero);

    RexNode pad =
        rexBuilder.makeExactLiteral(val.subtract(BigDecimal.ONE));
    RexNode cast = rexBuilder.makeReinterpretCast(
        rexInterval.getType(), pad, rexBuilder.makeLiteral(false));
    RexNode sum = floor
        ? minus(rexBuilder, rexInterval, cast)
        : plus(rexBuilder, rexInterval, cast);

    RexNode kase = floor
        ? case_(rexBuilder, rexInterval, cond, sum)
        : case_(rexBuilder, sum, cond, rexInterval);

    RexNode factor = rexBuilder.makeExactLiteral(val);
    RexNode div = divideInt(rexBuilder, kase, factor);
    return multiply(rexBuilder, div, factor);
  }

  // normal floor, ceil function
  return convertFunction(cx, (SqlFunction) call.getOperator(), call);
}
 
Example 14
Source Project: Bats   Source File: StandardConvertletTable.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Converts a call to the {@code EXTRACT} function.
 *
 * <p>Called automatically via reflection.
 */
public RexNode convertExtract(
    SqlRexContext cx,
    SqlExtractFunction op,
    SqlCall call) {
  return convertFunction(cx, (SqlFunction) call.getOperator(), call);
}
 
Example 15
Source Project: Bats   Source File: ListSqlOperatorTable.java    License: Apache License 2.0 5 votes vote down vote up
protected static SqlFunctionCategory category(SqlOperator operator) {
  if (operator instanceof SqlFunction) {
    return ((SqlFunction) operator).getFunctionType();
  } else {
    return SqlFunctionCategory.SYSTEM;
  }
}
 
Example 16
Source Project: Bats   Source File: DrillCalciteSqlFunctionWrapper.java    License: Apache License 2.0 5 votes vote down vote up
public DrillCalciteSqlFunctionWrapper(
    final SqlFunction wrappedFunction,
  final List<DrillFuncHolder> functions) {
  super(wrappedFunction.getName(),
      wrappedFunction.getSqlIdentifier(),
      wrappedFunction.getKind(),
      TypeInferenceUtils.getDrillSqlReturnTypeInference(
          wrappedFunction.getName(),
          functions),
      wrappedFunction.getOperandTypeInference(),
      Checker.ANY_CHECKER,
      wrappedFunction.getParamTypes(),
      wrappedFunction.getFunctionType());
  this.operator = wrappedFunction;
}
 
Example 17
Source Project: Bats   Source File: DrillCalciteWrapperUtility.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * This static method will extract the SqlFunction inside the given SqlFunction if the given SqlFunction is wrapped
 * in DrillCalciteSqlFunctionWrapper and will just return the given SqlFunction if it is not wrapped.
 */
public static SqlFunction extractSqlOperatorFromWrapper(final SqlFunction sqlFunction) {
  if(sqlFunction instanceof DrillCalciteSqlWrapper) {
    return (SqlFunction) ((DrillCalciteSqlWrapper) sqlFunction).getOperator();
  } else {
    return sqlFunction;
  }
}
 
Example 18
Source Project: Bats   Source File: DrillOperatorTable.java    License: Apache License 2.0 5 votes vote down vote up
private void populateWrappedCalciteOperators() {
  for (SqlOperator calciteOperator : inner.getOperatorList()) {
    final SqlOperator wrapper;
    if (calciteOperator instanceof SqlAggFunction) {
      wrapper = new DrillCalciteSqlAggFunctionWrapper((SqlAggFunction) calciteOperator,
          getFunctionListWithInference(calciteOperator.getName()));
    } else if (calciteOperator instanceof SqlFunction) {
      wrapper = new DrillCalciteSqlFunctionWrapper((SqlFunction) calciteOperator,
          getFunctionListWithInference(calciteOperator.getName()));
    } else if (calciteOperator instanceof SqlBetweenOperator) {
      // During the procedure of converting to RexNode,
      // StandardConvertletTable.convertBetween expects the SqlOperator to be a subclass of SqlBetweenOperator
      final SqlBetweenOperator sqlBetweenOperator = (SqlBetweenOperator) calciteOperator;
      wrapper = new DrillCalciteSqlBetweenOperatorWrapper(sqlBetweenOperator);
    } else {
      final String drillOpName;
      // For UNARY_MINUS (-) or UNARY_PLUS (+), we do not rename them as function_add or function_subtract.
      // Otherwise, Calcite will mix them up with binary operator subtract (-) or add (+)
      if (calciteOperator == SqlStdOperatorTable.UNARY_MINUS || calciteOperator == SqlStdOperatorTable.UNARY_PLUS) {
        drillOpName = calciteOperator.getName();
      } else {
        drillOpName = FunctionCallFactory.replaceOpWithFuncName(calciteOperator.getName());
      }

      final List<DrillFuncHolder> drillFuncHolders = getFunctionListWithInference(drillOpName);
      if (drillFuncHolders.isEmpty()) {
        continue;
      }

      wrapper = new DrillCalciteSqlOperatorWrapper(calciteOperator, drillOpName, drillFuncHolders);
    }
    calciteToWrapper.put(calciteOperator, wrapper);
  }
}
 
Example 19
Source Project: Flink-CEPplus   Source File: SqlValidatorImpl.java    License: Apache License 2.0 5 votes vote down vote up
public CalciteException handleUnresolvedFunction(SqlCall call,
	SqlFunction unresolvedFunction, List<RelDataType> argTypes,
	List<String> argNames) {
	// For builtins, we can give a better error message
	final List<SqlOperator> overloads = new ArrayList<>();
	opTab.lookupOperatorOverloads(unresolvedFunction.getNameAsId(), null,
		SqlSyntax.FUNCTION, overloads);
	if (overloads.size() == 1) {
		SqlFunction fun = (SqlFunction) overloads.get(0);
		if ((fun.getSqlIdentifier() == null)
			&& (fun.getSyntax() != SqlSyntax.FUNCTION_ID)) {
			final int expectedArgCount =
				fun.getOperandCountRange().getMin();
			throw newValidationError(call,
				RESOURCE.invalidArgCount(call.getOperator().getName(),
					expectedArgCount));
		}
	}

	AssignableOperandTypeChecker typeChecking =
		new AssignableOperandTypeChecker(argTypes, argNames);
	String signature =
		typeChecking.getAllowedSignatures(
			unresolvedFunction,
			unresolvedFunction.getName());
	throw newValidationError(call,
		RESOURCE.validatorUnknownFunction(signature));
}
 
Example 20
Source Project: Flink-CEPplus   Source File: SqlValidatorImpl.java    License: Apache License 2.0 5 votes vote down vote up
public void validateCall(
	SqlCall call,
	SqlValidatorScope scope) {
	final SqlOperator operator = call.getOperator();
	if ((call.operandCount() == 0)
		&& (operator.getSyntax() == SqlSyntax.FUNCTION_ID)
		&& !call.isExpanded()
		&& !conformance.allowNiladicParentheses()) {
		// For example, "LOCALTIME()" is illegal. (It should be
		// "LOCALTIME", which would have been handled as a
		// SqlIdentifier.)
		throw handleUnresolvedFunction(call, (SqlFunction) operator,
			ImmutableList.of(), null);
	}

	SqlValidatorScope operandScope = scope.getOperandScope(call);

	if (operator instanceof SqlFunction
		&& ((SqlFunction) operator).getFunctionType()
		== SqlFunctionCategory.MATCH_RECOGNIZE
		&& !(operandScope instanceof MatchRecognizeScope)) {
		throw newValidationError(call,
			Static.RESOURCE.functionMatchRecognizeOnly(call.toString()));
	}
	// Delegate validation to the operator.
	operator.validateCall(call, this, scope, operandScope);
}
 
Example 21
Source Project: flink   Source File: SqlValidatorImpl.java    License: Apache License 2.0 5 votes vote down vote up
public CalciteException handleUnresolvedFunction(SqlCall call,
	SqlFunction unresolvedFunction, List<RelDataType> argTypes,
	List<String> argNames) {
	// For builtins, we can give a better error message
	final List<SqlOperator> overloads = new ArrayList<>();
	opTab.lookupOperatorOverloads(unresolvedFunction.getNameAsId(), null,
			SqlSyntax.FUNCTION, overloads, catalogReader.nameMatcher());
	if (overloads.size() == 1) {
		SqlFunction fun = (SqlFunction) overloads.get(0);
		if ((fun.getSqlIdentifier() == null)
			&& (fun.getSyntax() != SqlSyntax.FUNCTION_ID)) {
			final int expectedArgCount =
				fun.getOperandCountRange().getMin();
			throw newValidationError(call,
				RESOURCE.invalidArgCount(call.getOperator().getName(),
					expectedArgCount));
		}
	}

	AssignableOperandTypeChecker typeChecking =
		new AssignableOperandTypeChecker(argTypes, argNames);
	String signature =
		typeChecking.getAllowedSignatures(
			unresolvedFunction,
			unresolvedFunction.getName());
	throw newValidationError(call,
		RESOURCE.validatorUnknownFunction(signature));
}
 
Example 22
Source Project: flink   Source File: SqlValidatorImpl.java    License: Apache License 2.0 5 votes vote down vote up
public void validateCall(
	SqlCall call,
	SqlValidatorScope scope) {
	final SqlOperator operator = call.getOperator();
	if ((call.operandCount() == 0)
		&& (operator.getSyntax() == SqlSyntax.FUNCTION_ID)
		&& !call.isExpanded()
		&& !conformance.allowNiladicParentheses()) {
		// For example, "LOCALTIME()" is illegal. (It should be
		// "LOCALTIME", which would have been handled as a
		// SqlIdentifier.)
		throw handleUnresolvedFunction(call, (SqlFunction) operator,
			ImmutableList.of(), null);
	}

	SqlValidatorScope operandScope = scope.getOperandScope(call);

	if (operator instanceof SqlFunction
		&& ((SqlFunction) operator).getFunctionType()
		== SqlFunctionCategory.MATCH_RECOGNIZE
		&& !(operandScope instanceof MatchRecognizeScope)) {
		throw newValidationError(call,
			Static.RESOURCE.functionMatchRecognizeOnly(call.toString()));
	}
	// Delegate validation to the operator.
	operator.validateCall(call, this, scope, operandScope);
}
 
Example 23
Source Project: flink   Source File: FunctionCatalogOperatorTable.java    License: Apache License 2.0 5 votes vote down vote up
private Optional<SqlFunction> convertAggregateFunction(
		String name,
		AggregateFunctionDefinition functionDefinition) {
	SqlFunction aggregateFunction = UserDefinedFunctionUtils.createAggregateSqlFunction(
		name,
		name,
		functionDefinition.getAggregateFunction(),
		functionDefinition.getResultTypeInfo(),
		functionDefinition.getAccumulatorTypeInfo(),
		typeFactory
	);
	return Optional.of(aggregateFunction);
}
 
Example 24
Source Project: flink   Source File: FunctionCatalogOperatorTable.java    License: Apache License 2.0 5 votes vote down vote up
private Optional<SqlFunction> convertScalarFunction(String name, ScalarFunctionDefinition functionDefinition) {
	SqlFunction scalarFunction = UserDefinedFunctionUtils.createScalarSqlFunction(
		name,
		name,
		functionDefinition.getScalarFunction(),
		typeFactory
	);
	return Optional.of(scalarFunction);
}
 
Example 25
Source Project: flink   Source File: FunctionCatalogOperatorTable.java    License: Apache License 2.0 5 votes vote down vote up
private Optional<SqlFunction> convertTableFunction(String name, TableFunctionDefinition functionDefinition) {
	SqlFunction tableFunction = UserDefinedFunctionUtils.createTableSqlFunction(
		name,
		name,
		functionDefinition.getTableFunction(),
		functionDefinition.getResultType(),
		typeFactory
	);
	return Optional.of(tableFunction);
}
 
Example 26
Source Project: flink   Source File: FunctionCatalogOperatorTable.java    License: Apache License 2.0 5 votes vote down vote up
private Optional<SqlFunction> convertAggregateFunction(
		String name,
		AggregateFunctionDefinition functionDefinition) {
	SqlFunction aggregateFunction = UserDefinedFunctionUtils.createAggregateSqlFunction(
		name,
		name,
		functionDefinition.getAggregateFunction(),
		TypeConversions.fromLegacyInfoToDataType(functionDefinition.getResultTypeInfo()),
		TypeConversions.fromLegacyInfoToDataType(functionDefinition.getAccumulatorTypeInfo()),
		typeFactory
	);
	return Optional.of(aggregateFunction);
}
 
Example 27
Source Project: flink   Source File: FunctionCatalogOperatorTable.java    License: Apache License 2.0 5 votes vote down vote up
private Optional<SqlFunction> convertScalarFunction(String name, ScalarFunctionDefinition functionDefinition) {
	SqlFunction scalarFunction = UserDefinedFunctionUtils.createScalarSqlFunction(
		name,
		name,
		functionDefinition.getScalarFunction(),
		typeFactory
	);
	return Optional.of(scalarFunction);
}
 
Example 28
Source Project: flink   Source File: FunctionCatalogOperatorTable.java    License: Apache License 2.0 5 votes vote down vote up
private Optional<SqlFunction> convertTableFunction(String name, TableFunctionDefinition functionDefinition) {
	SqlFunction tableFunction = UserDefinedFunctionUtils.createTableSqlFunction(
		name,
		name,
		functionDefinition.getTableFunction(),
		TypeConversions.fromLegacyInfoToDataType(functionDefinition.getResultType()),
		typeFactory
	);
	return Optional.of(tableFunction);
}
 
Example 29
Source Project: flink   Source File: RexNodeConverter.java    License: Apache License 2.0 5 votes vote down vote up
private RexNode visit(UnresolvedCallExpression call) {
	FunctionDefinition func = call.getFunctionDefinition();
	switch (func.getKind()) {
		case SCALAR:
			if (func instanceof ScalarFunctionDefinition) {
				ScalarFunction scalaFunc = ((ScalarFunctionDefinition) func).getScalarFunction();
				List<RexNode> child = convertCallChildren(call.getChildren());
				SqlFunction sqlFunction = UserDefinedFunctionUtils.createScalarSqlFunction(
						scalaFunc.functionIdentifier(),
						scalaFunc.toString(),
						scalaFunc,
						typeFactory);
				return relBuilder.call(sqlFunction, child);
			} else {
				FunctionDefinition def = call.getFunctionDefinition();
				if (conversionsOfBuiltInFunc.containsKey(def)) {
					RexNodeConversion conversion = conversionsOfBuiltInFunc.get(def);
					return conversion.convert(call);
				} else {
					throw new UnsupportedOperationException(def.toString());
				}
			}

		default:
			throw new UnsupportedOperationException();
	}
}
 
Example 30
Source Project: alchemy   Source File: SqlParseUtil.java    License: Apache License 2.0 5 votes vote down vote up
private static void parseFunction(SqlNode sqlNode, List<String> udfs) {
    if (sqlNode instanceof SqlBasicCall) {
        SqlBasicCall sqlBasicCall = (SqlBasicCall)sqlNode;
        SqlOperator operator = sqlBasicCall.getOperator();
        if (operator instanceof SqlFunction) {
            SqlFunction sqlFunction = (SqlFunction)operator;
            SqlFunctionCategory category = sqlFunction.getFunctionType();
            switch (category) {
                case USER_DEFINED_FUNCTION:
                case USER_DEFINED_SPECIFIC_FUNCTION:
                case USER_DEFINED_TABLE_FUNCTION:
                case USER_DEFINED_TABLE_SPECIFIC_FUNCTION:
                    addUdf(udfs, sqlFunction.getName());
                    break;
                default:
            }
        } else {
            parseFunction(sqlBasicCall.operand(0), udfs);
        }
        // 查询嵌套的函数
        SqlNode[] nodes = sqlBasicCall.getOperands();
        if(nodes != null && nodes.length > 0){
            for(SqlNode node : nodes){
                parseFunction(node, udfs);
            }
        }
    }
}