Search in sources :

Example 61 with CorrelationId

use of org.apache.calcite.rel.core.CorrelationId in project calcite by apache.

the class ProjectCorrelateTransposeRule method onMatch.

// ~ Methods ----------------------------------------------------------------
@Override
public void onMatch(RelOptRuleCall call) {
    final Project origProject = call.rel(0);
    final Correlate correlate = call.rel(1);
    // locate all fields referenced in the projection
    // determine which inputs are referenced in the projection;
    // if all fields are being referenced and there are no
    // special expressions, no point in proceeding any further
    final PushProjector pushProjector = new PushProjector(origProject, call.builder().literal(true), correlate, config.preserveExprCondition(), call.builder());
    if (pushProjector.locateAllRefs()) {
        return;
    }
    // create left and right projections, projecting only those
    // fields referenced on each side
    final RelNode leftProject = pushProjector.createProjectRefsAndExprs(correlate.getLeft(), true, false);
    RelNode rightProject = pushProjector.createProjectRefsAndExprs(correlate.getRight(), true, true);
    final Map<Integer, Integer> requiredColsMap = new HashMap<>();
    // adjust requiredColumns that reference the projected columns
    int[] adjustments = pushProjector.getAdjustments();
    BitSet updatedBits = new BitSet();
    for (Integer col : correlate.getRequiredColumns()) {
        int newCol = col + adjustments[col];
        updatedBits.set(newCol);
        requiredColsMap.put(col, newCol);
    }
    final RexBuilder rexBuilder = call.builder().getRexBuilder();
    CorrelationId correlationId = correlate.getCluster().createCorrel();
    RexCorrelVariable rexCorrel = (RexCorrelVariable) rexBuilder.makeCorrel(leftProject.getRowType(), correlationId);
    // updates RexCorrelVariable and sets actual RelDataType for RexFieldAccess
    rightProject = rightProject.accept(new RelNodesExprsHandler(new RexFieldAccessReplacer(correlate.getCorrelationId(), rexCorrel, rexBuilder, requiredColsMap)));
    // create a new correlate with the projected children
    final Correlate newCorrelate = correlate.copy(correlate.getTraitSet(), leftProject, rightProject, correlationId, ImmutableBitSet.of(BitSets.toIter(updatedBits)), correlate.getJoinType());
    // put the original project on top of the correlate, converting it to
    // reference the modified projection list
    final RelNode topProject = pushProjector.createNewProject(newCorrelate, adjustments);
    call.transformTo(topProject);
}
Also used : RexCorrelVariable(org.apache.calcite.rex.RexCorrelVariable) Correlate(org.apache.calcite.rel.core.Correlate) HashMap(java.util.HashMap) ImmutableBitSet(org.apache.calcite.util.ImmutableBitSet) BitSet(java.util.BitSet) Project(org.apache.calcite.rel.core.Project) RelNode(org.apache.calcite.rel.RelNode) RexBuilder(org.apache.calcite.rex.RexBuilder) CorrelationId(org.apache.calcite.rel.core.CorrelationId)

Example 62 with CorrelationId

use of org.apache.calcite.rel.core.CorrelationId in project calcite by apache.

the class RelOptRulesTest method checkProjectCorrelateTransposeRuleSemiOrAntiCorrelate.

