Search in sources :

Example 11 with RexLiteral

use of org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.rex.RexLiteral in project calcite by apache.

the class AggregateReduceFunctionsRule method reduceStddev.

private RexNode reduceStddev(Aggregate oldAggRel, AggregateCall oldCall, boolean biased, boolean sqrt, List<AggregateCall> newCalls, Map<AggregateCall, RexNode> aggCallMapping, List<RexNode> inputExprs) {
    // stddev_pop(x) ==>
    // power(
    // (sum(x * x) - sum(x) * sum(x) / count(x))
    // / count(x),
    // .5)
    // 
    // stddev_samp(x) ==>
    // power(
    // (sum(x * x) - sum(x) * sum(x) / count(x))
    // / nullif(count(x) - 1, 0),
    // .5)
    final int nGroups = oldAggRel.getGroupCount();
    final RelOptCluster cluster = oldAggRel.getCluster();
    final RexBuilder rexBuilder = cluster.getRexBuilder();
    final RelDataTypeFactory typeFactory = cluster.getTypeFactory();
    assert oldCall.getArgList().size() == 1 : oldCall.getArgList();
    final int argOrdinal = oldCall.getArgList().get(0);
    final RelDataType argOrdinalType = getFieldType(oldAggRel.getInput(), argOrdinal);
    final RelDataType oldCallType = typeFactory.createTypeWithNullability(oldCall.getType(), argOrdinalType.isNullable());
    final RexNode argRef = rexBuilder.ensureType(oldCallType, inputExprs.get(argOrdinal), true);
    final int argRefOrdinal = lookupOrAdd(inputExprs, argRef);
    final RexNode argSquared = rexBuilder.makeCall(SqlStdOperatorTable.MULTIPLY, argRef, argRef);
    final int argSquaredOrdinal = lookupOrAdd(inputExprs, argSquared);
    final AggregateCall sumArgSquaredAggCall = createAggregateCallWithBinding(typeFactory, SqlStdOperatorTable.SUM, argSquared.getType(), oldAggRel, oldCall, argSquaredOrdinal);
    final RexNode sumArgSquared = rexBuilder.addAggCall(sumArgSquaredAggCall, nGroups, oldAggRel.indicator, newCalls, aggCallMapping, ImmutableList.of(sumArgSquaredAggCall.getType()));
    final AggregateCall sumArgAggCall = AggregateCall.create(SqlStdOperatorTable.SUM, oldCall.isDistinct(), oldCall.isApproximate(), ImmutableIntList.of(argOrdinal), oldCall.filterArg, oldAggRel.getGroupCount(), oldAggRel.getInput(), null, null);
    final RexNode sumArg = rexBuilder.addAggCall(sumArgAggCall, nGroups, oldAggRel.indicator, newCalls, aggCallMapping, ImmutableList.of(sumArgAggCall.getType()));
    final RexNode sumArgCast = rexBuilder.ensureType(oldCallType, sumArg, true);
    final RexNode sumSquaredArg = rexBuilder.makeCall(SqlStdOperatorTable.MULTIPLY, sumArgCast, sumArgCast);
    final AggregateCall countArgAggCall = AggregateCall.create(SqlStdOperatorTable.COUNT, oldCall.isDistinct(), oldCall.isApproximate(), oldCall.getArgList(), oldCall.filterArg, oldAggRel.getGroupCount(), oldAggRel, null, null);
    final RexNode countArg = rexBuilder.addAggCall(countArgAggCall, nGroups, oldAggRel.indicator, newCalls, aggCallMapping, ImmutableList.of(argOrdinalType));
    final RexNode avgSumSquaredArg = rexBuilder.makeCall(SqlStdOperatorTable.DIVIDE, sumSquaredArg, countArg);
    final RexNode diff = rexBuilder.makeCall(SqlStdOperatorTable.MINUS, sumArgSquared, avgSumSquaredArg);
    final RexNode denominator;
    if (biased) {
        denominator = countArg;
    } else {
        final RexLiteral one = rexBuilder.makeExactLiteral(BigDecimal.ONE);
        final RexNode nul = rexBuilder.makeCast(countArg.getType(), rexBuilder.constantNull());
        final RexNode countMinusOne = rexBuilder.makeCall(SqlStdOperatorTable.MINUS, countArg, one);
        final RexNode countEqOne = rexBuilder.makeCall(SqlStdOperatorTable.EQUALS, countArg, one);
        denominator = rexBuilder.makeCall(SqlStdOperatorTable.CASE, countEqOne, nul, countMinusOne);
    }
    final RexNode div = rexBuilder.makeCall(SqlStdOperatorTable.DIVIDE, diff, denominator);
    RexNode result = div;
    if (sqrt) {
        final RexNode half = rexBuilder.makeExactLiteral(new BigDecimal("0.5"));
        result = rexBuilder.makeCall(SqlStdOperatorTable.POWER, div, half);
    }
    return rexBuilder.makeCast(oldCall.getType(), result);
}
Also used : RelOptCluster(org.apache.calcite.plan.RelOptCluster) AggregateCall(org.apache.calcite.rel.core.AggregateCall) RexLiteral(org.apache.calcite.rex.RexLiteral) RelDataTypeFactory(org.apache.calcite.rel.type.RelDataTypeFactory) RexBuilder(org.apache.calcite.rex.RexBuilder) RelDataType(org.apache.calcite.rel.type.RelDataType) BigDecimal(java.math.BigDecimal) RexNode(org.apache.calcite.rex.RexNode)

