Search in sources :

Example 11 with RexCall

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

the class RexImpTable method createImplementor.

public static CallImplementor createImplementor(final NotNullImplementor implementor, final NullPolicy nullPolicy, final boolean harmonize) {
    switch(nullPolicy) {
        case ANY:
        case STRICT:
        case SEMI_STRICT:
            return new CallImplementor() {

                public Expression implement(RexToLixTranslator translator, RexCall call, NullAs nullAs) {
                    return implementNullSemantics0(translator, call, nullAs, nullPolicy, harmonize, implementor);
                }
            };
        case AND:
            // : Boolean.FALSE;
            return new CallImplementor() {

                public Expression implement(RexToLixTranslator translator, RexCall call, NullAs nullAs) {
                    assert call.getOperator() == AND : "AND null semantics is supported only for AND operator. Actual operator is " + String.valueOf(call.getOperator());
                    final RexCall call2 = call2(false, translator, call);
                    switch(nullAs) {
                        // Just foldAnd
                        case NOT_POSSIBLE:
                        case TRUE:
                        // thus if we convert nulls to true then no harm is made
                        case FALSE:
                            // AND call should return false iff has FALSEs or has NULLs,
                            // thus if we convert nulls to false, no harm is made
                            final List<Expression> expressions = translator.translateList(call2.getOperands(), nullAs);
                            return Expressions.foldAnd(expressions);
                        case NULL:
                        case IS_NULL:
                        case IS_NOT_NULL:
                            final List<Expression> nullAsTrue = translator.translateList(call2.getOperands(), NullAs.TRUE);
                            final List<Expression> nullAsIsNull = translator.translateList(call2.getOperands(), NullAs.IS_NULL);
                            Expression hasFalse = Expressions.not(Expressions.foldAnd(nullAsTrue));
                            Expression hasNull = Expressions.foldOr(nullAsIsNull);
                            Expression result = nullAs.handle(Expressions.condition(hasFalse, BOXED_FALSE_EXPR, Expressions.condition(hasNull, NULL_EXPR, BOXED_TRUE_EXPR)));
                            return result;
                        default:
                            throw new IllegalArgumentException("Unknown nullAs when implementing AND: " + nullAs);
                    }
                }
            };
        case OR:
            // : Boolean.TRUE;
            return new CallImplementor() {

                public Expression implement(RexToLixTranslator translator, RexCall call, final NullAs nullAs) {
                    assert call.getOperator() == OR : "OR null semantics is supported only for OR operator. Actual operator is " + String.valueOf(call.getOperator());
                    final RexCall call2 = call2(harmonize, translator, call);
                    switch(nullAs) {
                        // Just foldOr
                        case NOT_POSSIBLE:
                        case TRUE:
                        // thus we convert nulls to TRUE and foldOr
                        case FALSE:
                            // This should return true iff has TRUE arguments,
                            // thus we convert nulls to FALSE and foldOr
                            final List<Expression> expressions = translator.translateList(call2.getOperands(), nullAs);
                            return Expressions.foldOr(expressions);
                        case NULL:
                        case IS_NULL:
                        case IS_NOT_NULL:
                            final List<Expression> nullAsFalse = translator.translateList(call2.getOperands(), NullAs.FALSE);
                            final List<Expression> nullAsIsNull = translator.translateList(call2.getOperands(), NullAs.IS_NULL);
                            Expression hasTrue = Expressions.foldOr(nullAsFalse);
                            Expression hasNull = Expressions.foldOr(nullAsIsNull);
                            Expression result = nullAs.handle(Expressions.condition(hasTrue, BOXED_TRUE_EXPR, Expressions.condition(hasNull, NULL_EXPR, BOXED_FALSE_EXPR)));
                            return result;
                        default:
                            throw new IllegalArgumentException("Unknown nullAs when implementing OR: " + nullAs);
                    }
                }
            };
        case NOT:
            // else false.
            return new CallImplementor() {

                public Expression implement(RexToLixTranslator translator, RexCall call, NullAs nullAs) {
                    switch(nullAs) {
                        case NULL:
                            return Expressions.call(BuiltInMethod.NOT.method, translator.translateList(call.getOperands(), nullAs));
                        default:
                            return Expressions.not(translator.translate(call.getOperands().get(0), negate(nullAs)));
                    }
                }

                private NullAs negate(NullAs nullAs) {
                    switch(nullAs) {
                        case FALSE:
                            return NullAs.TRUE;
                        case TRUE:
                            return NullAs.FALSE;
                        default:
                            return nullAs;
                    }
                }
            };
        case NONE:
            return new CallImplementor() {

                public Expression implement(RexToLixTranslator translator, RexCall call, NullAs nullAs) {
                    final RexCall call2 = call2(false, translator, call);
                    return implementCall(translator, call2, implementor, nullAs);
                }
            };
        default:
            throw new AssertionError(nullPolicy);
    }
}
Also used : RexCall(org.apache.calcite.rex.RexCall) UnaryExpression(org.apache.calcite.linq4j.tree.UnaryExpression) ConstantExpression(org.apache.calcite.linq4j.tree.ConstantExpression) ParameterExpression(org.apache.calcite.linq4j.tree.ParameterExpression) Expression(org.apache.calcite.linq4j.tree.Expression) MemberExpression(org.apache.calcite.linq4j.tree.MemberExpression)