private void checkProjectCorrelateTransposeRuleSemiOrAntiCorrelate(JoinRelType type) {
    final Function<RelBuilder, RelNode> relFn = b -> {
        RelNode left = b.values(new String[] { "f", "f2" }, "1", "2").build();
        CorrelationId correlationId = new CorrelationId(0);
        RexNode rexCorrel = b.getRexBuilder().makeCorrel(left.getRowType(), correlationId);
        RelNode right = b.values(new String[] { "f3", "f4" }, "1", "2").project(b.field(0), b.getRexBuilder().makeFieldAccess(rexCorrel, 0)).build();
        LogicalCorrelate correlate = new LogicalCorrelate(left.getCluster(), left.getTraitSet(), ImmutableList.of(), left, right, correlationId, ImmutableBitSet.of(0), type);
        b.push(correlate);
        return b.project(b.field(0)).build();
    };
    relFn(relFn).withRule(CoreRules.PROJECT_CORRELATE_TRANSPOSE).check();
}
Also used : AggregateProjectMergeRule(org.apache.calcite.rel.rules.AggregateProjectMergeRule) Programs(org.apache.calcite.tools.Programs) Arrays(java.util.Arrays) RelDistributions(org.apache.calcite.rel.RelDistributions) DateRangeRules(org.apache.calcite.rel.rules.DateRangeRules) Disabled(org.junit.jupiter.api.Disabled) Contexts(org.apache.calcite.plan.Contexts) Union(org.apache.calcite.rel.core.Union) CorrelationId(org.apache.calcite.rel.core.CorrelationId) EnumSet(java.util.EnumSet) RelTraitSet(org.apache.calcite.plan.RelTraitSet) ReduceExpressionsRule(org.apache.calcite.rel.rules.ReduceExpressionsRule) SqlOperatorBinding(org.apache.calcite.sql.SqlOperatorBinding) ImmutableBitSet(org.apache.calcite.util.ImmutableBitSet) HepMatchOrder(org.apache.calcite.plan.hep.HepMatchOrder) EnumerableSort(org.apache.calcite.adapter.enumerable.EnumerableSort) SqlKind(org.apache.calcite.sql.SqlKind) Minus(org.apache.calcite.rel.core.Minus) RexExecutorImpl(org.apache.calcite.rex.RexExecutorImpl) RelFieldCollation(org.apache.calcite.rel.RelFieldCollation) DataContexts(org.apache.calcite.DataContexts) NL(org.apache.calcite.test.SqlToRelTestBase.NL) HintPredicates(org.apache.calcite.rel.hint.HintPredicates) AggregateProjectConstantToDummyJoinRule(org.apache.calcite.rel.rules.AggregateProjectConstantToDummyJoinRule) RelDataTypeSystemImpl(org.apache.calcite.rel.type.RelDataTypeSystemImpl) SqlStdOperatorTable(org.apache.calcite.sql.fun.SqlStdOperatorTable) RelCollation(org.apache.calcite.rel.RelCollation) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) JoinCommuteRule(org.apache.calcite.rel.rules.JoinCommuteRule) SqlConformanceEnum(org.apache.calcite.sql.validate.SqlConformanceEnum) RuleSet(org.apache.calcite.tools.RuleSet) EnumerableLimitSort(org.apache.calcite.adapter.enumerable.EnumerableLimitSort) AggregateExtractProjectRule(org.apache.calcite.rel.rules.AggregateExtractProjectRule) ProjectToWindowRule(org.apache.calcite.rel.rules.ProjectToWindowRule) RexCall(org.apache.calcite.rex.RexCall) Assertions.fail(org.junit.jupiter.api.Assertions.fail) ProjectFilterTransposeRule(org.apache.calcite.rel.rules.ProjectFilterTransposeRule) ProjectReduceExpressionsRule(org.apache.calcite.rel.rules.ReduceExpressionsRule.ProjectReduceExpressionsRule) Assertions.assertNotNull(org.junit.jupiter.api.Assertions.assertNotNull) AggregateProjectPullUpConstantsRule(org.apache.calcite.rel.rules.AggregateProjectPullUpConstantsRule) AggregateExpandWithinDistinctRule(org.apache.calcite.rel.rules.AggregateExpandWithinDistinctRule) ReturnTypes(org.apache.calcite.sql.type.ReturnTypes) Filter(org.apache.calcite.rel.core.Filter) Join(org.apache.calcite.rel.core.Join) RuleSets(org.apache.calcite.tools.RuleSets) RelDecorrelator(org.apache.calcite.sql2rel.RelDecorrelator) LogicalCorrelate(org.apache.calcite.rel.logical.LogicalCorrelate) JoinAssociateRule(org.apache.calcite.rel.rules.JoinAssociateRule) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) MockCatalogReader(org.apache.calcite.test.catalog.MockCatalogReader) RelDataType(org.apache.calcite.rel.type.RelDataType) FilterProjectTransposeRule(org.apache.calcite.rel.rules.FilterProjectTransposeRule) SpatialRules(org.apache.calcite.rel.rules.SpatialRules) RelRule(org.apache.calcite.plan.RelRule) HepProgramBuilder(org.apache.calcite.plan.hep.HepProgramBuilder) Aggregate(org.apache.calcite.rel.core.Aggregate) LogicalAggregate(org.apache.calcite.rel.logical.LogicalAggregate) SqlFunction(org.apache.calcite.sql.SqlFunction) EnumerableRules(org.apache.calcite.adapter.enumerable.EnumerableRules) JoinRelType(org.apache.calcite.rel.core.JoinRelType) ProjectMultiJoinMergeRule(org.apache.calcite.rel.rules.ProjectMultiJoinMergeRule) RelDataTypeFactory(org.apache.calcite.rel.type.RelDataTypeFactory) LogicalFilter(org.apache.calcite.rel.logical.LogicalFilter) FilterMultiJoinMergeRule(org.apache.calcite.rel.rules.FilterMultiJoinMergeRule) UnionMergeRule(org.apache.calcite.rel.rules.UnionMergeRule) LogicalTableModify(org.apache.calcite.rel.logical.LogicalTableModify) RexUtil(org.apache.calcite.rex.RexUtil) CalciteConnectionConfig(org.apache.calcite.config.CalciteConnectionConfig) FilterFlattenCorrelatedConditionRule(org.apache.calcite.rel.rules.FilterFlattenCorrelatedConditionRule) RexNode(org.apache.calcite.rex.RexNode) RelBuilder(org.apache.calcite.tools.RelBuilder) RelHint(org.apache.calcite.rel.hint.RelHint) Locale(java.util.Locale) Intersect(org.apache.calcite.rel.core.Intersect) HepProgram(org.apache.calcite.plan.hep.HepProgram) SqlTypeFactoryImpl(org.apache.calcite.sql.type.SqlTypeFactoryImpl) RelOptCluster(org.apache.calcite.plan.RelOptCluster) ValuesReduceRule(org.apache.calcite.rel.rules.ValuesReduceRule) Program(org.apache.calcite.tools.Program) Predicate(java.util.function.Predicate) RexLiteral(org.apache.calcite.rex.RexLiteral) DataContext(org.apache.calcite.DataContext) MultiJoin(org.apache.calcite.rel.rules.MultiJoin) CustomCorrelate(org.apache.calcite.test.SqlToRelTestBase.CustomCorrelate) RexInputRef(org.apache.calcite.rex.RexInputRef) Test(org.junit.jupiter.api.Test) List(java.util.List) FilterJoinRule(org.apache.calcite.rel.rules.FilterJoinRule) MockCatalogReaderExtended(org.apache.calcite.test.catalog.MockCatalogReaderExtended) OperandTypes(org.apache.calcite.sql.type.OperandTypes) RelOptPlanner(org.apache.calcite.plan.RelOptPlanner) RelTraitDef(org.apache.calcite.plan.RelTraitDef) SqlSpecialOperator(org.apache.calcite.sql.SqlSpecialOperator) Project(org.apache.calcite.rel.core.Project) RelDistributionTraitDef(org.apache.calcite.rel.RelDistributionTraitDef) RelOptUtil(org.apache.calcite.plan.RelOptUtil) Function(java.util.function.Function) EnumerableConvention(org.apache.calcite.adapter.enumerable.EnumerableConvention) ImmutableList(com.google.common.collect.ImmutableList) Value(org.immutables.value.Value) HintStrategyTable(org.apache.calcite.rel.hint.HintStrategyTable) SqlLibrary(org.apache.calcite.sql.fun.SqlLibrary) SqlOperator(org.apache.calcite.sql.SqlOperator) CoreMatchers.sameInstance(org.hamcrest.CoreMatchers.sameInstance) RelCollations(org.apache.calcite.rel.RelCollations) SqlMonotonicity(org.apache.calcite.sql.validate.SqlMonotonicity) RelCollationTraitDef(org.apache.calcite.rel.RelCollationTraitDef) LogicalProject(org.apache.calcite.rel.logical.LogicalProject) SqlTypeName(org.apache.calcite.sql.type.SqlTypeName) RexBuilder(org.apache.calcite.rex.RexBuilder) SqlFunctionCategory(org.apache.calcite.sql.SqlFunctionCategory) ProjectJoinTransposeRule(org.apache.calcite.rel.rules.ProjectJoinTransposeRule) AggregateReduceFunctionsRule(org.apache.calcite.rel.rules.AggregateReduceFunctionsRule) PushProjector(org.apache.calcite.rel.rules.PushProjector) HepPlanner(org.apache.calcite.plan.hep.HepPlanner) RelNode(org.apache.calcite.rel.RelNode) SqlTestFactory(org.apache.calcite.sql.test.SqlTestFactory) EnumerableLimit(org.apache.calcite.adapter.enumerable.EnumerableLimit) RelOptRuleCall(org.apache.calcite.plan.RelOptRuleCall) CoerceInputsRule(org.apache.calcite.rel.rules.CoerceInputsRule) ProjectCorrelateTransposeRule(org.apache.calcite.rel.rules.ProjectCorrelateTransposeRule) RelOptRule(org.apache.calcite.plan.RelOptRule) CoreRules(org.apache.calcite.rel.rules.CoreRules) Collections(java.util.Collections) PruneEmptyRules(org.apache.calcite.rel.rules.PruneEmptyRules) RelBuilder(org.apache.calcite.tools.RelBuilder) RelNode(org.apache.calcite.rel.RelNode) CorrelationId(org.apache.calcite.rel.core.CorrelationId) LogicalCorrelate(org.apache.calcite.rel.logical.LogicalCorrelate) RexNode(org.apache.calcite.rex.RexNode)

