Search in sources :

Example 26 with SqlFunction

use of org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.sql.SqlFunction in project calcite by apache.

the class RelJson method toJson.

private Object toJson(RexNode node) {
    final Map<String, Object> map;
    switch(node.getKind()) {
        case FIELD_ACCESS:
            map = jsonBuilder.map();
            final RexFieldAccess fieldAccess = (RexFieldAccess) node;
            map.put("field", fieldAccess.getField().getName());
            map.put("expr", toJson(fieldAccess.getReferenceExpr()));
            return map;
        case LITERAL:
            final RexLiteral literal = (RexLiteral) node;
            final Object value2 = literal.getValue2();
            if (value2 == null) {
                // Special treatment for null literal because (1) we wouldn't want
                // 'null' to be confused as an empty expression and (2) for null
                // literals we need an explicit type.
                map = jsonBuilder.map();
                map.put("literal", null);
                map.put("type", literal.getTypeName().name());
                return map;
            }
            return value2;
        case INPUT_REF:
        case LOCAL_REF:
            map = jsonBuilder.map();
            map.put("input", ((RexSlot) node).getIndex());
            map.put("name", ((RexSlot) node).getName());
            return map;
        case CORREL_VARIABLE:
            map = jsonBuilder.map();
            map.put("correl", ((RexCorrelVariable) node).getName());
            map.put("type", toJson(node.getType()));
            return map;
        default:
            if (node instanceof RexCall) {
                final RexCall call = (RexCall) node;
                map = jsonBuilder.map();
                map.put("op", toJson(call.getOperator()));
                final List<Object> list = jsonBuilder.list();
                for (RexNode operand : call.getOperands()) {
                    list.add(toJson(operand));
                }
                map.put("operands", list);
                switch(node.getKind()) {
                    case CAST:
                        map.put("type", toJson(node.getType()));
                }
                if (call.getOperator() instanceof SqlFunction) {
                    if (((SqlFunction) call.getOperator()).getFunctionType().isUserDefined()) {
                        map.put("class", call.getOperator().getClass().getName());
                    }
                }
                return map;
            }
            throw new UnsupportedOperationException("unknown rex " + node);
    }
}
Also used : RexCall(org.apache.calcite.rex.RexCall) RexLiteral(org.apache.calcite.rex.RexLiteral) RexFieldAccess(org.apache.calcite.rex.RexFieldAccess) RexNode(org.apache.calcite.rex.RexNode) SqlFunction(org.apache.calcite.sql.SqlFunction)

Example 27 with SqlFunction

use of org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.sql.SqlFunction in project calcite by apache.

the class SqlFloorFunction method unparseDatetimeFunction.