Example 12 with RexCall

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

the class RexToLixTranslator method translate0.

/**
 * Translates an expression that is not in the cache.
 *
 * @param expr Expression
 * @param nullAs If false, if expression is definitely not null at
 *   runtime. Therefore we can optimize. For example, we can cast to int
 *   using x.intValue().
 * @return Translated expression
 */
private Expression translate0(RexNode expr, RexImpTable.NullAs nullAs, Type storageType) {
    if (nullAs == RexImpTable.NullAs.NULL && !expr.getType().isNullable()) {
        nullAs = RexImpTable.NullAs.NOT_POSSIBLE;
    }
    switch(expr.getKind()) {
        case INPUT_REF:
            final int index = ((RexInputRef) expr).getIndex();
            Expression x = inputGetter.field(list, index, storageType);
            // safe to share
            Expression input = list.append("inp" + index + "_", x);
            if (nullAs == RexImpTable.NullAs.NOT_POSSIBLE && input.type.equals(storageType)) {
                // unboxing via nullAs.handle below.
                return input;
            }
            return handleNull(input, nullAs);
        case LOCAL_REF:
            return translate(deref(expr), nullAs, storageType);
        case LITERAL:
            return translateLiteral((RexLiteral) expr, nullifyType(expr.getType(), isNullable(expr) && nullAs != RexImpTable.NullAs.NOT_POSSIBLE), typeFactory, nullAs);
        case DYNAMIC_PARAM:
            return translateParameter((RexDynamicParam) expr, nullAs, storageType);
        case CORREL_VARIABLE:
            throw new RuntimeException("Cannot translate " + expr + ". Correlated" + " variables should always be referenced by field access");
        case FIELD_ACCESS:
            RexFieldAccess fieldAccess = (RexFieldAccess) expr;
            RexNode target = deref(fieldAccess.getReferenceExpr());
            // only $cor.field access is supported
            if (!(target instanceof RexCorrelVariable)) {
                throw new RuntimeException("cannot translate expression " + expr);
            }
            if (correlates == null) {
                throw new RuntimeException("Cannot translate " + expr + " since " + "correlate variables resolver is not defined");
            }
            InputGetter getter = correlates.apply(((RexCorrelVariable) target).getName());
            return getter.field(list, fieldAccess.getField().getIndex(), storageType);
        default:
            if (expr instanceof RexCall) {
                return translateCall((RexCall) expr, nullAs);
            }
            throw new RuntimeException("cannot translate expression " + expr);
    }
}
Also used : RexCall(org.apache.calcite.rex.RexCall) RexCorrelVariable(org.apache.calcite.rex.RexCorrelVariable) Expression(org.apache.calcite.linq4j.tree.Expression) UnaryExpression(org.apache.calcite.linq4j.tree.UnaryExpression) ConstantExpression(org.apache.calcite.linq4j.tree.ConstantExpression) ParameterExpression(org.apache.calcite.linq4j.tree.ParameterExpression) RexInputRef(org.apache.calcite.rex.RexInputRef) RexFieldAccess(org.apache.calcite.rex.RexFieldAccess) RexNode(org.apache.calcite.rex.RexNode)

Example 13 with RexCall

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

the class EnumerableTableFunctionScan method isQueryable.