Example 63 with CorrelationId

use of org.apache.calcite.rel.core.CorrelationId in project calcite by apache.

the class RelJson method toRex.

@SuppressWarnings({ "rawtypes", "unchecked" })
@PolyNull
RexNode toRex(RelInput relInput, @PolyNull Object o) {
    final RelOptCluster cluster = relInput.getCluster();
    final RexBuilder rexBuilder = cluster.getRexBuilder();
    if (o == null) {
        return null;
    } else if (o instanceof Map) {
        final Map<String, @Nullable Object> map = (Map) o;
        final RelDataTypeFactory typeFactory = cluster.getTypeFactory();
        if (map.containsKey("op")) {
            final Map<String, @Nullable Object> opMap = get(map, "op");
            if (map.containsKey("class")) {
                opMap.put("class", get(map, "class"));
            }
            final List operands = get(map, "operands");
            final List<RexNode> rexOperands = toRexList(relInput, operands);
            final Object jsonType = map.get("type");
            final Map window = (Map) map.get("window");
            if (window != null) {
                final SqlAggFunction operator = requireNonNull(toAggregation(opMap), "operator");
                final RelDataType type = toType(typeFactory, requireNonNull(jsonType, "jsonType"));
                List<RexNode> partitionKeys = new ArrayList<>();
                Object partition = window.get("partition");
                if (partition != null) {
                    partitionKeys = toRexList(relInput, (List) partition);
                }
                List<RexFieldCollation> orderKeys = new ArrayList<>();
                if (window.containsKey("order")) {
                    addRexFieldCollationList(orderKeys, relInput, (List) window.get("order"));
                }
                final RexWindowBound lowerBound;
                final RexWindowBound upperBound;
                final boolean physical;
                if (window.get("rows-lower") != null) {
                    lowerBound = toRexWindowBound(relInput, (Map) window.get("rows-lower"));
                    upperBound = toRexWindowBound(relInput, (Map) window.get("rows-upper"));
                    physical = true;
                } else if (window.get("range-lower") != null) {
                    lowerBound = toRexWindowBound(relInput, (Map) window.get("range-lower"));
                    upperBound = toRexWindowBound(relInput, (Map) window.get("range-upper"));
                    physical = false;
                } else {
                    // No ROWS or RANGE clause
                    // Note: lower and upper bounds are non-nullable, so this branch is not reachable
                    lowerBound = null;
                    upperBound = null;
                    physical = false;
                }
                final boolean distinct = get((Map<String, Object>) map, "distinct");
                return rexBuilder.makeOver(type, operator, rexOperands, partitionKeys, ImmutableList.copyOf(orderKeys), requireNonNull(lowerBound, "lowerBound"), requireNonNull(upperBound, "upperBound"), physical, true, false, distinct, false);
            } else {
                final SqlOperator operator = requireNonNull(toOp(opMap), "operator");
                final RelDataType type;
                if (jsonType != null) {
                    type = toType(typeFactory, jsonType);
                } else {
                    type = rexBuilder.deriveReturnType(operator, rexOperands);
                }
                return rexBuilder.makeCall(type, operator, rexOperands);
            }
        }
        final Integer input = (Integer) map.get("input");
        if (input != null) {
            return inputTranslator.translateInput(this, input, map, relInput);
        }
        final String field = (String) map.get("field");
        if (field != null) {
            final Object jsonExpr = get(map, "expr");
            final RexNode expr = toRex(relInput, jsonExpr);
            return rexBuilder.makeFieldAccess(expr, field, true);
        }
        final String correl = (String) map.get("correl");
        if (correl != null) {
            final Object jsonType = get(map, "type");
            RelDataType type = toType(typeFactory, jsonType);
            return rexBuilder.makeCorrel(type, new CorrelationId(correl));
        }
        if (map.containsKey("literal")) {
            Object literal = map.get("literal");
            if (literal == null) {
                final RelDataType type = toType(typeFactory, get(map, "type"));
                return rexBuilder.makeNullLiteral(type);
            }
            if (!map.containsKey("type")) {
                // we just interpret the literal
                return toRex(relInput, literal);
            }
            final RelDataType type = toType(typeFactory, get(map, "type"));
            if (type.getSqlTypeName() == SqlTypeName.SYMBOL) {
                literal = RelEnumTypes.toEnum((String) literal);
            }
            return rexBuilder.makeLiteral(literal, type);
        }
        throw new UnsupportedOperationException("cannot convert to rex " + o);
    } else if (o instanceof Boolean) {
        return rexBuilder.makeLiteral((Boolean) o);
    } else if (o instanceof String) {
        return rexBuilder.makeLiteral((String) o);
    } else if (o instanceof Number) {
        final Number number = (Number) o;
        if (number instanceof Double || number instanceof Float) {
            return rexBuilder.makeApproxLiteral(BigDecimal.valueOf(number.doubleValue()));
        } else {
            return rexBuilder.makeExactLiteral(BigDecimal.valueOf(number.longValue()));
        }
    } else {
        throw new UnsupportedOperationException("cannot convert to rex " + o);
    }
}
Also used : RelOptCluster(org.apache.calcite.plan.RelOptCluster) SqlOperator(org.apache.calcite.sql.SqlOperator) RelDataType(org.apache.calcite.rel.type.RelDataType) SqlAggFunction(org.apache.calcite.sql.SqlAggFunction) RelDataTypeFactory(org.apache.calcite.rel.type.RelDataTypeFactory) RexWindowBound(org.apache.calcite.rex.RexWindowBound) RexBuilder(org.apache.calcite.rex.RexBuilder) ImmutableIntList(org.apache.calcite.util.ImmutableIntList) List(java.util.List) ArrayList(java.util.ArrayList) ImmutableList(com.google.common.collect.ImmutableList) CorrelationId(org.apache.calcite.rel.core.CorrelationId) Map(java.util.Map) HashMap(java.util.HashMap) Nullable(org.checkerframework.checker.nullness.qual.Nullable) RexNode(org.apache.calcite.rex.RexNode) PolyNull(org.checkerframework.checker.nullness.qual.PolyNull)