/**
 * 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);
}
Also used : SqlCall(org.apache.calcite.sql.SqlCall) SqlFunction(org.apache.calcite.sql.SqlFunction) SqlNode(org.apache.calcite.sql.SqlNode)

Example 28 with SqlFunction

use of org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.sql.SqlFunction in project drill by apache.

the class PreProcessLogicalRel method visit.

@Override
public RelNode visit(LogicalProject project) {
    final List<RexNode> projExpr = Lists.newArrayList();
    for (RexNode rexNode : project.getChildExps()) {
        projExpr.add(rexNode.accept(unwrappingExpressionVisitor));
    }
    project = project.copy(project.getTraitSet(), project.getInput(), projExpr, project.getRowType());
    List<RexNode> exprList = new ArrayList<>();
    boolean rewrite = false;
    for (RexNode rex : project.getChildExps()) {
        RexNode newExpr = rex;
        if (rex instanceof RexCall) {
            RexCall function = (RexCall) rex;
            String functionName = function.getOperator().getName();
            int nArgs = function.getOperands().size();
            // check if its a convert_from or convert_to function
            if (functionName.equalsIgnoreCase("convert_from") || functionName.equalsIgnoreCase("convert_to")) {
                String literal;
                if (nArgs == 2) {
                    if (function.getOperands().get(1) instanceof RexLiteral) {
                        try {
                            literal = ((NlsString) (((RexLiteral) function.getOperands().get(1)).getValue())).getValue();
                        } catch (final ClassCastException e) {
                            // Caused by user entering a value with a non-string literal
                            throw getConvertFunctionInvalidTypeException(function);
                        }
                    } else {
                        // caused by user entering a non-literal
                        throw getConvertFunctionInvalidTypeException(function);
                    }
                } else {
                    // Second operand is missing
                    throw UserException.parseError().message("'%s' expects a string literal as a second argument.", functionName).build(logger);
                }
                RexBuilder builder = new RexBuilder(factory);
                // construct the new function name based on the input argument
                String newFunctionName = functionName + literal;
                // Look up the new function name in the drill operator table
                List<SqlOperator> operatorList = table.getSqlOperator(newFunctionName);
                if (operatorList.size() == 0) {
                    // User typed in an invalid type name
                    throw getConvertFunctionException(functionName, literal);
                }
                SqlFunction newFunction = null;
                // Find the SqlFunction with the correct args
                for (SqlOperator op : operatorList) {
                    if (op.getOperandTypeChecker().getOperandCountRange().isValidCount(nArgs - 1)) {
                        newFunction = (SqlFunction) op;
                        break;
                    }
                }
                if (newFunction == null) {
                    // we are here because we found some dummy convert function. (See DummyConvertFrom and DummyConvertTo)
                    throw getConvertFunctionException(functionName, literal);
                }
                // create the new expression to be used in the rewritten project
                newExpr = builder.makeCall(newFunction, function.getOperands().subList(0, 1));
                rewrite = true;
            }
        }
        exprList.add(newExpr);
    }
    if (rewrite) {
        LogicalProject newProject = project.copy(project.getTraitSet(), project.getInput(0), exprList, project.getRowType());
        return visitChild(newProject, 0, project.getInput());
    }
    return visitChild(project, 0, project.getInput());
}
Also used : RexLiteral(org.apache.calcite.rex.RexLiteral) SqlOperator(org.apache.calcite.sql.SqlOperator) ArrayList(java.util.ArrayList) NlsString(org.apache.calcite.util.NlsString) RexCall(org.apache.calcite.rex.RexCall) RexBuilder(org.apache.calcite.rex.RexBuilder) LogicalProject(org.apache.calcite.rel.logical.LogicalProject) RexNode(org.apache.calcite.rex.RexNode) SqlFunction(org.apache.calcite.sql.SqlFunction)

Example 29 with SqlFunction

use of org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.sql.SqlFunction in project drill by apache.

the class DrillTableInfo method prepareTableMacroOperands.

/**
 * Returns list with operands for table function, obtained from specified call in the order
 * suitable to be used in table function and default values for absent arguments.
 * For example, for the following call:
 * <pre>
 *   `dfs`.`corrupted_dates`(`type` => 'parquet', `autoCorrectCorruptDates` => FALSE, `enableStringsSignedMinMax` => FALSE)
 * </pre>
 * will be returned the following list:
 * <pre>
 *   ['parquet', FALSE, FALSE, DEFAULT]
 * </pre>
 * whose elements correspond to the following parameters:
 * <pre>
 *   [type, autoCorrectCorruptDates, enableStringsSignedMinMax, schema]
 * </pre>
 *
 * @param call sql call whose arguments should be prepared
 * @return list with operands for table function
 */