private boolean isQueryable() {
    if (!(getCall() instanceof RexCall)) {
        return false;
    }
    final RexCall call = (RexCall) getCall();
    if (!(call.getOperator() instanceof SqlUserDefinedTableFunction)) {
        return false;
    }
    final SqlUserDefinedTableFunction udtf = (SqlUserDefinedTableFunction) call.getOperator();
    if (!(udtf.getFunction() instanceof TableFunctionImpl)) {
        return false;
    }
    final TableFunctionImpl tableFunction = (TableFunctionImpl) udtf.getFunction();
    final Method method = tableFunction.method;
    return QueryableTable.class.isAssignableFrom(method.getReturnType());
}
Also used : RexCall(org.apache.calcite.rex.RexCall) SqlUserDefinedTableFunction(org.apache.calcite.sql.validate.SqlUserDefinedTableFunction) TableFunctionImpl(org.apache.calcite.schema.impl.TableFunctionImpl) Method(java.lang.reflect.Method)

Example 14 with RexCall

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

the class AbstractMaterializedViewRule method replaceWithOriginalReferences.

/**
 * Given the input expression, it will replace (sub)expressions when possible
 * using the content of the mapping. In particular, the mapping contains the
 * digest of the expression and the index that the replacement input ref should
 * point to.
 */
private static RexNode replaceWithOriginalReferences(final RexBuilder rexBuilder, final RelNode node, final NodeLineage nodeLineage, final RexNode exprToRewrite) {
    // Currently we allow the following:
    // 1) compensation pred can be directly map to expression
    // 2) all references in compensation pred can be map to expressions
    // We support bypassing lossless casts.
    RexShuttle visitor = new RexShuttle() {

        @Override
        public RexNode visitCall(RexCall call) {
            RexNode rw = replace(call);
            return rw != null ? rw : super.visitCall(call);
        }

        @Override
        public RexNode visitTableInputRef(RexTableInputRef inputRef) {
            RexNode rw = replace(inputRef);
            return rw != null ? rw : super.visitTableInputRef(inputRef);
        }

        private RexNode replace(RexNode e) {
            Integer pos = nodeLineage.exprsLineage.get(e.toString());
            if (pos != null) {
                // Found it
                return rexBuilder.makeInputRef(node, pos);
            }
            pos = nodeLineage.exprsLineageLosslessCasts.get(e.toString());
            if (pos != null) {
                // Found it
                return rexBuilder.makeCast(e.getType(), rexBuilder.makeInputRef(node, pos));
            }
            return null;
        }
    };
    return visitor.apply(exprToRewrite);
}
Also used : RexCall(org.apache.calcite.rex.RexCall) RexShuttle(org.apache.calcite.rex.RexShuttle) RexTableInputRef(org.apache.calcite.rex.RexTableInputRef) RexNode(org.apache.calcite.rex.RexNode)

Example 15 with RexCall

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

the class AbstractMaterializedViewRule method perform.

/**
 * Rewriting logic is based on "Optimizing Queries Using Materialized Views:
 * A Practical, Scalable Solution" by Goldstein and Larson.
 *
 * <p>On the query side, rules matches a Project-node chain or node, where node
 * is either an Aggregate or a Join. Subplan rooted at the node operator must
 * be composed of one or more of the following operators: TableScan, Project,
 * Filter, and Join.
 *
 * <p>For each join MV, we need to check the following:
 * <ol>
 * <li> The plan rooted at the Join operator in the view produces all rows
 * needed by the plan rooted at the Join operator in the query.</li>
 * <li> All columns required by compensating predicates, i.e., predicates that
 * need to be enforced over the view, are available at the view output.</li>
 * <li> All output expressions can be computed from the output of the view.</li>
 * <li> All output rows occur with the correct duplication factor. We might
 * rely on existing Unique-Key - Foreign-Key relationships to extract that
 * information.</li>
 * </ol>
 *
 * <p>In turn, for each aggregate MV, we need to check the following:
 * <ol>
 * <li> The plan rooted at the Aggregate operator in the view produces all rows
 * needed by the plan rooted at the Aggregate operator in the query.</li>
 * <li> All columns required by compensating predicates, i.e., predicates that
 * need to be enforced over the view, are available at the view output.</li>
 * <li> The grouping columns in the query are a subset of the grouping columns
 * in the view.</li>
 * <li> All columns required to perform further grouping are available in the
 * view output.</li>
 * <li> All columns required to compute output expressions are available in the
 * view output.</li>
 * </ol>
 *
 * <p>The rule contains multiple extensions compared to the original paper. One of
 * them is the possibility of creating rewritings using Union operators, e.g., if
 * the result of a query is partially contained in the materialized view.
 */