Example 12 with RexLiteral

use of org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.rex.RexLiteral in project calcite by apache.

the class RelToSqlConverter method visit.

/**
 * @see #dispatch
 */
public Result visit(Values e) {
    final List<Clause> clauses = ImmutableList.of(Clause.SELECT);
    final Map<String, RelDataType> pairs = ImmutableMap.of();
    final Context context = aliasContext(pairs, false);
    SqlNode query;
    final boolean rename = stack.size() <= 1 || !(Iterables.get(stack, 1).r instanceof TableModify);
    final List<String> fieldNames = e.getRowType().getFieldNames();
    if (!dialect.supportsAliasedValues() && rename) {
        // Oracle does not support "AS t (c1, c2)". So instead of
        // (VALUES (v0, v1), (v2, v3)) AS t (c0, c1)
        // we generate
        // SELECT v0 AS c0, v1 AS c1 FROM DUAL
        // UNION ALL
        // SELECT v2 AS c0, v3 AS c1 FROM DUAL
        List<SqlSelect> list = new ArrayList<>();
        for (List<RexLiteral> tuple : e.getTuples()) {
            final List<SqlNode> values2 = new ArrayList<>();
            final SqlNodeList exprList = exprList(context, tuple);
            for (Pair<SqlNode, String> value : Pair.zip(exprList, fieldNames)) {
                values2.add(SqlStdOperatorTable.AS.createCall(POS, value.left, new SqlIdentifier(value.right, POS)));
            }
            list.add(new SqlSelect(POS, null, new SqlNodeList(values2, POS), new SqlIdentifier("DUAL", POS), null, null, null, null, null, null, null));
        }
        if (list.size() == 1) {
            query = list.get(0);
        } else {
            query = SqlStdOperatorTable.UNION_ALL.createCall(new SqlNodeList(list, POS));
        }
    } else {
        // Generate ANSI syntax
        // (VALUES (v0, v1), (v2, v3))
        // or, if rename is required
        // (VALUES (v0, v1), (v2, v3)) AS t (c0, c1)
        final SqlNodeList selects = new SqlNodeList(POS);
        for (List<RexLiteral> tuple : e.getTuples()) {
            selects.add(ANONYMOUS_ROW.createCall(exprList(context, tuple)));
        }
        query = SqlStdOperatorTable.VALUES.createCall(selects);
        if (rename) {
            final List<SqlNode> list = new ArrayList<>();
            list.add(query);
            list.add(new SqlIdentifier("t", POS));
            for (String fieldName : fieldNames) {
                list.add(new SqlIdentifier(fieldName, POS));
            }
            query = SqlStdOperatorTable.AS.createCall(POS, list);
        }
    }
    return result(query, clauses, e, null);
}
Also used : RexLiteral(org.apache.calcite.rex.RexLiteral) ArrayList(java.util.ArrayList) RelDataType(org.apache.calcite.rel.type.RelDataType) SqlIdentifier(org.apache.calcite.sql.SqlIdentifier) SqlSelect(org.apache.calcite.sql.SqlSelect) SqlNodeList(org.apache.calcite.sql.SqlNodeList) TableModify(org.apache.calcite.rel.core.TableModify) SqlNode(org.apache.calcite.sql.SqlNode)

Example 13 with RexLiteral

use of org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.rex.RexLiteral in project calcite by apache.

the class RelToSqlConverter method visit.

/**
 * @see #dispatch
 */