Example 64 with CorrelationId

use of org.apache.calcite.rel.core.CorrelationId in project calcite by apache.

the class SubQueryRemoveRule method matchProject.

private static void matchProject(SubQueryRemoveRule rule, RelOptRuleCall call) {
    final Project project = call.rel(0);
    final RelBuilder builder = call.builder();
    final RexSubQuery e = RexUtil.SubQueryFinder.find(project.getProjects());
    assert e != null;
    final RelOptUtil.Logic logic = LogicVisitor.find(RelOptUtil.Logic.TRUE_FALSE_UNKNOWN, project.getProjects(), e);
    builder.push(project.getInput());
    final int fieldCount = builder.peek().getRowType().getFieldCount();
    final Set<CorrelationId> variablesSet = RelOptUtil.getVariablesUsed(e.rel);
    final RexNode target = rule.apply(e, variablesSet, logic, builder, 1, fieldCount);
    final RexShuttle shuttle = new ReplaceSubQueryShuttle(e, target);
    builder.project(shuttle.apply(project.getProjects()), project.getRowType().getFieldNames());
    call.transformTo(builder.build());
}
Also used : Project(org.apache.calcite.rel.core.Project) RelBuilder(org.apache.calcite.tools.RelBuilder) RexShuttle(org.apache.calcite.rex.RexShuttle) RelOptUtil(org.apache.calcite.plan.RelOptUtil) CorrelationId(org.apache.calcite.rel.core.CorrelationId) RexSubQuery(org.apache.calcite.rex.RexSubQuery) RexNode(org.apache.calcite.rex.RexNode)