protected void perform(RelOptRuleCall call, Project topProject, RelNode node) {
    final RexBuilder rexBuilder = node.getCluster().getRexBuilder();
    final RelMetadataQuery mq = RelMetadataQuery.instance();
    final RelOptPlanner planner = call.getPlanner();
    final RexExecutor executor = Util.first(planner.getExecutor(), RexUtil.EXECUTOR);
    final RelOptPredicateList predicates = RelOptPredicateList.EMPTY;
    final RexSimplify simplify = new RexSimplify(rexBuilder, predicates, true, executor);
    final List<RelOptMaterialization> materializations = (planner instanceof VolcanoPlanner) ? ((VolcanoPlanner) planner).getMaterializations() : ImmutableList.<RelOptMaterialization>of();
    if (!materializations.isEmpty()) {
        // try to generate a rewriting are met
        if (!isValidPlan(topProject, node, mq)) {
            return;
        }
        // Obtain applicable (filtered) materializations
        // TODO: Filtering of relevant materializations needs to be
        // improved so we gather only materializations that might
        // actually generate a valid rewriting.
        final List<RelOptMaterialization> applicableMaterializations = RelOptMaterializations.getApplicableMaterializations(node, materializations);
        if (!applicableMaterializations.isEmpty()) {
            // 2. Initialize all query related auxiliary data structures
            // that will be used throughout query rewriting process
            // Generate query table references
            final Set<RelTableRef> queryTableRefs = mq.getTableReferences(node);
            if (queryTableRefs == null) {
                // Bail out
                return;
            }
            // Extract query predicates
            final RelOptPredicateList queryPredicateList = mq.getAllPredicates(node);
            if (queryPredicateList == null) {
                // Bail out
                return;
            }
            final RexNode pred = simplify.simplify(RexUtil.composeConjunction(rexBuilder, queryPredicateList.pulledUpPredicates, false));
            final Triple<RexNode, RexNode, RexNode> queryPreds = splitPredicates(rexBuilder, pred);
            // Extract query equivalence classes. An equivalence class is a set
            // of columns in the query output that are known to be equal.
            final EquivalenceClasses qEC = new EquivalenceClasses();
            for (RexNode conj : RelOptUtil.conjunctions(queryPreds.getLeft())) {
                assert conj.isA(SqlKind.EQUALS);
                RexCall equiCond = (RexCall) conj;
                qEC.addEquivalenceClass((RexTableInputRef) equiCond.getOperands().get(0), (RexTableInputRef) equiCond.getOperands().get(1));
            }
            // rewrite the given query
            for (RelOptMaterialization materialization : applicableMaterializations) {
                RelNode view = materialization.tableRel;
                Project topViewProject;
                RelNode viewNode;
                if (materialization.queryRel instanceof Project) {
                    topViewProject = (Project) materialization.queryRel;
                    viewNode = topViewProject.getInput();
                } else {
                    topViewProject = null;
                    viewNode = materialization.queryRel;
                }
                // 3.1. View checks before proceeding
                if (!isValidPlan(topViewProject, viewNode, mq)) {
                    // Skip it
                    continue;
                }
                // 3.2. Initialize all query related auxiliary data structures
                // that will be used throughout query rewriting process
                // Extract view predicates
                final RelOptPredicateList viewPredicateList = mq.getAllPredicates(viewNode);
                if (viewPredicateList == null) {
                    // Skip it
                    continue;
                }
                final RexNode viewPred = simplify.simplify(RexUtil.composeConjunction(rexBuilder, viewPredicateList.pulledUpPredicates, false));
                final Triple<RexNode, RexNode, RexNode> viewPreds = splitPredicates(rexBuilder, viewPred);
                // Extract view table references
                final Set<RelTableRef> viewTableRefs = mq.getTableReferences(viewNode);
                if (viewTableRefs == null) {
                    // Bail out
                    return;
                }
                // Extract view tables
                MatchModality matchModality;
                Multimap<RexTableInputRef, RexTableInputRef> compensationEquiColumns = ArrayListMultimap.create();
                if (!queryTableRefs.equals(viewTableRefs)) {
                    // subset of query tables (add additional tables through joins if possible)
                    if (viewTableRefs.containsAll(queryTableRefs)) {
                        matchModality = MatchModality.QUERY_PARTIAL;
                        final EquivalenceClasses vEC = new EquivalenceClasses();
                        for (RexNode conj : RelOptUtil.conjunctions(viewPreds.getLeft())) {
                            assert conj.isA(SqlKind.EQUALS);
                            RexCall equiCond = (RexCall) conj;
                            vEC.addEquivalenceClass((RexTableInputRef) equiCond.getOperands().get(0), (RexTableInputRef) equiCond.getOperands().get(1));
                        }
                        if (!compensatePartial(viewTableRefs, vEC, queryTableRefs, compensationEquiColumns)) {
                            // Cannot rewrite, skip it
                            continue;
                        }
                    } else if (queryTableRefs.containsAll(viewTableRefs)) {
                        matchModality = MatchModality.VIEW_PARTIAL;
                        ViewPartialRewriting partialRewritingResult = compensateViewPartial(call.builder(), rexBuilder, mq, view, topProject, node, queryTableRefs, qEC, topViewProject, viewNode, viewTableRefs);
                        if (partialRewritingResult == null) {
                            // Cannot rewrite, skip it
                            continue;
                        }
                        // Rewrite succeeded
                        view = partialRewritingResult.newView;
                        topViewProject = partialRewritingResult.newTopViewProject;
                        viewNode = partialRewritingResult.newViewNode;
                    } else {
                        // Skip it
                        continue;
                    }
                } else {
                    matchModality = MatchModality.COMPLETE;
                }
                // 4. We map every table in the query to a table with the same qualified
                // name (all query tables are contained in the view, thus this is equivalent
                // to mapping every table in the query to a view table).
                final Multimap<RelTableRef, RelTableRef> multiMapTables = ArrayListMultimap.create();
                for (RelTableRef queryTableRef1 : queryTableRefs) {
                    for (RelTableRef queryTableRef2 : queryTableRefs) {
                        if (queryTableRef1.getQualifiedName().equals(queryTableRef2.getQualifiedName())) {
                            multiMapTables.put(queryTableRef1, queryTableRef2);
                        }
                    }
                }
                // If a table is used multiple times, we will create multiple mappings,
                // and we will try to rewrite the query using each of the mappings.
                // Then, we will try to map every source table (query) to a target
                // table (view), and if we are successful, we will try to create
                // compensation predicates to filter the view results further
                // (if needed).
                final List<BiMap<RelTableRef, RelTableRef>> flatListMappings = generateTableMappings(multiMapTables);
                for (BiMap<RelTableRef, RelTableRef> queryToViewTableMapping : flatListMappings) {
                    // TableMapping : mapping query tables -> view tables
                    // 4.0. If compensation equivalence classes exist, we need to add
                    // the mapping to the query mapping
                    final EquivalenceClasses currQEC = EquivalenceClasses.copy(qEC);
                    if (matchModality == MatchModality.QUERY_PARTIAL) {
                        for (Entry<RexTableInputRef, RexTableInputRef> e : compensationEquiColumns.entries()) {
                            // Copy origin
                            RelTableRef queryTableRef = queryToViewTableMapping.inverse().get(e.getKey().getTableRef());
                            RexTableInputRef queryColumnRef = RexTableInputRef.of(queryTableRef, e.getKey().getIndex(), e.getKey().getType());
                            // Add to query equivalence classes and table mapping
                            currQEC.addEquivalenceClass(queryColumnRef, e.getValue());
                            queryToViewTableMapping.put(e.getValue().getTableRef(), // identity
                            e.getValue().getTableRef());
                        }
                    }
                    // 4.1. Compute compensation predicates, i.e., predicates that need to be
                    // enforced over the view to retain query semantics. The resulting predicates
                    // are expressed using {@link RexTableInputRef} over the query.
                    // First, to establish relationship, we swap column references of the view
                    // predicates to point to query tables and compute equivalence classes.
                    final RexNode viewColumnsEquiPred = RexUtil.swapTableReferences(rexBuilder, viewPreds.getLeft(), queryToViewTableMapping.inverse());
                    final EquivalenceClasses queryBasedVEC = new EquivalenceClasses();
                    for (RexNode conj : RelOptUtil.conjunctions(viewColumnsEquiPred)) {
                        assert conj.isA(SqlKind.EQUALS);
                        RexCall equiCond = (RexCall) conj;
                        queryBasedVEC.addEquivalenceClass((RexTableInputRef) equiCond.getOperands().get(0), (RexTableInputRef) equiCond.getOperands().get(1));
                    }
                    Triple<RexNode, RexNode, RexNode> compensationPreds = computeCompensationPredicates(rexBuilder, simplify, currQEC, queryPreds, queryBasedVEC, viewPreds, queryToViewTableMapping);
                    if (compensationPreds == null && generateUnionRewriting) {
                        // Attempt partial rewriting using union operator. This rewriting
                        // will read some data from the view and the rest of the data from
                        // the query computation. The resulting predicates are expressed
                        // using {@link RexTableInputRef} over the view.
                        compensationPreds = computeCompensationPredicates(rexBuilder, simplify, queryBasedVEC, viewPreds, currQEC, queryPreds, queryToViewTableMapping.inverse());
                        if (compensationPreds == null) {
                            // This was our last chance to use the view, skip it
                            continue;
                        }
                        RexNode compensationColumnsEquiPred = compensationPreds.getLeft();
                        RexNode otherCompensationPred = RexUtil.composeConjunction(rexBuilder, ImmutableList.of(compensationPreds.getMiddle(), compensationPreds.getRight()), false);
                        assert !compensationColumnsEquiPred.isAlwaysTrue() || !otherCompensationPred.isAlwaysTrue();
                        // b. Generate union branch (query).
                        final RelNode unionInputQuery = rewriteQuery(call.builder(), rexBuilder, simplify, mq, compensationColumnsEquiPred, otherCompensationPred, topProject, node, queryToViewTableMapping, queryBasedVEC, currQEC);
                        if (unionInputQuery == null) {
                            // Skip it
                            continue;
                        }
                        // c. Generate union branch (view).
                        // We trigger the unifying method. This method will either create a Project
                        // or an Aggregate operator on top of the view. It will also compute the
                        // output expressions for the query.
                        final RelNode unionInputView = rewriteView(call.builder(), rexBuilder, simplify, mq, matchModality, true, view, topProject, node, topViewProject, viewNode, queryToViewTableMapping, currQEC);
                        if (unionInputView == null) {
                            // Skip it
                            continue;
                        }
                        // d. Generate final rewriting (union).
                        final RelNode result = createUnion(call.builder(), rexBuilder, topProject, unionInputQuery, unionInputView);
                        if (result == null) {
                            // Skip it
                            continue;
                        }
                        call.transformTo(result);
                    } else if (compensationPreds != null) {
                        RexNode compensationColumnsEquiPred = compensationPreds.getLeft();
                        RexNode otherCompensationPred = RexUtil.composeConjunction(rexBuilder, ImmutableList.of(compensationPreds.getMiddle(), compensationPreds.getRight()), false);
                        // a. Compute final compensation predicate.
                        if (!compensationColumnsEquiPred.isAlwaysTrue() || !otherCompensationPred.isAlwaysTrue()) {
                            // All columns required by compensating predicates must be contained
                            // in the view output (condition 2).
                            List<RexNode> viewExprs = topViewProject == null ? extractReferences(rexBuilder, view) : topViewProject.getChildExps();
                            // since we want to enforce the rest
                            if (!compensationColumnsEquiPred.isAlwaysTrue()) {
                                compensationColumnsEquiPred = rewriteExpression(rexBuilder, mq, view, viewNode, viewExprs, queryToViewTableMapping.inverse(), queryBasedVEC, false, compensationColumnsEquiPred);
                                if (compensationColumnsEquiPred == null) {
                                    // Skip it
                                    continue;
                                }
                            }
                            // For the rest, we use the query equivalence classes
                            if (!otherCompensationPred.isAlwaysTrue()) {
                                otherCompensationPred = rewriteExpression(rexBuilder, mq, view, viewNode, viewExprs, queryToViewTableMapping.inverse(), currQEC, true, otherCompensationPred);
                                if (otherCompensationPred == null) {
                                    // Skip it
                                    continue;
                                }
                            }
                        }
                        final RexNode viewCompensationPred = RexUtil.composeConjunction(rexBuilder, ImmutableList.of(compensationColumnsEquiPred, otherCompensationPred), false);
                        // b. Generate final rewriting if possible.
                        // First, we add the compensation predicate (if any) on top of the view.
                        // Then, we trigger the unifying method. This method will either create a
                        // Project or an Aggregate operator on top of the view. It will also compute
                        // the output expressions for the query.
                        RelBuilder builder = call.builder();
                        RelNode viewWithFilter;
                        if (!viewCompensationPred.isAlwaysTrue()) {
                            RexNode newPred = simplify.simplify(viewCompensationPred);
                            viewWithFilter = builder.push(view).filter(newPred).build();
                            // We add (and push) the filter to the view plan before triggering the rewriting.
                            // This is useful in case some of the columns can be folded to same value after
                            // filter is added.
                            Pair<RelNode, RelNode> pushedNodes = pushFilterToOriginalViewPlan(builder, topViewProject, viewNode, newPred);
                            topViewProject = (Project) pushedNodes.left;
                            viewNode = pushedNodes.right;
                        } else {
                            viewWithFilter = builder.push(view).build();
                        }
                        final RelNode result = rewriteView(builder, rexBuilder, simplify, mq, matchModality, false, viewWithFilter, topProject, node, topViewProject, viewNode, queryToViewTableMapping, currQEC);
                        if (result == null) {
                            // Skip it
                            continue;
                        }
                        call.transformTo(result);
                    }
                // end else
                }
            }
        }
    }
}
Also used : RelMetadataQuery(org.apache.calcite.rel.metadata.RelMetadataQuery) RelOptPlanner(org.apache.calcite.plan.RelOptPlanner) RexCall(org.apache.calcite.rex.RexCall) RexExecutor(org.apache.calcite.rex.RexExecutor) RelOptPredicateList(org.apache.calcite.plan.RelOptPredicateList) RexBuilder(org.apache.calcite.rex.RexBuilder) RelOptPredicateList(org.apache.calcite.plan.RelOptPredicateList) List(java.util.List) ArrayList(java.util.ArrayList) ImmutableList(com.google.common.collect.ImmutableList) Pair(org.apache.calcite.util.Pair) RelBuilder(org.apache.calcite.tools.RelBuilder) BiMap(com.google.common.collect.BiMap) HashBiMap(com.google.common.collect.HashBiMap) RelTableRef(org.apache.calcite.rex.RexTableInputRef.RelTableRef) RexTableInputRef(org.apache.calcite.rex.RexTableInputRef) Project(org.apache.calcite.rel.core.Project) RelNode(org.apache.calcite.rel.RelNode) RexSimplify(org.apache.calcite.rex.RexSimplify) RelOptMaterialization(org.apache.calcite.plan.RelOptMaterialization) VolcanoPlanner(org.apache.calcite.plan.volcano.VolcanoPlanner) RexNode(org.apache.calcite.rex.RexNode)