public Result visit(Match e) {
    final RelNode input = e.getInput();
    final Result x = visitChild(0, input);
    final Context context = matchRecognizeContext(x.qualifiedContext());
    SqlNode tableRef = x.asQueryOrValues();
    final List<SqlNode> partitionSqlList = new ArrayList<>();
    if (e.getPartitionKeys() != null) {
        for (RexNode rex : e.getPartitionKeys()) {
            SqlNode sqlNode = context.toSql(null, rex);
            partitionSqlList.add(sqlNode);
        }
    }
    final SqlNodeList partitionList = new SqlNodeList(partitionSqlList, POS);
    final List<SqlNode> orderBySqlList = new ArrayList<>();
    if (e.getOrderKeys() != null) {
        for (RelFieldCollation fc : e.getOrderKeys().getFieldCollations()) {
            if (fc.nullDirection != RelFieldCollation.NullDirection.UNSPECIFIED) {
                boolean first = fc.nullDirection == RelFieldCollation.NullDirection.FIRST;
                SqlNode nullDirectionNode = dialect.emulateNullDirection(context.field(fc.getFieldIndex()), first, fc.direction.isDescending());
                if (nullDirectionNode != null) {
                    orderBySqlList.add(nullDirectionNode);
                    fc = new RelFieldCollation(fc.getFieldIndex(), fc.getDirection(), RelFieldCollation.NullDirection.UNSPECIFIED);
                }
            }
            orderBySqlList.add(context.toSql(fc));
        }
    }
    final SqlNodeList orderByList = new SqlNodeList(orderBySqlList, SqlParserPos.ZERO);
    final SqlLiteral rowsPerMatch = e.isAllRows() ? SqlMatchRecognize.RowsPerMatchOption.ALL_ROWS.symbol(POS) : SqlMatchRecognize.RowsPerMatchOption.ONE_ROW.symbol(POS);
    final SqlNode after;
    if (e.getAfter() instanceof RexLiteral) {
        SqlMatchRecognize.AfterOption value = (SqlMatchRecognize.AfterOption) ((RexLiteral) e.getAfter()).getValue2();
        after = SqlLiteral.createSymbol(value, POS);
    } else {
        RexCall call = (RexCall) e.getAfter();
        String operand = RexLiteral.stringValue(call.getOperands().get(0));
        after = call.getOperator().createCall(POS, new SqlIdentifier(operand, POS));
    }
    RexNode rexPattern = e.getPattern();
    final SqlNode pattern = context.toSql(null, rexPattern);
    final SqlLiteral strictStart = SqlLiteral.createBoolean(e.isStrictStart(), POS);
    final SqlLiteral strictEnd = SqlLiteral.createBoolean(e.isStrictEnd(), POS);
    RexLiteral rexInterval = (RexLiteral) e.getInterval();
    SqlIntervalLiteral interval = null;
    if (rexInterval != null) {
        interval = (SqlIntervalLiteral) context.toSql(null, rexInterval);
    }
    final SqlNodeList subsetList = new SqlNodeList(POS);
    for (Map.Entry<String, SortedSet<String>> entry : e.getSubsets().entrySet()) {
        SqlNode left = new SqlIdentifier(entry.getKey(), POS);
        List<SqlNode> rhl = Lists.newArrayList();
        for (String right : entry.getValue()) {
            rhl.add(new SqlIdentifier(right, POS));
        }
        subsetList.add(SqlStdOperatorTable.EQUALS.createCall(POS, left, new SqlNodeList(rhl, POS)));
    }
    final SqlNodeList measureList = new SqlNodeList(POS);
    for (Map.Entry<String, RexNode> entry : e.getMeasures().entrySet()) {
        final String alias = entry.getKey();
        final SqlNode sqlNode = context.toSql(null, entry.getValue());
        measureList.add(as(sqlNode, alias));
    }
    final SqlNodeList patternDefList = new SqlNodeList(POS);
    for (Map.Entry<String, RexNode> entry : e.getPatternDefinitions().entrySet()) {
        final String alias = entry.getKey();
        final SqlNode sqlNode = context.toSql(null, entry.getValue());
        patternDefList.add(as(sqlNode, alias));
    }
    final SqlNode matchRecognize = new SqlMatchRecognize(POS, tableRef, pattern, strictStart, strictEnd, patternDefList, measureList, after, subsetList, rowsPerMatch, partitionList, orderByList, interval);
    return result(matchRecognize, Expressions.list(Clause.FROM), e, null);
}
Also used : RexLiteral(org.apache.calcite.rex.RexLiteral) SqlIntervalLiteral(org.apache.calcite.sql.SqlIntervalLiteral) ArrayList(java.util.ArrayList) SqlMatchRecognize(org.apache.calcite.sql.SqlMatchRecognize) SqlIdentifier(org.apache.calcite.sql.SqlIdentifier) SortedSet(java.util.SortedSet) RexCall(org.apache.calcite.rex.RexCall) RelNode(org.apache.calcite.rel.RelNode) RelFieldCollation(org.apache.calcite.rel.RelFieldCollation) SqlNodeList(org.apache.calcite.sql.SqlNodeList) SqlLiteral(org.apache.calcite.sql.SqlLiteral) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) SqlNode(org.apache.calcite.sql.SqlNode) RexNode(org.apache.calcite.rex.RexNode)