Example 65 with CorrelationId

use of org.apache.calcite.rel.core.CorrelationId in project calcite by apache.

the class RexBuilderTest method testCopyCorrelVariable.

/**
 * Tests {@link RexCopier#visitCorrelVariable(RexCorrelVariable)}.
 */
@Test
void testCopyCorrelVariable() {
    final RelDataTypeFactory sourceTypeFactory = new SqlTypeFactoryImpl(RelDataTypeSystem.DEFAULT);
    RelDataType type = sourceTypeFactory.createSqlType(SqlTypeName.VARCHAR, 65536);
    final RelDataTypeFactory targetTypeFactory = new MySqlTypeFactoryImpl(RelDataTypeSystem.DEFAULT);
    final RexBuilder builder = new RexBuilder(targetTypeFactory);
    final RexCorrelVariable node = (RexCorrelVariable) builder.makeCorrel(type, new CorrelationId(0));
    final RexNode copy = builder.copy(node);
    assertTrue(copy instanceof RexCorrelVariable);
    final RexCorrelVariable result = (RexCorrelVariable) copy;
    assertThat(result.id, is(node.id));
    assertThat(result.getType().getSqlTypeName(), is(SqlTypeName.VARCHAR));
    assertThat(result.getType().getPrecision(), is(PRECISION));
}
Also used : SqlTypeFactoryImpl(org.apache.calcite.sql.type.SqlTypeFactoryImpl) RelDataTypeFactory(org.apache.calcite.rel.type.RelDataTypeFactory) RelDataType(org.apache.calcite.rel.type.RelDataType) CorrelationId(org.apache.calcite.rel.core.CorrelationId) Test(org.junit.jupiter.api.Test)