Aggregations

RexCall (org.apache.calcite.rex.RexCall)213 RexNode (org.apache.calcite.rex.RexNode)172 RexInputRef (org.apache.calcite.rex.RexInputRef)61 ArrayList (java.util.ArrayList)60 RexLiteral (org.apache.calcite.rex.RexLiteral)44 Nullable (javax.annotation.Nullable)35 RelNode (org.apache.calcite.rel.RelNode)26 RelDataType (org.apache.calcite.rel.type.RelDataType)24 SqlOperator (org.apache.calcite.sql.SqlOperator)23 List (java.util.List)22 RexBuilder (org.apache.calcite.rex.RexBuilder)22 DruidExpression (org.apache.druid.sql.calcite.expression.DruidExpression)19 SqlKind (org.apache.calcite.sql.SqlKind)14 ImmutableBitSet (org.apache.calcite.util.ImmutableBitSet)14 RelOptUtil (org.apache.calcite.plan.RelOptUtil)11 PostAggregator (org.apache.druid.query.aggregation.PostAggregator)11 RexCall (org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.rex.RexCall)10 RexNode (org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.rex.RexNode)10 RexTableInputRef (org.apache.calcite.rex.RexTableInputRef)10 RelDataTypeField (org.apache.calcite.rel.type.RelDataTypeField)9