private static List<SqlNode> prepareTableMacroOperands(SqlCall call) {
    Function<String, SqlNode> convertOperand = paramName -> call.getOperandList().stream().map(sqlNode -> (SqlCall) sqlNode).filter(sqlCall -> ((SqlIdentifier) sqlCall.operand(1)).getSimple().equals(paramName)).peek(sqlCall -> Preconditions.checkState(sqlCall.getKind() == SqlKind.ARGUMENT_ASSIGNMENT)).findFirst().map(sqlCall -> (SqlNode) sqlCall.operand(0)).orElse(SqlStdOperatorTable.DEFAULT.createCall(SqlParserPos.ZERO));
    SqlFunction operator = (SqlFunction) call.getOperator();
    return operator.getParamNames().stream().map(convertOperand).collect(Collectors.toList());
}
Also used : SqlParserPos(org.apache.calcite.sql.parser.SqlParserPos) SchemaUtilites(org.apache.drill.exec.planner.sql.SchemaUtilites) SqlKind(org.apache.calcite.sql.SqlKind) SqlUserDefinedTableMacro(org.apache.calcite.sql.validate.SqlUserDefinedTableMacro) Logger(org.slf4j.Logger) TranslatableTable(org.apache.calcite.schema.TranslatableTable) UserException(org.apache.drill.common.exceptions.UserException) LoggerFactory(org.slf4j.LoggerFactory) Table(org.apache.calcite.schema.Table) DrillTable(org.apache.drill.exec.planner.logical.DrillTable) Function(java.util.function.Function) Collectors(java.util.stream.Collectors) SqlCall(org.apache.calcite.sql.SqlCall) List(java.util.List) SqlFunction(org.apache.calcite.sql.SqlFunction) SqlNode(org.apache.calcite.sql.SqlNode) SqlStdOperatorTable(org.apache.calcite.sql.fun.SqlStdOperatorTable) AbstractSchema(org.apache.drill.exec.store.AbstractSchema) SqlIdentifier(org.apache.calcite.sql.SqlIdentifier) Preconditions(org.apache.drill.shaded.guava.com.google.common.base.Preconditions) SqlOperator(org.apache.calcite.sql.SqlOperator) Util(org.apache.calcite.util.Util) DrillTranslatableTable(org.apache.drill.exec.planner.logical.DrillTranslatableTable) SqlCall(org.apache.calcite.sql.SqlCall) SqlIdentifier(org.apache.calcite.sql.SqlIdentifier) SqlNode(org.apache.calcite.sql.SqlNode) SqlFunction(org.apache.calcite.sql.SqlFunction)

Example 30 with SqlFunction

use of org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.sql.SqlFunction in project drill by apache.

the class DrillOperatorTable method populateWrappedCalciteOperators.

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;
            // 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.convertToDrillFunctionName(calciteOperator.getName());
            }
            final List<DrillFuncHolder> drillFuncHolders = getFunctionListWithInference(drillOpName);
            if (drillFuncHolders.isEmpty()) {
                continue;
            }
            wrapper = new DrillCalciteSqlOperatorWrapper(calciteOperator, drillOpName, drillFuncHolders);
        }
        calciteToWrapper.put(calciteOperator, wrapper);
    }
}
Also used : DrillFuncHolder(org.apache.drill.exec.expr.fn.DrillFuncHolder) SqlOperator(org.apache.calcite.sql.SqlOperator) SqlBetweenOperator(org.apache.calcite.sql.fun.SqlBetweenOperator) SqlAggFunction(org.apache.calcite.sql.SqlAggFunction) SqlFunction(org.apache.calcite.sql.SqlFunction)

Aggregations

SqlFunction (org.apache.calcite.sql.SqlFunction)30 SqlOperator (org.apache.calcite.sql.SqlOperator)13 ArrayList (java.util.ArrayList)7 RexNode (org.apache.calcite.rex.RexNode)6 RoundOperatorConversion (org.apache.druid.sql.calcite.expression.builtin.RoundOperatorConversion)6 Test (org.junit.Test)6 SqlCall (org.apache.calcite.sql.SqlCall)5 ImmutableList (com.google.common.collect.ImmutableList)4 SqlIdentifier (org.apache.calcite.sql.SqlIdentifier)4 BigDecimal (java.math.BigDecimal)3 RexCall (org.apache.calcite.rex.RexCall)3 RexLiteral (org.apache.calcite.rex.RexLiteral)3 SqlNode (org.apache.calcite.sql.SqlNode)3 List (java.util.List)2 TimeUnitRange (org.apache.calcite.avatica.util.TimeUnitRange)2 LogicalProject (org.apache.calcite.rel.logical.LogicalProject)2 RelDataType (org.apache.calcite.rel.type.RelDataType)2 RexBuilder (org.apache.calcite.rex.RexBuilder)2 SqlAggFunction (org.apache.calcite.sql.SqlAggFunction)2 SqlBasicCall (org.apache.calcite.sql.SqlBasicCall)2