Example 14 with RexLiteral

use of org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.rex.RexLiteral in project calcite by apache.

the class RelMdUtil method getSelectivityValue.

/**
 * Returns the selectivity value stored in a call.
 *
 * @param artificialSelectivityFuncNode Call containing the selectivity value
 * @return selectivity value
 */
public static double getSelectivityValue(RexNode artificialSelectivityFuncNode) {
    assert artificialSelectivityFuncNode instanceof RexCall;
    RexCall call = (RexCall) artificialSelectivityFuncNode;
    assert call.getOperator() == ARTIFICIAL_SELECTIVITY_FUNC;
    RexNode operand = call.getOperands().get(0);
    return ((RexLiteral) operand).getValueAs(Double.class);
}
Also used : RexCall(org.apache.calcite.rex.RexCall) RexLiteral(org.apache.calcite.rex.RexLiteral) RexNode(org.apache.calcite.rex.RexNode)

Example 15 with RexLiteral

use of org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.rex.RexLiteral in project calcite by apache.

the class SqlToRelConverter method convertLiteralInValuesList.

private RexLiteral convertLiteralInValuesList(SqlNode sqlNode, Blackboard bb, RelDataType rowType, int iField) {
    if (!(sqlNode instanceof SqlLiteral)) {
        return null;
    }
    RelDataTypeField field = rowType.getFieldList().get(iField);
    RelDataType type = field.getType();
    if (type.isStruct()) {
        // don't use LogicalValues for those
        return null;
    }
    RexNode literalExpr = exprConverter.convertLiteral(bb, (SqlLiteral) sqlNode);
    if (!(literalExpr instanceof RexLiteral)) {
        assert literalExpr.isA(SqlKind.CAST);
        RexNode child = ((RexCall) literalExpr).getOperands().get(0);
        assert RexLiteral.isNullLiteral(child);
        // in LogicalValues digest, so it's OK to lose it here
        return (RexLiteral) child;
    }
    RexLiteral literal = (RexLiteral) literalExpr;
    Comparable value = literal.getValue();
    if (SqlTypeUtil.isExactNumeric(type) && SqlTypeUtil.hasScale(type)) {
        BigDecimal roundedValue = NumberUtil.rescaleBigDecimal((BigDecimal) value, type.getScale());
        return rexBuilder.makeExactLiteral(roundedValue, type);
    }
    if ((value instanceof NlsString) && (type.getSqlTypeName() == SqlTypeName.CHAR)) {
        // pad fixed character type
        NlsString unpadded = (NlsString) value;
        return rexBuilder.makeCharLiteral(new NlsString(Spaces.padRight(unpadded.getValue(), type.getPrecision()), unpadded.getCharsetName(), unpadded.getCollation()));
    }
    return literal;
}
Also used : RexLiteral(org.apache.calcite.rex.RexLiteral) RelDataTypeField(org.apache.calcite.rel.type.RelDataTypeField) NlsString(org.apache.calcite.util.NlsString) RelDataType(org.apache.calcite.rel.type.RelDataType) SqlLiteral(org.apache.calcite.sql.SqlLiteral) BigDecimal(java.math.BigDecimal) RexNode(org.apache.calcite.rex.RexNode)

Aggregations

RexLiteral (org.apache.calcite.rex.RexLiteral)150 RexNode (org.apache.calcite.rex.RexNode)92 ArrayList (java.util.ArrayList)51 RelDataType (org.apache.calcite.rel.type.RelDataType)45 RexCall (org.apache.calcite.rex.RexCall)45 Test (org.junit.Test)32 BigDecimal (java.math.BigDecimal)29 RexInputRef (org.apache.calcite.rex.RexInputRef)26 RelNode (org.apache.calcite.rel.RelNode)22 ImmutableList (com.google.common.collect.ImmutableList)18 RelDataTypeField (org.apache.calcite.rel.type.RelDataTypeField)17 List (java.util.List)16 Map (java.util.Map)16 RexBuilder (org.apache.calcite.rex.RexBuilder)16 AggregateCall (org.apache.calcite.rel.core.AggregateCall)15 ImmutableBitSet (org.apache.calcite.util.ImmutableBitSet)12 RexLiteral (org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.rex.RexLiteral)11 NlsString (org.apache.calcite.util.NlsString)11 HashMap (java.util.HashMap)10 RexNode (org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.rex.RexNode)10