Aggregations

CorrelationId (org.apache.calcite.rel.core.CorrelationId)74 RelNode (org.apache.calcite.rel.RelNode)39 RexNode (org.apache.calcite.rex.RexNode)33 RelDataType (org.apache.calcite.rel.type.RelDataType)25 ArrayList (java.util.ArrayList)22 RelOptCluster (org.apache.calcite.plan.RelOptCluster)19 RexBuilder (org.apache.calcite.rex.RexBuilder)18 RelBuilder (org.apache.calcite.tools.RelBuilder)17 ImmutableBitSet (org.apache.calcite.util.ImmutableBitSet)15 ImmutableList (com.google.common.collect.ImmutableList)12 RelTraitSet (org.apache.calcite.plan.RelTraitSet)12 RexCorrelVariable (org.apache.calcite.rex.RexCorrelVariable)11 RexShuttle (org.apache.calcite.rex.RexShuttle)11 RelDataTypeFactory (org.apache.calcite.rel.type.RelDataTypeFactory)10 RelDataTypeField (org.apache.calcite.rel.type.RelDataTypeField)10 List (java.util.List)9 RelOptUtil (org.apache.calcite.plan.RelOptUtil)9 JoinRelType (org.apache.calcite.rel.core.JoinRelType)9 ByteString (org.apache.calcite.avatica.util.ByteString)7 SqlOperator (org.apache.calcite.sql.SqlOperator)7