You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@ignite.apache.org by GitBox <gi...@apache.org> on 2020/11/13 11:54:15 UTC

[GitHub] [ignite] korlov42 opened a new pull request #8456: IGNITE-13544 Calcite integration. Merge joins

korlov42 opened a new pull request #8456:
URL: https://github.com/apache/ignite/pull/8456


   Thank you for submitting the pull request to the Apache Ignite.
   
   In order to streamline the review of the contribution 
   we ask you to ensure the following steps have been taken:
   
   ### The Contribution Checklist
   - [ ] There is a single JIRA ticket related to the pull request. 
   - [ ] The web-link to the pull request is attached to the JIRA ticket.
   - [ ] The JIRA ticket has the _Patch Available_ state.
   - [ ] The pull request body describes changes that have been made. 
   The description explains _WHAT_ and _WHY_ was made instead of _HOW_.
   - [ ] The pull request title is treated as the final commit message. 
   The following pattern must be used: `IGNITE-XXXX Change summary` where `XXXX` - number of JIRA issue.
   - [ ] A reviewer has been mentioned through the JIRA comments 
   (see [the Maintainers list](https://cwiki.apache.org/confluence/display/IGNITE/How+to+Contribute#HowtoContribute-ReviewProcessandMaintainers)) 
   - [ ] The pull request has been checked by the Teamcity Bot and 
   the `green visa` attached to the JIRA ticket (see [TC.Bot: Check PR](https://mtcga.gridgain.com/prs.html))
   
   ### Notes
   - [How to Contribute](https://cwiki.apache.org/confluence/display/IGNITE/How+to+Contribute)
   - [Coding abbreviation rules](https://cwiki.apache.org/confluence/display/IGNITE/Abbreviation+Rules)
   - [Coding Guidelines](https://cwiki.apache.org/confluence/display/IGNITE/Coding+Guidelines)
   - [Apache Ignite Teamcity Bot](https://cwiki.apache.org/confluence/display/IGNITE/Apache+Ignite+Teamcity+Bot)
   
   If you need any help, please email dev@ignite.apache.org or ask anу advice on http://asf.slack.com _#ignite_ channel.
   


----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [ignite] korlov42 commented on a change in pull request #8456: IGNITE-13544 Calcite integration. Merge joins

Posted by GitBox <gi...@apache.org>.
korlov42 commented on a change in pull request #8456:
URL: https://github.com/apache/ignite/pull/8456#discussion_r530968557



##########
File path: modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/rule/MergeJoinConverterRule.java
##########
@@ -0,0 +1,74 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ignite.internal.processors.query.calcite.rule;
+
+import org.apache.calcite.plan.RelOptCluster;
+import org.apache.calcite.plan.RelOptPlanner;
+import org.apache.calcite.plan.RelOptRule;
+import org.apache.calcite.plan.RelOptRuleCall;
+import org.apache.calcite.plan.RelTraitSet;
+import org.apache.calcite.rel.PhysicalNode;
+import org.apache.calcite.rel.RelCollations;
+import org.apache.calcite.rel.RelNode;
+import org.apache.calcite.rel.core.JoinInfo;
+import org.apache.calcite.rel.logical.LogicalJoin;
+import org.apache.calcite.rel.metadata.RelMetadataQuery;
+import org.apache.ignite.internal.processors.query.calcite.rel.IgniteConvention;
+import org.apache.ignite.internal.processors.query.calcite.rel.IgniteMergeJoin;
+import org.apache.ignite.internal.util.typedef.F;
+
+/**
+ * Ignite Join converter.
+ */
+public class MergeJoinConverterRule extends AbstractIgniteConverterRule<LogicalJoin> {
+    /** */
+    public static final RelOptRule INSTANCE = new MergeJoinConverterRule();
+
+    /**
+     * Creates a converter.
+     */
+    public MergeJoinConverterRule() {
+        super(LogicalJoin.class, "MergeJoinConverterRule");
+    }
+
+    /** {@inheritDoc} */
+    @Override public boolean matches(RelOptRuleCall call) {
+        LogicalJoin logicalJoin = call.rel(0);
+
+        return !F.isEmpty(logicalJoin.analyzeCondition().pairs());

Review comment:
       fixed 




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [ignite] zstan commented on a change in pull request #8456: IGNITE-13544 Calcite integration. Merge joins

Posted by GitBox <gi...@apache.org>.
zstan commented on a change in pull request #8456:
URL: https://github.com/apache/ignite/pull/8456#discussion_r531008305



##########
File path: modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/rel/IgniteMergeJoin.java
##########
@@ -0,0 +1,634 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ignite.internal.processors.query.calcite.rel;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableSet;
+import org.apache.calcite.plan.RelOptCluster;
+import org.apache.calcite.plan.RelOptCost;
+import org.apache.calcite.plan.RelOptPlanner;
+import org.apache.calcite.plan.RelTraitSet;
+import org.apache.calcite.rel.RelCollation;
+import org.apache.calcite.rel.RelCollations;
+import org.apache.calcite.rel.RelDistribution;
+import org.apache.calcite.rel.RelFieldCollation;
+import org.apache.calcite.rel.RelInput;
+import org.apache.calcite.rel.RelNode;
+import org.apache.calcite.rel.RelNodes;
+import org.apache.calcite.rel.RelWriter;
+import org.apache.calcite.rel.core.CorrelationId;
+import org.apache.calcite.rel.core.Join;
+import org.apache.calcite.rel.core.JoinInfo;
+import org.apache.calcite.rel.core.JoinRelType;
+import org.apache.calcite.rel.metadata.RelMdUtil;
+import org.apache.calcite.rel.metadata.RelMetadataQuery;
+import org.apache.calcite.rex.RexNode;
+import org.apache.calcite.sql.SqlExplainLevel;
+import org.apache.calcite.util.ImmutableBitSet;
+import org.apache.calcite.util.ImmutableIntList;
+import org.apache.calcite.util.Pair;
+import org.apache.calcite.util.Util;
+import org.apache.ignite.internal.processors.query.calcite.trait.CorrelationTrait;
+import org.apache.ignite.internal.processors.query.calcite.trait.DistributionFunction;
+import org.apache.ignite.internal.processors.query.calcite.trait.IgniteDistribution;
+import org.apache.ignite.internal.processors.query.calcite.trait.RewindabilityTrait;
+import org.apache.ignite.internal.processors.query.calcite.trait.TraitUtils;
+import org.apache.ignite.internal.processors.query.calcite.trait.TraitsAwareIgniteRel;
+import org.apache.ignite.internal.processors.query.calcite.util.Commons;
+import org.apache.ignite.internal.util.typedef.F;
+import org.jetbrains.annotations.Nullable;
+
+import static org.apache.calcite.rel.RelDistribution.Type.BROADCAST_DISTRIBUTED;
+import static org.apache.calcite.rel.RelDistribution.Type.HASH_DISTRIBUTED;
+import static org.apache.calcite.rel.RelDistribution.Type.SINGLETON;
+import static org.apache.calcite.rel.core.JoinRelType.INNER;
+import static org.apache.calcite.rel.core.JoinRelType.LEFT;
+import static org.apache.calcite.rel.core.JoinRelType.RIGHT;
+import static org.apache.calcite.util.NumberUtil.multiply;
+import static org.apache.ignite.internal.processors.query.calcite.trait.IgniteDistributions.broadcast;
+import static org.apache.ignite.internal.processors.query.calcite.trait.IgniteDistributions.hash;
+import static org.apache.ignite.internal.processors.query.calcite.trait.IgniteDistributions.single;
+
+/** */
+public class IgniteMergeJoin extends Join implements TraitsAwareIgniteRel {
+    /** */
+    public IgniteMergeJoin(RelOptCluster cluster, RelTraitSet traitSet, RelNode left, RelNode right,
+        RexNode condition, Set<CorrelationId> variablesSet, JoinRelType joinType) {
+        super(cluster, traitSet, left, right, condition, variablesSet, joinType);
+    }
+
+    /** */
+    public IgniteMergeJoin(RelInput input) {
+        this(input.getCluster(),
+            input.getTraitSet().replace(IgniteConvention.INSTANCE),
+            input.getInputs().get(0),
+            input.getInputs().get(1),
+            input.getExpression("condition"),
+            ImmutableSet.copyOf(Commons.transform(input.getIntegerList("variablesSet"), CorrelationId::new)),
+            input.getEnum("joinType", JoinRelType.class));
+    }
+
+    /** {@inheritDoc} */
+    @Override public Join copy(RelTraitSet traitSet, RexNode condition, RelNode left, RelNode right,
+        JoinRelType joinType, boolean semiJoinDone) {
+        return new IgniteMergeJoin(getCluster(), traitSet, left, right, condition, variablesSet, joinType);
+    }
+
+    /** {@inheritDoc} */
+    @Override public <T> T accept(IgniteRelVisitor<T> visitor) {
+        return visitor.visit(this);
+    }
+
+    /** {@inheritDoc} */
+    @Override public IgniteRel clone(RelOptCluster cluster, List<IgniteRel> inputs) {
+        return new IgniteMergeJoin(cluster, getTraitSet(), inputs.get(0), inputs.get(1), getCondition(), getVariablesSet(), getJoinType());
+    }
+
+    /** {@inheritDoc} */
+    @Override public RelWriter explainTerms(RelWriter pw) {
+        return super.explainTerms(pw)
+            .itemIf(
+                "variablesSet",
+                Commons.transform(variablesSet.asList(), CorrelationId::getId),
+                pw.getDetailLevel() == SqlExplainLevel.ALL_ATTRIBUTES
+            );
+    }
+
+    /** {@inheritDoc} */
+    @Override public List<Pair<RelTraitSet, List<RelTraitSet>>> deriveCollation(
+        RelTraitSet nodeTraits,
+        List<RelTraitSet> inputTraits
+    ) {
+        RelTraitSet left = inputTraits.get(0), right = inputTraits.get(1);
+        RelCollation leftCollation = TraitUtils.collation(left), rightCollation = TraitUtils.collation(right);
+
+        List<Integer> newLeftCollation, newRightCollation;
+
+        if (isPrefix(leftCollation.getKeys(), joinInfo.leftKeys)) { // preserve left collation
+            newLeftCollation = new ArrayList<>(leftCollation.getKeys());
+
+            Map<Integer, Integer> leftToRight = joinInfo.pairs().stream()
+                .collect(Collectors.toMap(p -> p.source, p -> p.target));
+
+            newRightCollation = newLeftCollation.stream().map(leftToRight::get).collect(Collectors.toList());
+        }
+        else if (isPrefix(rightCollation.getKeys(), joinInfo.rightKeys)) { // preserve right collation
+            newRightCollation = new ArrayList<>(rightCollation.getKeys());
+
+            Map<Integer, Integer> rightToLeft = joinInfo.pairs().stream()
+                .collect(Collectors.toMap(p -> p.target, p -> p.source));
+
+            newLeftCollation = newRightCollation.stream().map(rightToLeft::get).collect(Collectors.toList());
+        }
+        else { // generate new collations
+            // TODO: generate permutations when there will be multitraits
+
+            newLeftCollation = new ArrayList<>(joinInfo.leftKeys);
+            newRightCollation = new ArrayList<>(joinInfo.rightKeys);
+        }
+
+        leftCollation = createCollation(newLeftCollation);
+        rightCollation = createCollation(newRightCollation);
+
+        return ImmutableList.of(
+            Pair.of(
+                nodeTraits.replace(leftCollation),
+                ImmutableList.of(
+                    left.replace(leftCollation),
+                    right.replace(rightCollation)
+                )
+            )
+        );
+    }
+
+    /** {@inheritDoc} */
+    @Override public List<Pair<RelTraitSet, List<RelTraitSet>>> deriveRewindability(
+        RelTraitSet nodeTraits,
+        List<RelTraitSet> inputTraits
+    ) {
+        // The node is rewindable only if both sources are rewindable.
+
+        RelTraitSet left = inputTraits.get(0), right = inputTraits.get(1);
+
+        RewindabilityTrait leftRewindability = TraitUtils.rewindability(left);
+        RewindabilityTrait rightRewindability = TraitUtils.rewindability(right);
+
+        RelTraitSet outTraits, leftTraits, rightTraits;
+
+        if (leftRewindability.rewindable() && rightRewindability.rewindable()) {
+            outTraits = nodeTraits.replace(RewindabilityTrait.REWINDABLE);
+            leftTraits = left.replace(RewindabilityTrait.REWINDABLE);
+            rightTraits = right.replace(RewindabilityTrait.REWINDABLE);
+        }
+        else {
+            outTraits = nodeTraits.replace(RewindabilityTrait.ONE_WAY);
+            leftTraits = left.replace(RewindabilityTrait.ONE_WAY);
+            rightTraits = right.replace(RewindabilityTrait.ONE_WAY);
+        }
+
+        return ImmutableList.of(Pair.of(outTraits, ImmutableList.of(leftTraits, rightTraits)));
+    }
+
+    /** {@inheritDoc} */
+    @Override public List<Pair<RelTraitSet, List<RelTraitSet>>> deriveDistribution(
+        RelTraitSet nodeTraits,
+        List<RelTraitSet> inputTraits
+    ) {
+        // Tere are several rules:
+        // 1) any join is possible on broadcast or single distribution
+        // 2) hash distributed join is possible when join keys equal to source distribution keys
+        // 3) hash and broadcast distributed tables can be joined when join keys equal to hash
+        //    distributed table distribution keys and:
+        //      3.1) it's a left join and a hash distributed table is at left
+        //      3.2) it's a right join and a hash distributed table is at right
+        //      3.3) it's an inner join, this case a hash distributed table may be at any side
+
+        RelTraitSet left = inputTraits.get(0), right = inputTraits.get(1);
+
+        List<Pair<RelTraitSet, List<RelTraitSet>>> res = new ArrayList<>();
+
+        IgniteDistribution leftDistr = TraitUtils.distribution(left);
+        IgniteDistribution rightDistr = TraitUtils.distribution(right);
+
+        RelTraitSet outTraits, leftTraits, rightTraits;
+
+        if (leftDistr == broadcast() || rightDistr == broadcast()) {
+            outTraits = nodeTraits.replace(broadcast());
+            leftTraits = left.replace(broadcast());
+            rightTraits = right.replace(broadcast());
+
+            res.add(Pair.of(outTraits, ImmutableList.of(leftTraits, rightTraits)));
+        }
+
+        if (leftDistr == single() || rightDistr == single()) {
+            outTraits = nodeTraits.replace(single());
+            leftTraits = left.replace(single());
+            rightTraits = right.replace(single());
+
+            res.add(Pair.of(outTraits, ImmutableList.of(leftTraits, rightTraits)));
+        }
+
+        if (!F.isEmpty(joinInfo.pairs())) {
+            Set<DistributionFunction> functions = new HashSet<>();
+
+            if (leftDistr.getType() == HASH_DISTRIBUTED
+                && Objects.equals(joinInfo.leftKeys, leftDistr.getKeys()))
+                functions.add(leftDistr.function());
+
+            if (rightDistr.getType() == HASH_DISTRIBUTED
+                && Objects.equals(joinInfo.rightKeys, rightDistr.getKeys()))
+                functions.add(rightDistr.function());
+
+            functions.add(DistributionFunction.hash());
+
+            for (DistributionFunction function : functions) {
+                leftTraits = left.replace(hash(joinInfo.leftKeys, function));
+                rightTraits = right.replace(hash(joinInfo.rightKeys, function));
+
+                // TODO distribution multitrait support
+                outTraits = nodeTraits.replace(hash(joinInfo.leftKeys, function));
+                res.add(Pair.of(outTraits, ImmutableList.of(leftTraits, rightTraits)));
+
+                outTraits = nodeTraits.replace(hash(joinInfo.rightKeys, function));
+                res.add(Pair.of(outTraits, ImmutableList.of(leftTraits, rightTraits)));
+
+                if (joinType == INNER || joinType == LEFT) {
+                    outTraits = nodeTraits.replace(hash(joinInfo.leftKeys, function));
+                    leftTraits = left.replace(hash(joinInfo.leftKeys, function));
+                    rightTraits = right.replace(broadcast());
+
+                    res.add(Pair.of(outTraits, ImmutableList.of(leftTraits, rightTraits)));
+                }
+
+                if (joinType == INNER || joinType == RIGHT) {
+                    outTraits = nodeTraits.replace(hash(joinInfo.rightKeys, function));
+                    leftTraits = left.replace(broadcast());
+                    rightTraits = right.replace(hash(joinInfo.rightKeys, function));
+
+                    res.add(Pair.of(outTraits, ImmutableList.of(leftTraits, rightTraits)));
+                }
+            }
+        }
+
+        if (!res.isEmpty())
+            return ImmutableList.of();
+
+        return ImmutableList.of(Pair.of(nodeTraits.replace(single()),
+            ImmutableList.of(left.replace(single()), right.replace(single()))));
+    }
+
+    /** {@inheritDoc} */
+    @Override public List<Pair<RelTraitSet, List<RelTraitSet>>> deriveCorrelation(RelTraitSet nodeTraits,
+        List<RelTraitSet> inTraits) {
+        // left correlations
+        Set<CorrelationId> corrIds = new HashSet<>(TraitUtils.correlation(inTraits.get(0)).correlationIds());
+        // right correlations
+        corrIds.addAll(TraitUtils.correlation(inTraits.get(1)).correlationIds());
+
+        return ImmutableList.of(Pair.of(nodeTraits.replace(CorrelationTrait.correlations(corrIds)), inTraits));
+    }
+
+    /** {@inheritDoc} */
+    @Override public List<Pair<RelTraitSet, List<RelTraitSet>>> passThroughCollation(
+        RelTraitSet nodeTraits,
+        List<RelTraitSet> inputTraits
+    ) {
+        RelCollation collation = TraitUtils.collation(nodeTraits);
+        RelTraitSet left = inputTraits.get(0), right = inputTraits.get(1);
+
+        int rightOff = this.left.getRowType().getFieldCount();
+
+        Map<Integer, Integer> rightToLeft = joinInfo.pairs().stream()
+            .collect(Collectors.toMap(p -> p.target, p -> p.source));
+
+        List<Integer> collationLeftPrj = new ArrayList<>();
+
+        for (Integer c : collation.getKeys()) {
+            collationLeftPrj.add(
+                c >= rightOff ? rightToLeft.get(c - rightOff) : c
+            );
+        }
+
+        boolean preserveNodeCollation = false;
+
+        List<Integer> newLeftCollation, newRightCollation;
+
+        Map<Integer, Integer> leftToRight = joinInfo.pairs().stream()
+            .collect(Collectors.toMap(p -> p.source, p -> p.target));
+
+        if (isPrefix(collationLeftPrj, joinInfo.leftKeys)) { // preserve collation
+            newLeftCollation = new ArrayList<>();
+            newRightCollation = new ArrayList<>();
+
+            int ind = 0;
+            for (Integer c : collation.getKeys()) {
+                if (c < rightOff) {
+                    newLeftCollation.add(c);
+
+                    if (ind < joinInfo.leftKeys.size())
+                        newRightCollation.add(leftToRight.get(c));
+                }
+                else {
+                    c -= rightOff;
+                    newRightCollation.add(c);
+
+                    if (ind < joinInfo.leftKeys.size())
+                        newLeftCollation.add(rightToLeft.get(c));
+                }
+
+                ind++;
+            }
+
+            preserveNodeCollation = true;
+        }
+        else { // generate new collations
+            newLeftCollation = maxPrefix(collationLeftPrj, joinInfo.leftKeys);
+
+            Set<Integer> tail = new HashSet<>(joinInfo.leftKeys);
+
+            tail.removeAll(newLeftCollation);
+
+            // TODO: generate permutations when there will be multitraits
+            newLeftCollation.addAll(tail);
+
+            newRightCollation = newLeftCollation.stream().map(leftToRight::get).collect(Collectors.toList());
+        }
+
+        RelCollation leftCollation = createCollation(newLeftCollation);
+        RelCollation rightCollation = createCollation(newRightCollation);
+
+        return ImmutableList.of(
+            Pair.of(
+                nodeTraits.replace(preserveNodeCollation ? collation : leftCollation),
+                ImmutableList.of(
+                    left.replace(leftCollation),
+                    right.replace(rightCollation)
+                )
+            )
+        );
+    }
+
+    /** {@inheritDoc} */
+    @Override public List<Pair<RelTraitSet, List<RelTraitSet>>> passThroughRewindability(
+        RelTraitSet nodeTraits,
+        List<RelTraitSet> inputTraits
+    ) {
+        // The node is rewindable only if both sources are rewindable.
+
+        RelTraitSet left = inputTraits.get(0), right = inputTraits.get(1);
+
+        RewindabilityTrait rewindability = TraitUtils.rewindability(nodeTraits);
+
+        return ImmutableList.of(Pair.of(nodeTraits.replace(rewindability),
+            ImmutableList.of(left.replace(rewindability), right.replace(rewindability))));
+    }
+
+    /** {@inheritDoc} */
+    @Override public List<Pair<RelTraitSet, List<RelTraitSet>>> passThroughDistribution(
+        RelTraitSet nodeTraits,
+        List<RelTraitSet> inputTraits
+    ) {
+        // Tere are several rules:
+        // 1) any join is possible on broadcast or single distribution
+        // 2) hash distributed join is possible when join keys equal to source distribution keys
+        // 3) hash and broadcast distributed tables can be joined when join keys equal to hash
+        //    distributed table distribution keys and:
+        //      3.1) it's a left join and a hash distributed table is at left
+        //      3.2) it's a right join and a hash distributed table is at right
+        //      3.3) it's an inner join, this case a hash distributed table may be at any side
+
+        RelTraitSet left = inputTraits.get(0), right = inputTraits.get(1);
+
+        List<Pair<RelTraitSet, List<RelTraitSet>>> res = new ArrayList<>();
+
+        RelTraitSet outTraits, leftTraits, rightTraits;
+
+        IgniteDistribution distribution = TraitUtils.distribution(nodeTraits);
+
+        RelDistribution.Type distrType = distribution.getType();
+        switch (distrType) {
+            case BROADCAST_DISTRIBUTED:
+            case SINGLETON:
+                outTraits = nodeTraits.replace(distribution);
+                leftTraits = left.replace(distribution);
+                rightTraits = right.replace(distribution);
+
+                res.add(Pair.of(outTraits, ImmutableList.of(leftTraits, rightTraits)));
+
+                break;
+            case HASH_DISTRIBUTED:
+            case RANDOM_DISTRIBUTED:
+                // Such join may be replaced as a cross join with a filter uppon it.
+                // It's impossible to get random or hash distribution from a cross join.
+                if (F.isEmpty(joinInfo.pairs()))
+                    break;
+
+                // We cannot provide random distribution without unique constrain on join keys,
+                // so, we require hash distribution (wich satisfies random distribution) instead.
+                DistributionFunction function = distrType == HASH_DISTRIBUTED
+                    ? distribution.function()
+                    : DistributionFunction.hash();
+
+                IgniteDistribution outDistr; // TODO distribution multitrait support
+
+                outDistr = hash(joinInfo.leftKeys, function);
+
+                if (distrType != HASH_DISTRIBUTED || outDistr.satisfies(distribution)) {
+                    outTraits = nodeTraits.replace(outDistr);
+                    leftTraits = left.replace(hash(joinInfo.leftKeys, function));
+                    rightTraits = right.replace(hash(joinInfo.rightKeys, function));
+
+                    res.add(Pair.of(outTraits, ImmutableList.of(leftTraits, rightTraits)));
+
+                    if (joinType == INNER || joinType == LEFT) {
+                        outTraits = nodeTraits.replace(outDistr);
+                        leftTraits = left.replace(hash(joinInfo.leftKeys, function));
+                        rightTraits = right.replace(broadcast());
+
+                        res.add(Pair.of(outTraits, ImmutableList.of(leftTraits, rightTraits)));
+                    }
+                }
+
+                outDistr = hash(joinInfo.rightKeys, function);
+
+                if (distrType != HASH_DISTRIBUTED || outDistr.satisfies(distribution)) {
+                    outTraits = nodeTraits.replace(outDistr);
+                    leftTraits = left.replace(hash(joinInfo.leftKeys, function));
+                    rightTraits = right.replace(hash(joinInfo.rightKeys, function));
+
+                    res.add(Pair.of(outTraits, ImmutableList.of(leftTraits, rightTraits)));
+
+                    if (joinType == INNER || joinType == RIGHT) {
+                        outTraits = nodeTraits.replace(outDistr);
+                        leftTraits = left.replace(broadcast());
+                        rightTraits = right.replace(hash(joinInfo.rightKeys, function));
+
+                        res.add(Pair.of(outTraits, ImmutableList.of(leftTraits, rightTraits)));
+                    }
+                }
+
+                break;
+
+            default:
+                break;
+        }
+
+        if (!res.isEmpty())
+            return res;
+
+        return ImmutableList.of(Pair.of(nodeTraits.replace(single()),
+            ImmutableList.of(left.replace(single()), right.replace(single()))));
+    }
+
+    /** {@inheritDoc} */
+    @Override public List<Pair<RelTraitSet, List<RelTraitSet>>> passThroughCorrelation(RelTraitSet nodeTraits,
+        List<RelTraitSet> inTraits) {
+        return ImmutableList.of(Pair.of(nodeTraits,
+            ImmutableList.of(
+                inTraits.get(0).replace(TraitUtils.correlation(nodeTraits)),
+                inTraits.get(1).replace(TraitUtils.correlation(nodeTraits))
+            )
+        ));
+    }
+
+    /** {@inheritDoc} */
+    @Override public double estimateRowCount(RelMetadataQuery mq) {
+        @Nullable Double result = null;
+        boolean finished = false;
+        if (!getJoinType().projectsRight()) {
+          // Create a RexNode representing the selectivity of the
+          // semijoin filter and pass it to getSelectivity
+          RexNode semiJoinSelectivity =
+              RelMdUtil.makeSemiJoinSelectivityRexNode(mq, this);
+
+            result = multiply(mq.getSelectivity(getLeft(), semiJoinSelectivity),
+                mq.getRowCount(getLeft()));
+        }
+        else { // Row count estimates of 0 will be rounded up to 1.
+               // So, use maxRowCount where the product is very small.
+            final Double left1 = mq.getRowCount(getLeft());
+            final Double right1 = mq.getRowCount(getRight());
+            if (left1 != null && right1 != null) {
+                if (left1 <= 1D || right1 <= 1D) {
+                    Double max = mq.getMaxRowCount(this);
+                    if (max != null && max <= 1D) {
+                        result = max;
+                        finished = true;
+                    }
+                }
+                if (!finished) {
+                    JoinInfo joinInfo1 = analyzeCondition();
+                    ImmutableIntList leftKeys = joinInfo1.leftKeys;
+                    ImmutableIntList rightKeys = joinInfo1.rightKeys;
+                    double selectivity = mq.getSelectivity(this, getCondition());
+                    if (F.isEmpty(leftKeys) || F.isEmpty(rightKeys)) {
+                        result = left1 * right1 * selectivity;
+                    }
+                    else {
+                        double leftDistinct = Util.first(
+                            mq.getDistinctRowCount(getLeft(), ImmutableBitSet.of(leftKeys), null), left1);
+                        double rightDistinct = Util.first(
+                            mq.getDistinctRowCount(getRight(), ImmutableBitSet.of(rightKeys), null), right1);
+                        double leftCardinality = leftDistinct / left1;
+                        double rightCardinality = rightDistinct / right1;
+                        double rowsCount = (Math.min(left1, right1) / (leftCardinality * rightCardinality)) * selectivity;
+                        JoinRelType type = getJoinType();
+                        if (type == LEFT)
+                            rowsCount += left1;
+                        else if (type == RIGHT)
+                            rowsCount += right1;
+                        else if (type == JoinRelType.FULL)
+                            rowsCount += left1 + right1;
+                        result = rowsCount;
+                    }
+                }
+            }
+        }
+
+        return Util.first(result, 1D);
+    }
+
+    /** {@inheritDoc} */
+    @Override public RelOptCost computeSelfCost(RelOptPlanner planner, RelMetadataQuery mq) {
+        double rowCount = mq.getRowCount(this);
+
+        // Joins can be flipped, and for many algorithms, both versions are viable
+        // and have the same cost. To make the results stable between versions of
+        // the planner, make one of the versions slightly more expensive.
+        switch (joinType) {
+            case SEMI:
+            case ANTI:
+                // SEMI and ANTI join cannot be flipped
+                break;
+            case RIGHT:
+                rowCount = RelMdUtil.addEpsilon(rowCount);
+                break;
+            default:
+                if (RelNodes.COMPARATOR.compare(left, right) > 0)
+                    rowCount = RelMdUtil.addEpsilon(rowCount);
+        }
+
+        final double rightRowCount = right.estimateRowCount(mq);
+        final double leftRowCount = left.estimateRowCount(mq);
+
+        if (Double.isInfinite(leftRowCount))
+            rowCount = leftRowCount;
+        if (Double.isInfinite(rightRowCount))
+            rowCount = rightRowCount;
+
+        RelDistribution.Type type = distribution().getType();
+
+        if (type == BROADCAST_DISTRIBUTED || type == SINGLETON)
+            rowCount = RelMdUtil.addEpsilon(rowCount);
+
+        return planner.getCostFactory().makeCost(rowCount, 0, 0);
+    }
+
+    private static <T> List<T> maxPrefix(List<T> seq, Collection<T> elems) {
+        List<T> res = new ArrayList<>();
+
+        Set<T> elems0 = new HashSet<>(elems);
+
+        for (T e : seq) {
+            if (!elems0.remove(e))
+                break;
+
+            res.add(e);
+        }
+
+        return res;
+    }
+
+    private static <T> boolean isPrefix(List<T> seq, Collection<T> elems) {

Review comment:
       1. no javadoc
   2. strange contract - collection as input and set as inner struct
   3. if you need real prefix comparison of two collections you don`t need additional Set, i hope.




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [ignite] zstan commented on a change in pull request #8456: IGNITE-13544 Calcite integration. Merge joins

Posted by GitBox <gi...@apache.org>.
zstan commented on a change in pull request #8456:
URL: https://github.com/apache/ignite/pull/8456#discussion_r530991984



##########
File path: modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/rel/IgniteMergeJoin.java
##########
@@ -0,0 +1,634 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ignite.internal.processors.query.calcite.rel;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableSet;
+import org.apache.calcite.plan.RelOptCluster;
+import org.apache.calcite.plan.RelOptCost;
+import org.apache.calcite.plan.RelOptPlanner;
+import org.apache.calcite.plan.RelTraitSet;
+import org.apache.calcite.rel.RelCollation;
+import org.apache.calcite.rel.RelCollations;
+import org.apache.calcite.rel.RelDistribution;
+import org.apache.calcite.rel.RelFieldCollation;
+import org.apache.calcite.rel.RelInput;
+import org.apache.calcite.rel.RelNode;
+import org.apache.calcite.rel.RelNodes;
+import org.apache.calcite.rel.RelWriter;
+import org.apache.calcite.rel.core.CorrelationId;
+import org.apache.calcite.rel.core.Join;
+import org.apache.calcite.rel.core.JoinInfo;
+import org.apache.calcite.rel.core.JoinRelType;
+import org.apache.calcite.rel.metadata.RelMdUtil;
+import org.apache.calcite.rel.metadata.RelMetadataQuery;
+import org.apache.calcite.rex.RexNode;
+import org.apache.calcite.sql.SqlExplainLevel;
+import org.apache.calcite.util.ImmutableBitSet;
+import org.apache.calcite.util.ImmutableIntList;
+import org.apache.calcite.util.Pair;
+import org.apache.calcite.util.Util;
+import org.apache.ignite.internal.processors.query.calcite.trait.CorrelationTrait;
+import org.apache.ignite.internal.processors.query.calcite.trait.DistributionFunction;
+import org.apache.ignite.internal.processors.query.calcite.trait.IgniteDistribution;
+import org.apache.ignite.internal.processors.query.calcite.trait.RewindabilityTrait;
+import org.apache.ignite.internal.processors.query.calcite.trait.TraitUtils;
+import org.apache.ignite.internal.processors.query.calcite.trait.TraitsAwareIgniteRel;
+import org.apache.ignite.internal.processors.query.calcite.util.Commons;
+import org.apache.ignite.internal.util.typedef.F;
+import org.jetbrains.annotations.Nullable;
+
+import static org.apache.calcite.rel.RelDistribution.Type.BROADCAST_DISTRIBUTED;
+import static org.apache.calcite.rel.RelDistribution.Type.HASH_DISTRIBUTED;
+import static org.apache.calcite.rel.RelDistribution.Type.SINGLETON;
+import static org.apache.calcite.rel.core.JoinRelType.INNER;
+import static org.apache.calcite.rel.core.JoinRelType.LEFT;
+import static org.apache.calcite.rel.core.JoinRelType.RIGHT;
+import static org.apache.calcite.util.NumberUtil.multiply;
+import static org.apache.ignite.internal.processors.query.calcite.trait.IgniteDistributions.broadcast;
+import static org.apache.ignite.internal.processors.query.calcite.trait.IgniteDistributions.hash;
+import static org.apache.ignite.internal.processors.query.calcite.trait.IgniteDistributions.single;
+
+/** */
+public class IgniteMergeJoin extends Join implements TraitsAwareIgniteRel {
+    /** */
+    public IgniteMergeJoin(RelOptCluster cluster, RelTraitSet traitSet, RelNode left, RelNode right,
+        RexNode condition, Set<CorrelationId> variablesSet, JoinRelType joinType) {
+        super(cluster, traitSet, left, right, condition, variablesSet, joinType);

Review comment:
       why do you use deprecated constructor here?




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [ignite] korlov42 commented on a change in pull request #8456: IGNITE-13544 Calcite integration. Merge joins

Posted by GitBox <gi...@apache.org>.
korlov42 commented on a change in pull request #8456:
URL: https://github.com/apache/ignite/pull/8456#discussion_r531491843



##########
File path: modules/calcite/src/test/java/org/apache/ignite/internal/processors/query/calcite/exec/rel/ExecutionTest.java
##########
@@ -980,6 +980,71 @@ public void testCorrelatedNestedLoopJoin() {
         }
     }
 
+    /** */
+    @Test
+    public void testMergeJoin() {
+        ExecutionContext<Object[]> ctx = executionContext(F.first(nodes()), UUID.randomUUID(), 0);
+        IgniteTypeFactory tf = ctx.getTypeFactory();
+        RelDataType rowType = TypeUtils.createRowType(tf, int.class, String.class, int.class);
+
+        int[] leftSizes = {1, 99, 100, 101, 512, 513, 2000};

Review comment:
       fixed

##########
File path: modules/calcite/src/test/java/org/apache/ignite/internal/processors/query/calcite/PlannerTest.java
##########
@@ -2656,6 +2659,221 @@ public void testJoinPushExpressionRule() throws Exception {
         }
     }
 
+    /** */
+    @Test
+    public void testMergeJoin() throws Exception {
+        IgniteTypeFactory f = new IgniteTypeFactory(IgniteTypeSystem.INSTANCE);
+
+        TestTable emp = new TestTable(
+            new RelDataTypeFactory.Builder(f)
+                .add("ID", f.createJavaType(Integer.class))
+                .add("NAME", f.createJavaType(String.class))
+                .add("DEPTNO", f.createJavaType(Integer.class))
+                .build()) {
+
+            @Override public IgniteDistribution distribution() {
+                return IgniteDistributions.broadcast();
+            }
+        };
+
+        emp.addIndex(new IgniteIndex(RelCollations.of(ImmutableIntList.of(1, 2)), "emp_idx", null, emp));
+
+        TestTable dept = new TestTable(
+            new RelDataTypeFactory.Builder(f)
+                .add("DEPTNO", f.createJavaType(Integer.class))
+                .add("NAME", f.createJavaType(String.class))
+                .build()) {
+
+            @Override public IgniteDistribution distribution() {
+                return IgniteDistributions.broadcast();
+            }
+        };
+
+        dept.addIndex(new IgniteIndex(RelCollations.of(ImmutableIntList.of(1, 0)), "dep_idx", null, dept));
+
+        IgniteSchema publicSchema = new IgniteSchema("PUBLIC");
+
+        publicSchema.addTable("EMP", emp);
+        publicSchema.addTable("DEPT", dept);
+
+        SchemaPlus schema = createRootSchema(false)
+            .add("PUBLIC", publicSchema);
+
+        String sql = "select * from dept d join emp e on d.deptno = e.deptno and e.name = d.name order by e.name, d.deptno";
+
+        RelTraitDef<?>[] traitDefs = {
+            DistributionTraitDef.INSTANCE,
+            ConventionTraitDef.INSTANCE,
+            RelCollationTraitDef.INSTANCE,
+            RewindabilityTraitDef.INSTANCE,
+            CorrelationTraitDef.INSTANCE
+        };
+
+        PlanningContext ctx = PlanningContext.builder()
+            .localNodeId(F.first(nodes))
+            .originatingNodeId(F.first(nodes))
+            .parentContext(Contexts.empty())
+            .frameworkConfig(newConfigBuilder(FRAMEWORK_CONFIG)
+                .defaultSchema(schema)
+                .traitDefs(traitDefs)
+                .build())
+            .logger(log)
+            .query(sql)
+            .topologyVersion(AffinityTopologyVersion.NONE)
+            .build();
+
+        try (IgnitePlanner planner = ctx.planner()) {
+            assertNotNull(planner);
+
+            String qry = ctx.query();
+
+            assertNotNull(qry);
+
+            // Parse
+            SqlNode sqlNode = planner.parse(qry);
+
+            // Validate
+            sqlNode = planner.validate(sqlNode);
+
+            // Convert to Relational operators graph
+            RelRoot relRoot = planner.rel(sqlNode);
+
+            RelNode rel = relRoot.rel;
+
+            assertNotNull(rel);
+            assertEquals("" +
+                    "LogicalSort(sort0=[$3], sort1=[$0], dir0=[ASC], dir1=[ASC])\n" +
+                    "  LogicalProject(DEPTNO=[$0], NAME=[$1], ID=[$2], NAME0=[$3], DEPTNO0=[$4])\n" +
+                    "    LogicalJoin(condition=[AND(=($0, $4), =($3, $1))], joinType=[inner])\n" +
+                    "      IgniteLogicalTableScan(table=[[PUBLIC, DEPT]])\n" +
+                    "      IgniteLogicalTableScan(table=[[PUBLIC, EMP]])\n",
+                RelOptUtil.toString(rel));
+
+            // Transformation chain
+            RelTraitSet desired = rel.getTraitSet()
+                .replace(IgniteConvention.INSTANCE)
+                .replace(IgniteDistributions.single())
+                .simplify();
+
+            RelNode phys = planner.transform(PlannerPhase.OPTIMIZATION, desired, rel);
+
+            assertNotNull(phys);
+            assertEquals("" +
+                    "IgniteMergeJoin(condition=[AND(=($0, $4), =($3, $1))], joinType=[inner])\n" +
+                    "  IgniteIndexScan(table=[[PUBLIC, DEPT]], index=[dep_idx])\n" +
+                    "  IgniteIndexScan(table=[[PUBLIC, EMP]], index=[emp_idx])\n",
+                RelOptUtil.toString(phys));
+        }
+    }
+
+    /** */
+    @Test
+    public void testMergeJoinIsNotAppliedForNonEquiJoin() throws Exception {
+        IgniteTypeFactory f = new IgniteTypeFactory(IgniteTypeSystem.INSTANCE);
+
+        TestTable emp = new TestTable(
+            new RelDataTypeFactory.Builder(f)
+                .add("ID", f.createJavaType(Integer.class))
+                .add("NAME", f.createJavaType(String.class))
+                .add("DEPTNO", f.createJavaType(Integer.class))
+                .build()) {
+
+            @Override public IgniteDistribution distribution() {
+                return IgniteDistributions.broadcast();

Review comment:
       fixed




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [ignite] korlov42 commented on a change in pull request #8456: IGNITE-13544 Calcite integration. Merge joins

Posted by GitBox <gi...@apache.org>.
korlov42 commented on a change in pull request #8456:
URL: https://github.com/apache/ignite/pull/8456#discussion_r530889879



##########
File path: modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/metadata/IgniteMdRowCount.java
##########
@@ -47,6 +48,63 @@
         return joinRowCount(mq, rel);
     }
 
+    /** */
+    public Double getRowCount(IgniteCorrelatedNestedLoopJoin rel, RelMetadataQuery mq) {
+        if (!rel.getJoinType().projectsRight()) {
+            // Create a RexNode representing the selectivity of the
+            // semijoin filter and pass it to getSelectivity
+            RexNode semiJoinSelectivity =
+                RelMdUtil.makeSemiJoinSelectivityRexNode(mq, rel);
+
+            return multiply(mq.getSelectivity(rel.getLeft(), semiJoinSelectivity),
+                mq.getRowCount(rel.getLeft()));
+        }
+
+        // Row count estimates of 0 will be rounded up to 1.
+        // So, use maxRowCount where the product is very small.
+        final Double left = mq.getRowCount(rel.getLeft());
+        final Double right = mq.getRowCount(rel.getRight());
+
+        if (left == null || right == null)
+            return null;
+
+        if (left <= 1D || right <= 1D) {

Review comment:
       it is 1D (one of type Double). To be honest I don't sure we need a constant for this




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [ignite] zstan commented on a change in pull request #8456: IGNITE-13544 Calcite integration. Merge joins

Posted by GitBox <gi...@apache.org>.
zstan commented on a change in pull request #8456:
URL: https://github.com/apache/ignite/pull/8456#discussion_r525324104



##########
File path: modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/rule/MergeJoinConverterRule.java
##########
@@ -0,0 +1,74 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ignite.internal.processors.query.calcite.rule;
+
+import org.apache.calcite.plan.RelOptCluster;
+import org.apache.calcite.plan.RelOptPlanner;
+import org.apache.calcite.plan.RelOptRule;
+import org.apache.calcite.plan.RelOptRuleCall;
+import org.apache.calcite.plan.RelTraitSet;
+import org.apache.calcite.rel.PhysicalNode;
+import org.apache.calcite.rel.RelCollations;
+import org.apache.calcite.rel.RelNode;
+import org.apache.calcite.rel.core.JoinInfo;
+import org.apache.calcite.rel.logical.LogicalJoin;
+import org.apache.calcite.rel.metadata.RelMetadataQuery;
+import org.apache.ignite.internal.processors.query.calcite.rel.IgniteConvention;
+import org.apache.ignite.internal.processors.query.calcite.rel.IgniteMergeJoin;
+import org.apache.ignite.internal.util.typedef.F;
+
+/**
+ * Ignite Join converter.
+ */
+public class MergeJoinConverterRule extends AbstractIgniteConverterRule<LogicalJoin> {
+    /** */
+    public static final RelOptRule INSTANCE = new MergeJoinConverterRule();
+
+    /**
+     * Creates a converter.
+     */
+    public MergeJoinConverterRule() {
+        super(LogicalJoin.class, "MergeJoinConverterRule");
+    }
+
+    /** {@inheritDoc} */
+    @Override public boolean matches(RelOptRuleCall call) {
+        LogicalJoin logicalJoin = call.rel(0);
+
+        return !F.isEmpty(logicalJoin.analyzeCondition().pairs());

Review comment:
       i also don`t know about JoinRelType#SEMI and JoinRelType#ANTI here, also we need to cover all these join types, i hope ... 




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [ignite] korlov42 commented on a change in pull request #8456: IGNITE-13544 Calcite integration. Merge joins

Posted by GitBox <gi...@apache.org>.
korlov42 commented on a change in pull request #8456:
URL: https://github.com/apache/ignite/pull/8456#discussion_r531492533



##########
File path: modules/calcite/src/test/java/org/apache/ignite/internal/processors/query/calcite/PlannerTest.java
##########
@@ -2656,6 +2659,221 @@ public void testJoinPushExpressionRule() throws Exception {
         }
     }
 
+    /** */
+    @Test
+    public void testMergeJoin() throws Exception {
+        IgniteTypeFactory f = new IgniteTypeFactory(IgniteTypeSystem.INSTANCE);
+
+        TestTable emp = new TestTable(
+            new RelDataTypeFactory.Builder(f)
+                .add("ID", f.createJavaType(Integer.class))
+                .add("NAME", f.createJavaType(String.class))
+                .add("DEPTNO", f.createJavaType(Integer.class))
+                .build()) {
+
+            @Override public IgniteDistribution distribution() {
+                return IgniteDistributions.broadcast();
+            }
+        };
+
+        emp.addIndex(new IgniteIndex(RelCollations.of(ImmutableIntList.of(1, 2)), "emp_idx", null, emp));
+
+        TestTable dept = new TestTable(
+            new RelDataTypeFactory.Builder(f)
+                .add("DEPTNO", f.createJavaType(Integer.class))
+                .add("NAME", f.createJavaType(String.class))
+                .build()) {
+
+            @Override public IgniteDistribution distribution() {
+                return IgniteDistributions.broadcast();
+            }
+        };
+
+        dept.addIndex(new IgniteIndex(RelCollations.of(ImmutableIntList.of(1, 0)), "dep_idx", null, dept));
+
+        IgniteSchema publicSchema = new IgniteSchema("PUBLIC");
+
+        publicSchema.addTable("EMP", emp);
+        publicSchema.addTable("DEPT", dept);
+
+        SchemaPlus schema = createRootSchema(false)
+            .add("PUBLIC", publicSchema);
+
+        String sql = "select * from dept d join emp e on d.deptno = e.deptno and e.name = d.name order by e.name, d.deptno";
+
+        RelTraitDef<?>[] traitDefs = {
+            DistributionTraitDef.INSTANCE,
+            ConventionTraitDef.INSTANCE,
+            RelCollationTraitDef.INSTANCE,
+            RewindabilityTraitDef.INSTANCE,
+            CorrelationTraitDef.INSTANCE
+        };
+
+        PlanningContext ctx = PlanningContext.builder()
+            .localNodeId(F.first(nodes))
+            .originatingNodeId(F.first(nodes))
+            .parentContext(Contexts.empty())
+            .frameworkConfig(newConfigBuilder(FRAMEWORK_CONFIG)
+                .defaultSchema(schema)
+                .traitDefs(traitDefs)
+                .build())
+            .logger(log)
+            .query(sql)
+            .topologyVersion(AffinityTopologyVersion.NONE)
+            .build();
+
+        try (IgnitePlanner planner = ctx.planner()) {
+            assertNotNull(planner);
+
+            String qry = ctx.query();
+
+            assertNotNull(qry);
+
+            // Parse
+            SqlNode sqlNode = planner.parse(qry);
+
+            // Validate
+            sqlNode = planner.validate(sqlNode);
+
+            // Convert to Relational operators graph
+            RelRoot relRoot = planner.rel(sqlNode);
+
+            RelNode rel = relRoot.rel;
+
+            assertNotNull(rel);
+            assertEquals("" +
+                    "LogicalSort(sort0=[$3], sort1=[$0], dir0=[ASC], dir1=[ASC])\n" +
+                    "  LogicalProject(DEPTNO=[$0], NAME=[$1], ID=[$2], NAME0=[$3], DEPTNO0=[$4])\n" +
+                    "    LogicalJoin(condition=[AND(=($0, $4), =($3, $1))], joinType=[inner])\n" +
+                    "      IgniteLogicalTableScan(table=[[PUBLIC, DEPT]])\n" +
+                    "      IgniteLogicalTableScan(table=[[PUBLIC, EMP]])\n",
+                RelOptUtil.toString(rel));
+
+            // Transformation chain
+            RelTraitSet desired = rel.getTraitSet()
+                .replace(IgniteConvention.INSTANCE)
+                .replace(IgniteDistributions.single())
+                .simplify();
+
+            RelNode phys = planner.transform(PlannerPhase.OPTIMIZATION, desired, rel);
+
+            assertNotNull(phys);
+            assertEquals("" +
+                    "IgniteMergeJoin(condition=[AND(=($0, $4), =($3, $1))], joinType=[inner])\n" +
+                    "  IgniteIndexScan(table=[[PUBLIC, DEPT]], index=[dep_idx])\n" +
+                    "  IgniteIndexScan(table=[[PUBLIC, EMP]], index=[emp_idx])\n",
+                RelOptUtil.toString(phys));
+        }
+    }
+
+    /** */
+    @Test
+    public void testMergeJoinIsNotAppliedForNonEquiJoin() throws Exception {
+        IgniteTypeFactory f = new IgniteTypeFactory(IgniteTypeSystem.INSTANCE);
+
+        TestTable emp = new TestTable(
+            new RelDataTypeFactory.Builder(f)
+                .add("ID", f.createJavaType(Integer.class))
+                .add("NAME", f.createJavaType(String.class))
+                .add("DEPTNO", f.createJavaType(Integer.class))
+                .build()) {
+
+            @Override public IgniteDistribution distribution() {
+                return IgniteDistributions.broadcast();
+            }
+        };
+
+        emp.addIndex(new IgniteIndex(RelCollations.of(ImmutableIntList.of(1, 2)), "emp_idx", null, emp));
+
+        TestTable dept = new TestTable(
+            new RelDataTypeFactory.Builder(f)
+                .add("DEPTNO", f.createJavaType(Integer.class))
+                .add("NAME", f.createJavaType(String.class))
+                .build()) {
+
+            @Override public IgniteDistribution distribution() {
+                return IgniteDistributions.broadcast();
+            }
+        };
+
+        dept.addIndex(new IgniteIndex(RelCollations.of(ImmutableIntList.of(1, 0)), "dep_idx", null, dept));
+
+        IgniteSchema publicSchema = new IgniteSchema("PUBLIC");
+
+        publicSchema.addTable("EMP", emp);
+        publicSchema.addTable("DEPT", dept);
+
+        SchemaPlus schema = createRootSchema(false)
+            .add("PUBLIC", publicSchema);
+
+        String sql = "select * from dept d join emp e on d.deptno = e.deptno and e.name >= d.name order by e.name, d.deptno";
+
+        RelTraitDef<?>[] traitDefs = {
+            DistributionTraitDef.INSTANCE,
+            ConventionTraitDef.INSTANCE,
+            RelCollationTraitDef.INSTANCE,
+            RewindabilityTraitDef.INSTANCE,
+            CorrelationTraitDef.INSTANCE
+        };
+
+        PlanningContext ctx = PlanningContext.builder()

Review comment:
       fixed




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [ignite] zstan commented on a change in pull request #8456: IGNITE-13544 Calcite integration. Merge joins

Posted by GitBox <gi...@apache.org>.
zstan commented on a change in pull request #8456:
URL: https://github.com/apache/ignite/pull/8456#discussion_r532376106



##########
File path: modules/calcite/src/test/java/org/apache/ignite/internal/processors/query/calcite/PlannerTest.java
##########
@@ -2656,6 +2659,221 @@ public void testJoinPushExpressionRule() throws Exception {
         }
     }
 
+    /** */
+    @Test
+    public void testMergeJoin() throws Exception {
+        IgniteTypeFactory f = new IgniteTypeFactory(IgniteTypeSystem.INSTANCE);
+
+        TestTable emp = new TestTable(
+            new RelDataTypeFactory.Builder(f)
+                .add("ID", f.createJavaType(Integer.class))
+                .add("NAME", f.createJavaType(String.class))
+                .add("DEPTNO", f.createJavaType(Integer.class))
+                .build()) {
+
+            @Override public IgniteDistribution distribution() {
+                return IgniteDistributions.broadcast();
+            }
+        };
+
+        emp.addIndex(new IgniteIndex(RelCollations.of(ImmutableIntList.of(1, 2)), "emp_idx", null, emp));
+
+        TestTable dept = new TestTable(
+            new RelDataTypeFactory.Builder(f)
+                .add("DEPTNO", f.createJavaType(Integer.class))
+                .add("NAME", f.createJavaType(String.class))
+                .build()) {
+
+            @Override public IgniteDistribution distribution() {
+                return IgniteDistributions.broadcast();
+            }
+        };
+
+        dept.addIndex(new IgniteIndex(RelCollations.of(ImmutableIntList.of(1, 0)), "dep_idx", null, dept));
+
+        IgniteSchema publicSchema = new IgniteSchema("PUBLIC");
+
+        publicSchema.addTable("EMP", emp);
+        publicSchema.addTable("DEPT", dept);
+
+        SchemaPlus schema = createRootSchema(false)
+            .add("PUBLIC", publicSchema);
+
+        String sql = "select * from dept d join emp e on d.deptno = e.deptno and e.name = d.name order by e.name, d.deptno";
+
+        RelTraitDef<?>[] traitDefs = {
+            DistributionTraitDef.INSTANCE,
+            ConventionTraitDef.INSTANCE,
+            RelCollationTraitDef.INSTANCE,
+            RewindabilityTraitDef.INSTANCE,
+            CorrelationTraitDef.INSTANCE
+        };
+
+        PlanningContext ctx = PlanningContext.builder()
+            .localNodeId(F.first(nodes))
+            .originatingNodeId(F.first(nodes))
+            .parentContext(Contexts.empty())
+            .frameworkConfig(newConfigBuilder(FRAMEWORK_CONFIG)
+                .defaultSchema(schema)
+                .traitDefs(traitDefs)
+                .build())
+            .logger(log)
+            .query(sql)
+            .topologyVersion(AffinityTopologyVersion.NONE)
+            .build();
+
+        try (IgnitePlanner planner = ctx.planner()) {
+            assertNotNull(planner);
+
+            String qry = ctx.query();
+
+            assertNotNull(qry);
+
+            // Parse
+            SqlNode sqlNode = planner.parse(qry);
+
+            // Validate
+            sqlNode = planner.validate(sqlNode);
+
+            // Convert to Relational operators graph
+            RelRoot relRoot = planner.rel(sqlNode);
+
+            RelNode rel = relRoot.rel;
+
+            assertNotNull(rel);
+            assertEquals("" +
+                    "LogicalSort(sort0=[$3], sort1=[$0], dir0=[ASC], dir1=[ASC])\n" +
+                    "  LogicalProject(DEPTNO=[$0], NAME=[$1], ID=[$2], NAME0=[$3], DEPTNO0=[$4])\n" +
+                    "    LogicalJoin(condition=[AND(=($0, $4), =($3, $1))], joinType=[inner])\n" +
+                    "      IgniteLogicalTableScan(table=[[PUBLIC, DEPT]])\n" +
+                    "      IgniteLogicalTableScan(table=[[PUBLIC, EMP]])\n",
+                RelOptUtil.toString(rel));
+
+            // Transformation chain
+            RelTraitSet desired = rel.getTraitSet()
+                .replace(IgniteConvention.INSTANCE)
+                .replace(IgniteDistributions.single())
+                .simplify();
+
+            RelNode phys = planner.transform(PlannerPhase.OPTIMIZATION, desired, rel);
+
+            assertNotNull(phys);
+            assertEquals("" +
+                    "IgniteMergeJoin(condition=[AND(=($0, $4), =($3, $1))], joinType=[inner])\n" +
+                    "  IgniteIndexScan(table=[[PUBLIC, DEPT]], index=[dep_idx])\n" +
+                    "  IgniteIndexScan(table=[[PUBLIC, EMP]], index=[emp_idx])\n",
+                RelOptUtil.toString(phys));
+        }
+    }
+
+    /** */
+    @Test
+    public void testMergeJoinIsNotAppliedForNonEquiJoin() throws Exception {
+        IgniteTypeFactory f = new IgniteTypeFactory(IgniteTypeSystem.INSTANCE);
+
+        TestTable emp = new TestTable(
+            new RelDataTypeFactory.Builder(f)
+                .add("ID", f.createJavaType(Integer.class))
+                .add("NAME", f.createJavaType(String.class))
+                .add("DEPTNO", f.createJavaType(Integer.class))
+                .build()) {
+
+            @Override public IgniteDistribution distribution() {
+                return IgniteDistributions.broadcast();

Review comment:
       ok, you are right.




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [ignite] zstan commented on a change in pull request #8456: IGNITE-13544 Calcite integration. Merge joins

Posted by GitBox <gi...@apache.org>.
zstan commented on a change in pull request #8456:
URL: https://github.com/apache/ignite/pull/8456#discussion_r531395804



##########
File path: modules/calcite/src/test/java/org/apache/ignite/internal/processors/query/calcite/PlannerTest.java
##########
@@ -2656,6 +2659,221 @@ public void testJoinPushExpressionRule() throws Exception {
         }
     }
 
+    /** */
+    @Test
+    public void testMergeJoin() throws Exception {
+        IgniteTypeFactory f = new IgniteTypeFactory(IgniteTypeSystem.INSTANCE);
+
+        TestTable emp = new TestTable(
+            new RelDataTypeFactory.Builder(f)
+                .add("ID", f.createJavaType(Integer.class))
+                .add("NAME", f.createJavaType(String.class))
+                .add("DEPTNO", f.createJavaType(Integer.class))
+                .build()) {
+
+            @Override public IgniteDistribution distribution() {
+                return IgniteDistributions.broadcast();
+            }
+        };
+
+        emp.addIndex(new IgniteIndex(RelCollations.of(ImmutableIntList.of(1, 2)), "emp_idx", null, emp));
+
+        TestTable dept = new TestTable(
+            new RelDataTypeFactory.Builder(f)
+                .add("DEPTNO", f.createJavaType(Integer.class))
+                .add("NAME", f.createJavaType(String.class))
+                .build()) {
+
+            @Override public IgniteDistribution distribution() {
+                return IgniteDistributions.broadcast();
+            }
+        };
+
+        dept.addIndex(new IgniteIndex(RelCollations.of(ImmutableIntList.of(1, 0)), "dep_idx", null, dept));
+
+        IgniteSchema publicSchema = new IgniteSchema("PUBLIC");
+
+        publicSchema.addTable("EMP", emp);
+        publicSchema.addTable("DEPT", dept);
+
+        SchemaPlus schema = createRootSchema(false)
+            .add("PUBLIC", publicSchema);
+
+        String sql = "select * from dept d join emp e on d.deptno = e.deptno and e.name = d.name order by e.name, d.deptno";
+
+        RelTraitDef<?>[] traitDefs = {
+            DistributionTraitDef.INSTANCE,
+            ConventionTraitDef.INSTANCE,
+            RelCollationTraitDef.INSTANCE,
+            RewindabilityTraitDef.INSTANCE,
+            CorrelationTraitDef.INSTANCE
+        };
+
+        PlanningContext ctx = PlanningContext.builder()
+            .localNodeId(F.first(nodes))
+            .originatingNodeId(F.first(nodes))
+            .parentContext(Contexts.empty())
+            .frameworkConfig(newConfigBuilder(FRAMEWORK_CONFIG)
+                .defaultSchema(schema)
+                .traitDefs(traitDefs)
+                .build())
+            .logger(log)
+            .query(sql)
+            .topologyVersion(AffinityTopologyVersion.NONE)
+            .build();
+
+        try (IgnitePlanner planner = ctx.planner()) {
+            assertNotNull(planner);
+
+            String qry = ctx.query();
+
+            assertNotNull(qry);
+
+            // Parse
+            SqlNode sqlNode = planner.parse(qry);
+
+            // Validate
+            sqlNode = planner.validate(sqlNode);
+
+            // Convert to Relational operators graph
+            RelRoot relRoot = planner.rel(sqlNode);
+
+            RelNode rel = relRoot.rel;
+
+            assertNotNull(rel);
+            assertEquals("" +
+                    "LogicalSort(sort0=[$3], sort1=[$0], dir0=[ASC], dir1=[ASC])\n" +
+                    "  LogicalProject(DEPTNO=[$0], NAME=[$1], ID=[$2], NAME0=[$3], DEPTNO0=[$4])\n" +
+                    "    LogicalJoin(condition=[AND(=($0, $4), =($3, $1))], joinType=[inner])\n" +
+                    "      IgniteLogicalTableScan(table=[[PUBLIC, DEPT]])\n" +
+                    "      IgniteLogicalTableScan(table=[[PUBLIC, EMP]])\n",
+                RelOptUtil.toString(rel));
+
+            // Transformation chain
+            RelTraitSet desired = rel.getTraitSet()
+                .replace(IgniteConvention.INSTANCE)
+                .replace(IgniteDistributions.single())
+                .simplify();
+
+            RelNode phys = planner.transform(PlannerPhase.OPTIMIZATION, desired, rel);
+
+            assertNotNull(phys);
+            assertEquals("" +
+                    "IgniteMergeJoin(condition=[AND(=($0, $4), =($3, $1))], joinType=[inner])\n" +
+                    "  IgniteIndexScan(table=[[PUBLIC, DEPT]], index=[dep_idx])\n" +
+                    "  IgniteIndexScan(table=[[PUBLIC, EMP]], index=[emp_idx])\n",
+                RelOptUtil.toString(phys));
+        }
+    }
+
+    /** */
+    @Test
+    public void testMergeJoinIsNotAppliedForNonEquiJoin() throws Exception {
+        IgniteTypeFactory f = new IgniteTypeFactory(IgniteTypeSystem.INSTANCE);
+
+        TestTable emp = new TestTable(
+            new RelDataTypeFactory.Builder(f)
+                .add("ID", f.createJavaType(Integer.class))
+                .add("NAME", f.createJavaType(String.class))
+                .add("DEPTNO", f.createJavaType(Integer.class))
+                .build()) {
+
+            @Override public IgniteDistribution distribution() {
+                return IgniteDistributions.broadcast();
+            }
+        };
+
+        emp.addIndex(new IgniteIndex(RelCollations.of(ImmutableIntList.of(1, 2)), "emp_idx", null, emp));
+
+        TestTable dept = new TestTable(
+            new RelDataTypeFactory.Builder(f)
+                .add("DEPTNO", f.createJavaType(Integer.class))
+                .add("NAME", f.createJavaType(String.class))
+                .build()) {
+
+            @Override public IgniteDistribution distribution() {
+                return IgniteDistributions.broadcast();
+            }
+        };
+
+        dept.addIndex(new IgniteIndex(RelCollations.of(ImmutableIntList.of(1, 0)), "dep_idx", null, dept));
+
+        IgniteSchema publicSchema = new IgniteSchema("PUBLIC");
+
+        publicSchema.addTable("EMP", emp);
+        publicSchema.addTable("DEPT", dept);
+
+        SchemaPlus schema = createRootSchema(false)
+            .add("PUBLIC", publicSchema);
+
+        String sql = "select * from dept d join emp e on d.deptno = e.deptno and e.name >= d.name order by e.name, d.deptno";
+
+        RelTraitDef<?>[] traitDefs = {
+            DistributionTraitDef.INSTANCE,
+            ConventionTraitDef.INSTANCE,
+            RelCollationTraitDef.INSTANCE,
+            RewindabilityTraitDef.INSTANCE,
+            CorrelationTraitDef.INSTANCE
+        };
+
+        PlanningContext ctx = PlanningContext.builder()

Review comment:
       plz replace this huge code stuff with more compact one, like : RelNode phys = physicalPlan(sql, publicSchema);
   examples of usage near and upper in this class.




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [ignite] korlov42 commented on a change in pull request #8456: IGNITE-13544 Calcite integration. Merge joins

Posted by GitBox <gi...@apache.org>.
korlov42 commented on a change in pull request #8456:
URL: https://github.com/apache/ignite/pull/8456#discussion_r531083915



##########
File path: modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/rel/IgniteMergeJoin.java
##########
@@ -0,0 +1,634 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ignite.internal.processors.query.calcite.rel;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableSet;
+import org.apache.calcite.plan.RelOptCluster;
+import org.apache.calcite.plan.RelOptCost;
+import org.apache.calcite.plan.RelOptPlanner;
+import org.apache.calcite.plan.RelTraitSet;
+import org.apache.calcite.rel.RelCollation;
+import org.apache.calcite.rel.RelCollations;
+import org.apache.calcite.rel.RelDistribution;
+import org.apache.calcite.rel.RelFieldCollation;
+import org.apache.calcite.rel.RelInput;
+import org.apache.calcite.rel.RelNode;
+import org.apache.calcite.rel.RelNodes;
+import org.apache.calcite.rel.RelWriter;
+import org.apache.calcite.rel.core.CorrelationId;
+import org.apache.calcite.rel.core.Join;
+import org.apache.calcite.rel.core.JoinInfo;
+import org.apache.calcite.rel.core.JoinRelType;
+import org.apache.calcite.rel.metadata.RelMdUtil;
+import org.apache.calcite.rel.metadata.RelMetadataQuery;
+import org.apache.calcite.rex.RexNode;
+import org.apache.calcite.sql.SqlExplainLevel;
+import org.apache.calcite.util.ImmutableBitSet;
+import org.apache.calcite.util.ImmutableIntList;
+import org.apache.calcite.util.Pair;
+import org.apache.calcite.util.Util;
+import org.apache.ignite.internal.processors.query.calcite.trait.CorrelationTrait;
+import org.apache.ignite.internal.processors.query.calcite.trait.DistributionFunction;
+import org.apache.ignite.internal.processors.query.calcite.trait.IgniteDistribution;
+import org.apache.ignite.internal.processors.query.calcite.trait.RewindabilityTrait;
+import org.apache.ignite.internal.processors.query.calcite.trait.TraitUtils;
+import org.apache.ignite.internal.processors.query.calcite.trait.TraitsAwareIgniteRel;
+import org.apache.ignite.internal.processors.query.calcite.util.Commons;
+import org.apache.ignite.internal.util.typedef.F;
+import org.jetbrains.annotations.Nullable;
+
+import static org.apache.calcite.rel.RelDistribution.Type.BROADCAST_DISTRIBUTED;
+import static org.apache.calcite.rel.RelDistribution.Type.HASH_DISTRIBUTED;
+import static org.apache.calcite.rel.RelDistribution.Type.SINGLETON;
+import static org.apache.calcite.rel.core.JoinRelType.INNER;
+import static org.apache.calcite.rel.core.JoinRelType.LEFT;
+import static org.apache.calcite.rel.core.JoinRelType.RIGHT;
+import static org.apache.calcite.util.NumberUtil.multiply;
+import static org.apache.ignite.internal.processors.query.calcite.trait.IgniteDistributions.broadcast;
+import static org.apache.ignite.internal.processors.query.calcite.trait.IgniteDistributions.hash;
+import static org.apache.ignite.internal.processors.query.calcite.trait.IgniteDistributions.single;
+
+/** */
+public class IgniteMergeJoin extends Join implements TraitsAwareIgniteRel {
+    /** */
+    public IgniteMergeJoin(RelOptCluster cluster, RelTraitSet traitSet, RelNode left, RelNode right,
+        RexNode condition, Set<CorrelationId> variablesSet, JoinRelType joinType) {
+        super(cluster, traitSet, left, right, condition, variablesSet, joinType);
+    }
+
+    /** */
+    public IgniteMergeJoin(RelInput input) {
+        this(input.getCluster(),
+            input.getTraitSet().replace(IgniteConvention.INSTANCE),
+            input.getInputs().get(0),
+            input.getInputs().get(1),
+            input.getExpression("condition"),
+            ImmutableSet.copyOf(Commons.transform(input.getIntegerList("variablesSet"), CorrelationId::new)),
+            input.getEnum("joinType", JoinRelType.class));
+    }
+
+    /** {@inheritDoc} */
+    @Override public Join copy(RelTraitSet traitSet, RexNode condition, RelNode left, RelNode right,
+        JoinRelType joinType, boolean semiJoinDone) {
+        return new IgniteMergeJoin(getCluster(), traitSet, left, right, condition, variablesSet, joinType);
+    }
+
+    /** {@inheritDoc} */
+    @Override public <T> T accept(IgniteRelVisitor<T> visitor) {
+        return visitor.visit(this);
+    }
+
+    /** {@inheritDoc} */
+    @Override public IgniteRel clone(RelOptCluster cluster, List<IgniteRel> inputs) {
+        return new IgniteMergeJoin(cluster, getTraitSet(), inputs.get(0), inputs.get(1), getCondition(), getVariablesSet(), getJoinType());
+    }
+
+    /** {@inheritDoc} */
+    @Override public RelWriter explainTerms(RelWriter pw) {
+        return super.explainTerms(pw)
+            .itemIf(
+                "variablesSet",
+                Commons.transform(variablesSet.asList(), CorrelationId::getId),
+                pw.getDetailLevel() == SqlExplainLevel.ALL_ATTRIBUTES
+            );
+    }
+
+    /** {@inheritDoc} */
+    @Override public List<Pair<RelTraitSet, List<RelTraitSet>>> deriveCollation(
+        RelTraitSet nodeTraits,
+        List<RelTraitSet> inputTraits
+    ) {
+        RelTraitSet left = inputTraits.get(0), right = inputTraits.get(1);
+        RelCollation leftCollation = TraitUtils.collation(left), rightCollation = TraitUtils.collation(right);
+
+        List<Integer> newLeftCollation, newRightCollation;
+
+        if (isPrefix(leftCollation.getKeys(), joinInfo.leftKeys)) { // preserve left collation
+            newLeftCollation = new ArrayList<>(leftCollation.getKeys());
+
+            Map<Integer, Integer> leftToRight = joinInfo.pairs().stream()
+                .collect(Collectors.toMap(p -> p.source, p -> p.target));
+
+            newRightCollation = newLeftCollation.stream().map(leftToRight::get).collect(Collectors.toList());
+        }
+        else if (isPrefix(rightCollation.getKeys(), joinInfo.rightKeys)) { // preserve right collation
+            newRightCollation = new ArrayList<>(rightCollation.getKeys());
+
+            Map<Integer, Integer> rightToLeft = joinInfo.pairs().stream()
+                .collect(Collectors.toMap(p -> p.target, p -> p.source));
+
+            newLeftCollation = newRightCollation.stream().map(rightToLeft::get).collect(Collectors.toList());
+        }
+        else { // generate new collations
+            // TODO: generate permutations when there will be multitraits
+
+            newLeftCollation = new ArrayList<>(joinInfo.leftKeys);
+            newRightCollation = new ArrayList<>(joinInfo.rightKeys);
+        }
+
+        leftCollation = createCollation(newLeftCollation);
+        rightCollation = createCollation(newRightCollation);
+
+        return ImmutableList.of(
+            Pair.of(
+                nodeTraits.replace(leftCollation),
+                ImmutableList.of(
+                    left.replace(leftCollation),
+                    right.replace(rightCollation)
+                )
+            )
+        );
+    }
+
+    /** {@inheritDoc} */
+    @Override public List<Pair<RelTraitSet, List<RelTraitSet>>> deriveRewindability(
+        RelTraitSet nodeTraits,
+        List<RelTraitSet> inputTraits
+    ) {
+        // The node is rewindable only if both sources are rewindable.
+
+        RelTraitSet left = inputTraits.get(0), right = inputTraits.get(1);
+
+        RewindabilityTrait leftRewindability = TraitUtils.rewindability(left);
+        RewindabilityTrait rightRewindability = TraitUtils.rewindability(right);
+
+        RelTraitSet outTraits, leftTraits, rightTraits;
+
+        if (leftRewindability.rewindable() && rightRewindability.rewindable()) {
+            outTraits = nodeTraits.replace(RewindabilityTrait.REWINDABLE);
+            leftTraits = left.replace(RewindabilityTrait.REWINDABLE);
+            rightTraits = right.replace(RewindabilityTrait.REWINDABLE);
+        }
+        else {
+            outTraits = nodeTraits.replace(RewindabilityTrait.ONE_WAY);
+            leftTraits = left.replace(RewindabilityTrait.ONE_WAY);
+            rightTraits = right.replace(RewindabilityTrait.ONE_WAY);
+        }
+
+        return ImmutableList.of(Pair.of(outTraits, ImmutableList.of(leftTraits, rightTraits)));
+    }
+
+    /** {@inheritDoc} */
+    @Override public List<Pair<RelTraitSet, List<RelTraitSet>>> deriveDistribution(
+        RelTraitSet nodeTraits,
+        List<RelTraitSet> inputTraits
+    ) {
+        // Tere are several rules:
+        // 1) any join is possible on broadcast or single distribution
+        // 2) hash distributed join is possible when join keys equal to source distribution keys
+        // 3) hash and broadcast distributed tables can be joined when join keys equal to hash
+        //    distributed table distribution keys and:
+        //      3.1) it's a left join and a hash distributed table is at left
+        //      3.2) it's a right join and a hash distributed table is at right
+        //      3.3) it's an inner join, this case a hash distributed table may be at any side
+
+        RelTraitSet left = inputTraits.get(0), right = inputTraits.get(1);
+
+        List<Pair<RelTraitSet, List<RelTraitSet>>> res = new ArrayList<>();
+
+        IgniteDistribution leftDistr = TraitUtils.distribution(left);
+        IgniteDistribution rightDistr = TraitUtils.distribution(right);
+
+        RelTraitSet outTraits, leftTraits, rightTraits;
+
+        if (leftDistr == broadcast() || rightDistr == broadcast()) {
+            outTraits = nodeTraits.replace(broadcast());
+            leftTraits = left.replace(broadcast());
+            rightTraits = right.replace(broadcast());
+
+            res.add(Pair.of(outTraits, ImmutableList.of(leftTraits, rightTraits)));
+        }
+
+        if (leftDistr == single() || rightDistr == single()) {
+            outTraits = nodeTraits.replace(single());
+            leftTraits = left.replace(single());
+            rightTraits = right.replace(single());
+
+            res.add(Pair.of(outTraits, ImmutableList.of(leftTraits, rightTraits)));
+        }
+
+        if (!F.isEmpty(joinInfo.pairs())) {
+            Set<DistributionFunction> functions = new HashSet<>();
+
+            if (leftDistr.getType() == HASH_DISTRIBUTED
+                && Objects.equals(joinInfo.leftKeys, leftDistr.getKeys()))
+                functions.add(leftDistr.function());
+
+            if (rightDistr.getType() == HASH_DISTRIBUTED
+                && Objects.equals(joinInfo.rightKeys, rightDistr.getKeys()))
+                functions.add(rightDistr.function());
+
+            functions.add(DistributionFunction.hash());
+
+            for (DistributionFunction function : functions) {
+                leftTraits = left.replace(hash(joinInfo.leftKeys, function));
+                rightTraits = right.replace(hash(joinInfo.rightKeys, function));
+
+                // TODO distribution multitrait support
+                outTraits = nodeTraits.replace(hash(joinInfo.leftKeys, function));
+                res.add(Pair.of(outTraits, ImmutableList.of(leftTraits, rightTraits)));
+
+                outTraits = nodeTraits.replace(hash(joinInfo.rightKeys, function));
+                res.add(Pair.of(outTraits, ImmutableList.of(leftTraits, rightTraits)));
+
+                if (joinType == INNER || joinType == LEFT) {
+                    outTraits = nodeTraits.replace(hash(joinInfo.leftKeys, function));
+                    leftTraits = left.replace(hash(joinInfo.leftKeys, function));
+                    rightTraits = right.replace(broadcast());
+
+                    res.add(Pair.of(outTraits, ImmutableList.of(leftTraits, rightTraits)));
+                }
+
+                if (joinType == INNER || joinType == RIGHT) {
+                    outTraits = nodeTraits.replace(hash(joinInfo.rightKeys, function));
+                    leftTraits = left.replace(broadcast());
+                    rightTraits = right.replace(hash(joinInfo.rightKeys, function));
+
+                    res.add(Pair.of(outTraits, ImmutableList.of(leftTraits, rightTraits)));
+                }
+            }
+        }
+
+        if (!res.isEmpty())
+            return ImmutableList.of();
+
+        return ImmutableList.of(Pair.of(nodeTraits.replace(single()),
+            ImmutableList.of(left.replace(single()), right.replace(single()))));
+    }
+
+    /** {@inheritDoc} */
+    @Override public List<Pair<RelTraitSet, List<RelTraitSet>>> deriveCorrelation(RelTraitSet nodeTraits,
+        List<RelTraitSet> inTraits) {
+        // left correlations
+        Set<CorrelationId> corrIds = new HashSet<>(TraitUtils.correlation(inTraits.get(0)).correlationIds());
+        // right correlations
+        corrIds.addAll(TraitUtils.correlation(inTraits.get(1)).correlationIds());
+
+        return ImmutableList.of(Pair.of(nodeTraits.replace(CorrelationTrait.correlations(corrIds)), inTraits));
+    }
+
+    /** {@inheritDoc} */
+    @Override public List<Pair<RelTraitSet, List<RelTraitSet>>> passThroughCollation(
+        RelTraitSet nodeTraits,
+        List<RelTraitSet> inputTraits
+    ) {
+        RelCollation collation = TraitUtils.collation(nodeTraits);
+        RelTraitSet left = inputTraits.get(0), right = inputTraits.get(1);
+
+        int rightOff = this.left.getRowType().getFieldCount();
+
+        Map<Integer, Integer> rightToLeft = joinInfo.pairs().stream()
+            .collect(Collectors.toMap(p -> p.target, p -> p.source));
+
+        List<Integer> collationLeftPrj = new ArrayList<>();
+
+        for (Integer c : collation.getKeys()) {
+            collationLeftPrj.add(
+                c >= rightOff ? rightToLeft.get(c - rightOff) : c
+            );
+        }
+
+        boolean preserveNodeCollation = false;
+
+        List<Integer> newLeftCollation, newRightCollation;
+
+        Map<Integer, Integer> leftToRight = joinInfo.pairs().stream()
+            .collect(Collectors.toMap(p -> p.source, p -> p.target));
+
+        if (isPrefix(collationLeftPrj, joinInfo.leftKeys)) { // preserve collation
+            newLeftCollation = new ArrayList<>();
+            newRightCollation = new ArrayList<>();
+
+            int ind = 0;
+            for (Integer c : collation.getKeys()) {
+                if (c < rightOff) {
+                    newLeftCollation.add(c);
+
+                    if (ind < joinInfo.leftKeys.size())
+                        newRightCollation.add(leftToRight.get(c));
+                }
+                else {
+                    c -= rightOff;
+                    newRightCollation.add(c);
+
+                    if (ind < joinInfo.leftKeys.size())
+                        newLeftCollation.add(rightToLeft.get(c));
+                }
+
+                ind++;
+            }
+
+            preserveNodeCollation = true;
+        }
+        else { // generate new collations
+            newLeftCollation = maxPrefix(collationLeftPrj, joinInfo.leftKeys);
+
+            Set<Integer> tail = new HashSet<>(joinInfo.leftKeys);
+
+            tail.removeAll(newLeftCollation);
+
+            // TODO: generate permutations when there will be multitraits
+            newLeftCollation.addAll(tail);
+
+            newRightCollation = newLeftCollation.stream().map(leftToRight::get).collect(Collectors.toList());
+        }
+
+        RelCollation leftCollation = createCollation(newLeftCollation);
+        RelCollation rightCollation = createCollation(newRightCollation);
+
+        return ImmutableList.of(
+            Pair.of(
+                nodeTraits.replace(preserveNodeCollation ? collation : leftCollation),
+                ImmutableList.of(
+                    left.replace(leftCollation),
+                    right.replace(rightCollation)
+                )
+            )
+        );
+    }
+
+    /** {@inheritDoc} */
+    @Override public List<Pair<RelTraitSet, List<RelTraitSet>>> passThroughRewindability(
+        RelTraitSet nodeTraits,
+        List<RelTraitSet> inputTraits
+    ) {
+        // The node is rewindable only if both sources are rewindable.
+
+        RelTraitSet left = inputTraits.get(0), right = inputTraits.get(1);
+
+        RewindabilityTrait rewindability = TraitUtils.rewindability(nodeTraits);
+
+        return ImmutableList.of(Pair.of(nodeTraits.replace(rewindability),
+            ImmutableList.of(left.replace(rewindability), right.replace(rewindability))));
+    }
+
+    /** {@inheritDoc} */
+    @Override public List<Pair<RelTraitSet, List<RelTraitSet>>> passThroughDistribution(
+        RelTraitSet nodeTraits,
+        List<RelTraitSet> inputTraits
+    ) {
+        // Tere are several rules:
+        // 1) any join is possible on broadcast or single distribution
+        // 2) hash distributed join is possible when join keys equal to source distribution keys
+        // 3) hash and broadcast distributed tables can be joined when join keys equal to hash
+        //    distributed table distribution keys and:
+        //      3.1) it's a left join and a hash distributed table is at left
+        //      3.2) it's a right join and a hash distributed table is at right
+        //      3.3) it's an inner join, this case a hash distributed table may be at any side
+
+        RelTraitSet left = inputTraits.get(0), right = inputTraits.get(1);
+
+        List<Pair<RelTraitSet, List<RelTraitSet>>> res = new ArrayList<>();
+
+        RelTraitSet outTraits, leftTraits, rightTraits;
+
+        IgniteDistribution distribution = TraitUtils.distribution(nodeTraits);
+
+        RelDistribution.Type distrType = distribution.getType();
+        switch (distrType) {
+            case BROADCAST_DISTRIBUTED:
+            case SINGLETON:
+                outTraits = nodeTraits.replace(distribution);
+                leftTraits = left.replace(distribution);
+                rightTraits = right.replace(distribution);
+
+                res.add(Pair.of(outTraits, ImmutableList.of(leftTraits, rightTraits)));
+
+                break;
+            case HASH_DISTRIBUTED:
+            case RANDOM_DISTRIBUTED:
+                // Such join may be replaced as a cross join with a filter uppon it.
+                // It's impossible to get random or hash distribution from a cross join.
+                if (F.isEmpty(joinInfo.pairs()))
+                    break;
+
+                // We cannot provide random distribution without unique constrain on join keys,
+                // so, we require hash distribution (wich satisfies random distribution) instead.
+                DistributionFunction function = distrType == HASH_DISTRIBUTED
+                    ? distribution.function()
+                    : DistributionFunction.hash();
+
+                IgniteDistribution outDistr; // TODO distribution multitrait support
+
+                outDistr = hash(joinInfo.leftKeys, function);
+
+                if (distrType != HASH_DISTRIBUTED || outDistr.satisfies(distribution)) {
+                    outTraits = nodeTraits.replace(outDistr);
+                    leftTraits = left.replace(hash(joinInfo.leftKeys, function));
+                    rightTraits = right.replace(hash(joinInfo.rightKeys, function));
+
+                    res.add(Pair.of(outTraits, ImmutableList.of(leftTraits, rightTraits)));
+
+                    if (joinType == INNER || joinType == LEFT) {
+                        outTraits = nodeTraits.replace(outDistr);
+                        leftTraits = left.replace(hash(joinInfo.leftKeys, function));
+                        rightTraits = right.replace(broadcast());
+
+                        res.add(Pair.of(outTraits, ImmutableList.of(leftTraits, rightTraits)));
+                    }
+                }
+
+                outDistr = hash(joinInfo.rightKeys, function);
+
+                if (distrType != HASH_DISTRIBUTED || outDistr.satisfies(distribution)) {
+                    outTraits = nodeTraits.replace(outDistr);
+                    leftTraits = left.replace(hash(joinInfo.leftKeys, function));
+                    rightTraits = right.replace(hash(joinInfo.rightKeys, function));
+
+                    res.add(Pair.of(outTraits, ImmutableList.of(leftTraits, rightTraits)));
+
+                    if (joinType == INNER || joinType == RIGHT) {
+                        outTraits = nodeTraits.replace(outDistr);
+                        leftTraits = left.replace(broadcast());
+                        rightTraits = right.replace(hash(joinInfo.rightKeys, function));
+
+                        res.add(Pair.of(outTraits, ImmutableList.of(leftTraits, rightTraits)));
+                    }
+                }
+
+                break;
+
+            default:
+                break;
+        }
+
+        if (!res.isEmpty())
+            return res;
+
+        return ImmutableList.of(Pair.of(nodeTraits.replace(single()),
+            ImmutableList.of(left.replace(single()), right.replace(single()))));
+    }
+
+    /** {@inheritDoc} */
+    @Override public List<Pair<RelTraitSet, List<RelTraitSet>>> passThroughCorrelation(RelTraitSet nodeTraits,
+        List<RelTraitSet> inTraits) {
+        return ImmutableList.of(Pair.of(nodeTraits,
+            ImmutableList.of(
+                inTraits.get(0).replace(TraitUtils.correlation(nodeTraits)),
+                inTraits.get(1).replace(TraitUtils.correlation(nodeTraits))
+            )
+        ));
+    }
+
+    /** {@inheritDoc} */
+    @Override public double estimateRowCount(RelMetadataQuery mq) {
+        @Nullable Double result = null;
+        boolean finished = false;
+        if (!getJoinType().projectsRight()) {
+          // Create a RexNode representing the selectivity of the
+          // semijoin filter and pass it to getSelectivity
+          RexNode semiJoinSelectivity =
+              RelMdUtil.makeSemiJoinSelectivityRexNode(mq, this);
+
+            result = multiply(mq.getSelectivity(getLeft(), semiJoinSelectivity),
+                mq.getRowCount(getLeft()));
+        }
+        else { // Row count estimates of 0 will be rounded up to 1.
+               // So, use maxRowCount where the product is very small.
+            final Double left1 = mq.getRowCount(getLeft());
+            final Double right1 = mq.getRowCount(getRight());
+            if (left1 != null && right1 != null) {
+                if (left1 <= 1D || right1 <= 1D) {
+                    Double max = mq.getMaxRowCount(this);
+                    if (max != null && max <= 1D) {
+                        result = max;
+                        finished = true;
+                    }
+                }
+                if (!finished) {
+                    JoinInfo joinInfo1 = analyzeCondition();
+                    ImmutableIntList leftKeys = joinInfo1.leftKeys;
+                    ImmutableIntList rightKeys = joinInfo1.rightKeys;
+                    double selectivity = mq.getSelectivity(this, getCondition());
+                    if (F.isEmpty(leftKeys) || F.isEmpty(rightKeys)) {
+                        result = left1 * right1 * selectivity;
+                    }
+                    else {
+                        double leftDistinct = Util.first(
+                            mq.getDistinctRowCount(getLeft(), ImmutableBitSet.of(leftKeys), null), left1);
+                        double rightDistinct = Util.first(
+                            mq.getDistinctRowCount(getRight(), ImmutableBitSet.of(rightKeys), null), right1);
+                        double leftCardinality = leftDistinct / left1;
+                        double rightCardinality = rightDistinct / right1;
+                        double rowsCount = (Math.min(left1, right1) / (leftCardinality * rightCardinality)) * selectivity;
+                        JoinRelType type = getJoinType();
+                        if (type == LEFT)
+                            rowsCount += left1;
+                        else if (type == RIGHT)
+                            rowsCount += right1;
+                        else if (type == JoinRelType.FULL)
+                            rowsCount += left1 + right1;
+                        result = rowsCount;
+                    }
+                }
+            }
+        }
+
+        return Util.first(result, 1D);
+    }
+
+    /** {@inheritDoc} */
+    @Override public RelOptCost computeSelfCost(RelOptPlanner planner, RelMetadataQuery mq) {
+        double rowCount = mq.getRowCount(this);
+
+        // Joins can be flipped, and for many algorithms, both versions are viable
+        // and have the same cost. To make the results stable between versions of
+        // the planner, make one of the versions slightly more expensive.
+        switch (joinType) {
+            case SEMI:
+            case ANTI:
+                // SEMI and ANTI join cannot be flipped
+                break;
+            case RIGHT:
+                rowCount = RelMdUtil.addEpsilon(rowCount);
+                break;
+            default:
+                if (RelNodes.COMPARATOR.compare(left, right) > 0)
+                    rowCount = RelMdUtil.addEpsilon(rowCount);
+        }
+
+        final double rightRowCount = right.estimateRowCount(mq);
+        final double leftRowCount = left.estimateRowCount(mq);
+
+        if (Double.isInfinite(leftRowCount))
+            rowCount = leftRowCount;
+        if (Double.isInfinite(rightRowCount))
+            rowCount = rightRowCount;
+
+        RelDistribution.Type type = distribution().getType();
+
+        if (type == BROADCAST_DISTRIBUTED || type == SINGLETON)
+            rowCount = RelMdUtil.addEpsilon(rowCount);
+
+        return planner.getCostFactory().makeCost(rowCount, 0, 0);
+    }
+
+    private static <T> List<T> maxPrefix(List<T> seq, Collection<T> elems) {
+        List<T> res = new ArrayList<>();
+
+        Set<T> elems0 = new HashSet<>(elems);
+
+        for (T e : seq) {
+            if (!elems0.remove(e))
+                break;
+
+            res.add(e);
+        }
+
+        return res;
+    }
+
+    private static <T> boolean isPrefix(List<T> seq, Collection<T> elems) {

Review comment:
       I add the javadoc. Hope it helps to get the idea of the method




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [ignite] zstan commented on a change in pull request #8456: IGNITE-13544 Calcite integration. Merge joins

Posted by GitBox <gi...@apache.org>.
zstan commented on a change in pull request #8456:
URL: https://github.com/apache/ignite/pull/8456#discussion_r531400336



##########
File path: modules/calcite/src/test/java/org/apache/ignite/internal/processors/query/calcite/PlannerTest.java
##########
@@ -2656,6 +2659,221 @@ public void testJoinPushExpressionRule() throws Exception {
         }
     }
 
+    /** */
+    @Test
+    public void testMergeJoin() throws Exception {
+        IgniteTypeFactory f = new IgniteTypeFactory(IgniteTypeSystem.INSTANCE);
+
+        TestTable emp = new TestTable(
+            new RelDataTypeFactory.Builder(f)
+                .add("ID", f.createJavaType(Integer.class))
+                .add("NAME", f.createJavaType(String.class))
+                .add("DEPTNO", f.createJavaType(Integer.class))
+                .build()) {
+
+            @Override public IgniteDistribution distribution() {
+                return IgniteDistributions.broadcast();
+            }
+        };
+
+        emp.addIndex(new IgniteIndex(RelCollations.of(ImmutableIntList.of(1, 2)), "emp_idx", null, emp));
+
+        TestTable dept = new TestTable(
+            new RelDataTypeFactory.Builder(f)
+                .add("DEPTNO", f.createJavaType(Integer.class))
+                .add("NAME", f.createJavaType(String.class))
+                .build()) {
+
+            @Override public IgniteDistribution distribution() {
+                return IgniteDistributions.broadcast();
+            }
+        };
+
+        dept.addIndex(new IgniteIndex(RelCollations.of(ImmutableIntList.of(1, 0)), "dep_idx", null, dept));
+
+        IgniteSchema publicSchema = new IgniteSchema("PUBLIC");
+
+        publicSchema.addTable("EMP", emp);
+        publicSchema.addTable("DEPT", dept);
+
+        SchemaPlus schema = createRootSchema(false)
+            .add("PUBLIC", publicSchema);
+
+        String sql = "select * from dept d join emp e on d.deptno = e.deptno and e.name = d.name order by e.name, d.deptno";
+
+        RelTraitDef<?>[] traitDefs = {
+            DistributionTraitDef.INSTANCE,
+            ConventionTraitDef.INSTANCE,
+            RelCollationTraitDef.INSTANCE,
+            RewindabilityTraitDef.INSTANCE,
+            CorrelationTraitDef.INSTANCE
+        };
+
+        PlanningContext ctx = PlanningContext.builder()
+            .localNodeId(F.first(nodes))
+            .originatingNodeId(F.first(nodes))
+            .parentContext(Contexts.empty())
+            .frameworkConfig(newConfigBuilder(FRAMEWORK_CONFIG)
+                .defaultSchema(schema)
+                .traitDefs(traitDefs)
+                .build())
+            .logger(log)
+            .query(sql)
+            .topologyVersion(AffinityTopologyVersion.NONE)
+            .build();
+
+        try (IgnitePlanner planner = ctx.planner()) {
+            assertNotNull(planner);
+
+            String qry = ctx.query();
+
+            assertNotNull(qry);
+
+            // Parse
+            SqlNode sqlNode = planner.parse(qry);
+
+            // Validate
+            sqlNode = planner.validate(sqlNode);
+
+            // Convert to Relational operators graph
+            RelRoot relRoot = planner.rel(sqlNode);
+
+            RelNode rel = relRoot.rel;
+
+            assertNotNull(rel);
+            assertEquals("" +
+                    "LogicalSort(sort0=[$3], sort1=[$0], dir0=[ASC], dir1=[ASC])\n" +
+                    "  LogicalProject(DEPTNO=[$0], NAME=[$1], ID=[$2], NAME0=[$3], DEPTNO0=[$4])\n" +
+                    "    LogicalJoin(condition=[AND(=($0, $4), =($3, $1))], joinType=[inner])\n" +
+                    "      IgniteLogicalTableScan(table=[[PUBLIC, DEPT]])\n" +
+                    "      IgniteLogicalTableScan(table=[[PUBLIC, EMP]])\n",
+                RelOptUtil.toString(rel));
+
+            // Transformation chain
+            RelTraitSet desired = rel.getTraitSet()
+                .replace(IgniteConvention.INSTANCE)
+                .replace(IgniteDistributions.single())
+                .simplify();
+
+            RelNode phys = planner.transform(PlannerPhase.OPTIMIZATION, desired, rel);
+
+            assertNotNull(phys);
+            assertEquals("" +
+                    "IgniteMergeJoin(condition=[AND(=($0, $4), =($3, $1))], joinType=[inner])\n" +
+                    "  IgniteIndexScan(table=[[PUBLIC, DEPT]], index=[dep_idx])\n" +
+                    "  IgniteIndexScan(table=[[PUBLIC, EMP]], index=[emp_idx])\n",
+                RelOptUtil.toString(phys));
+        }
+    }
+
+    /** */
+    @Test
+    public void testMergeJoinIsNotAppliedForNonEquiJoin() throws Exception {
+        IgniteTypeFactory f = new IgniteTypeFactory(IgniteTypeSystem.INSTANCE);
+
+        TestTable emp = new TestTable(
+            new RelDataTypeFactory.Builder(f)
+                .add("ID", f.createJavaType(Integer.class))
+                .add("NAME", f.createJavaType(String.class))
+                .add("DEPTNO", f.createJavaType(Integer.class))
+                .build()) {
+
+            @Override public IgniteDistribution distribution() {
+                return IgniteDistributions.broadcast();

Review comment:
       I found, that changing distribution into : return IgniteDistributions.affinity(0, "EMP", "hash");
   will not return physical plan at all, is it ok ?




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [ignite] zstan commented on a change in pull request #8456: IGNITE-13544 Calcite integration. Merge joins

Posted by GitBox <gi...@apache.org>.
zstan commented on a change in pull request #8456:
URL: https://github.com/apache/ignite/pull/8456#discussion_r531395150



##########
File path: modules/calcite/src/test/java/org/apache/ignite/internal/processors/query/calcite/exec/rel/ExecutionTest.java
##########
@@ -980,6 +980,71 @@ public void testCorrelatedNestedLoopJoin() {
         }
     }
 
+    /** */
+    @Test
+    public void testMergeJoin() {
+        ExecutionContext<Object[]> ctx = executionContext(F.first(nodes()), UUID.randomUUID(), 0);
+        IgniteTypeFactory tf = ctx.getTypeFactory();
+        RelDataType rowType = TypeUtils.createRowType(tf, int.class, String.class, int.class);
+
+        int[] leftSizes = {1, 99, 100, 101, 512, 513, 2000};

Review comment:
       plz change hardcoded, like it made here
   https://github.com/apache/ignite/blob/ignite-12248/modules/calcite/src/test/java/org/apache/ignite/internal/processors/query/calcite/LimitOffsetTest.java#L212




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [ignite] korlov42 commented on a change in pull request #8456: IGNITE-13544 Calcite integration. Merge joins

Posted by GitBox <gi...@apache.org>.
korlov42 commented on a change in pull request #8456:
URL: https://github.com/apache/ignite/pull/8456#discussion_r530894211



##########
File path: modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/metadata/IgniteMdRowCount.java
##########
@@ -47,6 +48,63 @@
         return joinRowCount(mq, rel);
     }
 
+    /** */
+    public Double getRowCount(IgniteCorrelatedNestedLoopJoin rel, RelMetadataQuery mq) {
+        if (!rel.getJoinType().projectsRight()) {
+            // Create a RexNode representing the selectivity of the
+            // semijoin filter and pass it to getSelectivity
+            RexNode semiJoinSelectivity =
+                RelMdUtil.makeSemiJoinSelectivityRexNode(mq, rel);
+
+            return multiply(mq.getSelectivity(rel.getLeft(), semiJoinSelectivity),
+                mq.getRowCount(rel.getLeft()));
+        }
+
+        // Row count estimates of 0 will be rounded up to 1.
+        // So, use maxRowCount where the product is very small.
+        final Double left = mq.getRowCount(rel.getLeft());
+        final Double right = mq.getRowCount(rel.getRight());
+
+        if (left == null || right == null)
+            return null;
+
+        if (left <= 1D || right <= 1D) {
+            Double max = mq.getMaxRowCount(rel);
+            if (max != null && max <= 1D)
+                return max;
+        }
+
+        JoinInfo joinInfo = rel.analyzeCondition();
+
+        ImmutableIntList leftKeys = joinInfo.leftKeys;
+        ImmutableIntList rightKeys = joinInfo.rightKeys;
+
+        if (F.isEmpty(leftKeys) || F.isEmpty(rightKeys)) {
+            if (F.isEmpty(leftKeys))
+                return left * right;
+            else
+                return left * right * mq.getSelectivity(rel, rel.getCondition());
+        }
+

Review comment:
       because rel.estimateRowCount(mq) uses this method to estimate row count




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [ignite] korlov42 commented on a change in pull request #8456: IGNITE-13544 Calcite integration. Merge joins

Posted by GitBox <gi...@apache.org>.
korlov42 commented on a change in pull request #8456:
URL: https://github.com/apache/ignite/pull/8456#discussion_r529500695



##########
File path: modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/rule/MergeJoinConverterRule.java
##########
@@ -0,0 +1,74 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ignite.internal.processors.query.calcite.rule;
+
+import org.apache.calcite.plan.RelOptCluster;
+import org.apache.calcite.plan.RelOptPlanner;
+import org.apache.calcite.plan.RelOptRule;
+import org.apache.calcite.plan.RelOptRuleCall;
+import org.apache.calcite.plan.RelTraitSet;
+import org.apache.calcite.rel.PhysicalNode;
+import org.apache.calcite.rel.RelCollations;
+import org.apache.calcite.rel.RelNode;
+import org.apache.calcite.rel.core.JoinInfo;
+import org.apache.calcite.rel.logical.LogicalJoin;
+import org.apache.calcite.rel.metadata.RelMetadataQuery;
+import org.apache.ignite.internal.processors.query.calcite.rel.IgniteConvention;
+import org.apache.ignite.internal.processors.query.calcite.rel.IgniteMergeJoin;
+import org.apache.ignite.internal.util.typedef.F;
+
+/**
+ * Ignite Join converter.
+ */
+public class MergeJoinConverterRule extends AbstractIgniteConverterRule<LogicalJoin> {
+    /** */
+    public static final RelOptRule INSTANCE = new MergeJoinConverterRule();
+
+    /**
+     * Creates a converter.
+     */
+    public MergeJoinConverterRule() {
+        super(LogicalJoin.class, "MergeJoinConverterRule");
+    }
+
+    /** {@inheritDoc} */
+    @Override public boolean matches(RelOptRuleCall call) {
+        LogicalJoin logicalJoin = call.rel(0);
+
+        return !F.isEmpty(logicalJoin.analyzeCondition().pairs());
+    }
+
+    /** {@inheritDoc} */
+    @Override protected PhysicalNode convert(RelOptPlanner planner, RelMetadataQuery mq, LogicalJoin rel) {
+        RelOptCluster cluster = rel.getCluster();
+
+        JoinInfo joinInfo = JoinInfo.of(rel.getLeft(), rel.getRight(), rel.getCondition());
+
+        RelTraitSet leftInTraits = cluster.traitSetOf(IgniteConvention.INSTANCE)
+            .replace(RelCollations.of(joinInfo.leftKeys));
+        RelTraitSet outTraits = cluster.traitSetOf(IgniteConvention.INSTANCE)
+            .replace(RelCollations.of(joinInfo.leftKeys)); // preserve collation of the left input

Review comment:
       because we can't preserve collation of both input's when converting from logical to physical node. There is a tests that verifies collation from ORDER BY preserved even it contains column from both table. Please see https://github.com/apache/ignite/pull/8456/files#diff-9b2afd77c4bd5e6a82744cac80418daa1804931da4828fb08d3b9c842a71ecd0R2637 




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [ignite] zstan commented on a change in pull request #8456: IGNITE-13544 Calcite integration. Merge joins

Posted by GitBox <gi...@apache.org>.
zstan commented on a change in pull request #8456:
URL: https://github.com/apache/ignite/pull/8456#discussion_r530856818



##########
File path: modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/metadata/IgniteMdRowCount.java
##########
@@ -47,6 +48,63 @@
         return joinRowCount(mq, rel);
     }
 
+    /** */
+    public Double getRowCount(IgniteCorrelatedNestedLoopJoin rel, RelMetadataQuery mq) {
+        if (!rel.getJoinType().projectsRight()) {
+            // Create a RexNode representing the selectivity of the
+            // semijoin filter and pass it to getSelectivity
+            RexNode semiJoinSelectivity =
+                RelMdUtil.makeSemiJoinSelectivityRexNode(mq, rel);
+
+            return multiply(mq.getSelectivity(rel.getLeft(), semiJoinSelectivity),
+                mq.getRowCount(rel.getLeft()));
+        }
+
+        // Row count estimates of 0 will be rounded up to 1.
+        // So, use maxRowCount where the product is very small.
+        final Double left = mq.getRowCount(rel.getLeft());
+        final Double right = mq.getRowCount(rel.getRight());
+
+        if (left == null || right == null)
+            return null;
+
+        if (left <= 1D || right <= 1D) {

Review comment:
       replace 10 with constant.




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [ignite] korlov42 commented on a change in pull request #8456: IGNITE-13544 Calcite integration. Merge joins

Posted by GitBox <gi...@apache.org>.
korlov42 commented on a change in pull request #8456:
URL: https://github.com/apache/ignite/pull/8456#discussion_r530517188



##########
File path: modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/rule/MergeJoinConverterRule.java
##########
@@ -0,0 +1,74 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ignite.internal.processors.query.calcite.rule;
+
+import org.apache.calcite.plan.RelOptCluster;
+import org.apache.calcite.plan.RelOptPlanner;
+import org.apache.calcite.plan.RelOptRule;
+import org.apache.calcite.plan.RelOptRuleCall;
+import org.apache.calcite.plan.RelTraitSet;
+import org.apache.calcite.rel.PhysicalNode;
+import org.apache.calcite.rel.RelCollations;
+import org.apache.calcite.rel.RelNode;
+import org.apache.calcite.rel.core.JoinInfo;
+import org.apache.calcite.rel.logical.LogicalJoin;
+import org.apache.calcite.rel.metadata.RelMetadataQuery;
+import org.apache.ignite.internal.processors.query.calcite.rel.IgniteConvention;
+import org.apache.ignite.internal.processors.query.calcite.rel.IgniteMergeJoin;
+import org.apache.ignite.internal.util.typedef.F;
+
+/**
+ * Ignite Join converter.
+ */
+public class MergeJoinConverterRule extends AbstractIgniteConverterRule<LogicalJoin> {
+    /** */
+    public static final RelOptRule INSTANCE = new MergeJoinConverterRule();
+
+    /**
+     * Creates a converter.
+     */
+    public MergeJoinConverterRule() {
+        super(LogicalJoin.class, "MergeJoinConverterRule");
+    }
+
+    /** {@inheritDoc} */
+    @Override public boolean matches(RelOptRuleCall call) {
+        LogicalJoin logicalJoin = call.rel(0);
+
+        return !F.isEmpty(logicalJoin.analyzeCondition().pairs());

Review comment:
       Oh, now I see. Yes, you are right. Condition should be like `return !F.isEmpty(logicalJoin.analyzeCondition().pairs()) && logicalJoin.analyzeCondition().isEqui();`




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [ignite] korlov42 commented on a change in pull request #8456: IGNITE-13544 Calcite integration. Merge joins

Posted by GitBox <gi...@apache.org>.
korlov42 commented on a change in pull request #8456:
URL: https://github.com/apache/ignite/pull/8456#discussion_r531491891



##########
File path: modules/calcite/src/test/java/org/apache/ignite/internal/processors/query/calcite/PlannerTest.java
##########
@@ -2656,6 +2659,221 @@ public void testJoinPushExpressionRule() throws Exception {
         }
     }
 
+    /** */
+    @Test
+    public void testMergeJoin() throws Exception {
+        IgniteTypeFactory f = new IgniteTypeFactory(IgniteTypeSystem.INSTANCE);
+
+        TestTable emp = new TestTable(
+            new RelDataTypeFactory.Builder(f)
+                .add("ID", f.createJavaType(Integer.class))
+                .add("NAME", f.createJavaType(String.class))
+                .add("DEPTNO", f.createJavaType(Integer.class))
+                .build()) {
+
+            @Override public IgniteDistribution distribution() {
+                return IgniteDistributions.broadcast();
+            }
+        };
+
+        emp.addIndex(new IgniteIndex(RelCollations.of(ImmutableIntList.of(1, 2)), "emp_idx", null, emp));
+
+        TestTable dept = new TestTable(
+            new RelDataTypeFactory.Builder(f)
+                .add("DEPTNO", f.createJavaType(Integer.class))
+                .add("NAME", f.createJavaType(String.class))
+                .build()) {
+
+            @Override public IgniteDistribution distribution() {
+                return IgniteDistributions.broadcast();
+            }
+        };
+
+        dept.addIndex(new IgniteIndex(RelCollations.of(ImmutableIntList.of(1, 0)), "dep_idx", null, dept));
+
+        IgniteSchema publicSchema = new IgniteSchema("PUBLIC");
+
+        publicSchema.addTable("EMP", emp);
+        publicSchema.addTable("DEPT", dept);
+
+        SchemaPlus schema = createRootSchema(false)
+            .add("PUBLIC", publicSchema);
+
+        String sql = "select * from dept d join emp e on d.deptno = e.deptno and e.name = d.name order by e.name, d.deptno";
+
+        RelTraitDef<?>[] traitDefs = {
+            DistributionTraitDef.INSTANCE,
+            ConventionTraitDef.INSTANCE,
+            RelCollationTraitDef.INSTANCE,
+            RewindabilityTraitDef.INSTANCE,
+            CorrelationTraitDef.INSTANCE
+        };
+
+        PlanningContext ctx = PlanningContext.builder()
+            .localNodeId(F.first(nodes))
+            .originatingNodeId(F.first(nodes))
+            .parentContext(Contexts.empty())
+            .frameworkConfig(newConfigBuilder(FRAMEWORK_CONFIG)
+                .defaultSchema(schema)
+                .traitDefs(traitDefs)
+                .build())
+            .logger(log)
+            .query(sql)
+            .topologyVersion(AffinityTopologyVersion.NONE)
+            .build();
+
+        try (IgnitePlanner planner = ctx.planner()) {
+            assertNotNull(planner);
+
+            String qry = ctx.query();
+
+            assertNotNull(qry);
+
+            // Parse
+            SqlNode sqlNode = planner.parse(qry);
+
+            // Validate
+            sqlNode = planner.validate(sqlNode);
+
+            // Convert to Relational operators graph
+            RelRoot relRoot = planner.rel(sqlNode);
+
+            RelNode rel = relRoot.rel;
+
+            assertNotNull(rel);
+            assertEquals("" +
+                    "LogicalSort(sort0=[$3], sort1=[$0], dir0=[ASC], dir1=[ASC])\n" +
+                    "  LogicalProject(DEPTNO=[$0], NAME=[$1], ID=[$2], NAME0=[$3], DEPTNO0=[$4])\n" +
+                    "    LogicalJoin(condition=[AND(=($0, $4), =($3, $1))], joinType=[inner])\n" +
+                    "      IgniteLogicalTableScan(table=[[PUBLIC, DEPT]])\n" +
+                    "      IgniteLogicalTableScan(table=[[PUBLIC, EMP]])\n",
+                RelOptUtil.toString(rel));
+
+            // Transformation chain
+            RelTraitSet desired = rel.getTraitSet()
+                .replace(IgniteConvention.INSTANCE)
+                .replace(IgniteDistributions.single())
+                .simplify();
+
+            RelNode phys = planner.transform(PlannerPhase.OPTIMIZATION, desired, rel);
+
+            assertNotNull(phys);
+            assertEquals("" +
+                    "IgniteMergeJoin(condition=[AND(=($0, $4), =($3, $1))], joinType=[inner])\n" +
+                    "  IgniteIndexScan(table=[[PUBLIC, DEPT]], index=[dep_idx])\n" +
+                    "  IgniteIndexScan(table=[[PUBLIC, EMP]], index=[emp_idx])\n",
+                RelOptUtil.toString(phys));
+        }
+    }
+
+    /** */
+    @Test
+    public void testMergeJoinIsNotAppliedForNonEquiJoin() throws Exception {
+        IgniteTypeFactory f = new IgniteTypeFactory(IgniteTypeSystem.INSTANCE);
+
+        TestTable emp = new TestTable(
+            new RelDataTypeFactory.Builder(f)
+                .add("ID", f.createJavaType(Integer.class))
+                .add("NAME", f.createJavaType(String.class))
+                .add("DEPTNO", f.createJavaType(Integer.class))
+                .build()) {
+
+            @Override public IgniteDistribution distribution() {
+                return IgniteDistributions.broadcast();

Review comment:
       Can't reproduce this locally. Did you do any additional changes?




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [ignite] korlov42 commented on a change in pull request #8456: IGNITE-13544 Calcite integration. Merge joins

Posted by GitBox <gi...@apache.org>.
korlov42 commented on a change in pull request #8456:
URL: https://github.com/apache/ignite/pull/8456#discussion_r529503114



##########
File path: modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/rule/MergeJoinConverterRule.java
##########
@@ -0,0 +1,74 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ignite.internal.processors.query.calcite.rule;
+
+import org.apache.calcite.plan.RelOptCluster;
+import org.apache.calcite.plan.RelOptPlanner;
+import org.apache.calcite.plan.RelOptRule;
+import org.apache.calcite.plan.RelOptRuleCall;
+import org.apache.calcite.plan.RelTraitSet;
+import org.apache.calcite.rel.PhysicalNode;
+import org.apache.calcite.rel.RelCollations;
+import org.apache.calcite.rel.RelNode;
+import org.apache.calcite.rel.core.JoinInfo;
+import org.apache.calcite.rel.logical.LogicalJoin;
+import org.apache.calcite.rel.metadata.RelMetadataQuery;
+import org.apache.ignite.internal.processors.query.calcite.rel.IgniteConvention;
+import org.apache.ignite.internal.processors.query.calcite.rel.IgniteMergeJoin;
+import org.apache.ignite.internal.util.typedef.F;
+
+/**
+ * Ignite Join converter.
+ */
+public class MergeJoinConverterRule extends AbstractIgniteConverterRule<LogicalJoin> {
+    /** */
+    public static final RelOptRule INSTANCE = new MergeJoinConverterRule();
+
+    /**
+     * Creates a converter.
+     */
+    public MergeJoinConverterRule() {
+        super(LogicalJoin.class, "MergeJoinConverterRule");
+    }
+
+    /** {@inheritDoc} */
+    @Override public boolean matches(RelOptRuleCall call) {
+        LogicalJoin logicalJoin = call.rel(0);
+
+        return !F.isEmpty(logicalJoin.analyzeCondition().pairs());

Review comment:
       I don't sure we should cover non-equi join with merge algorithm. Merge join is not very optimal in case of many-to-many joins.




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [ignite] asfgit closed pull request #8456: IGNITE-13544 Calcite integration. Merge joins

Posted by GitBox <gi...@apache.org>.
asfgit closed pull request #8456:
URL: https://github.com/apache/ignite/pull/8456


   


----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [ignite] korlov42 commented on a change in pull request #8456: IGNITE-13544 Calcite integration. Merge joins

Posted by GitBox <gi...@apache.org>.
korlov42 commented on a change in pull request #8456:
URL: https://github.com/apache/ignite/pull/8456#discussion_r530894211



##########
File path: modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/metadata/IgniteMdRowCount.java
##########
@@ -47,6 +48,63 @@
         return joinRowCount(mq, rel);
     }
 
+    /** */
+    public Double getRowCount(IgniteCorrelatedNestedLoopJoin rel, RelMetadataQuery mq) {
+        if (!rel.getJoinType().projectsRight()) {
+            // Create a RexNode representing the selectivity of the
+            // semijoin filter and pass it to getSelectivity
+            RexNode semiJoinSelectivity =
+                RelMdUtil.makeSemiJoinSelectivityRexNode(mq, rel);
+
+            return multiply(mq.getSelectivity(rel.getLeft(), semiJoinSelectivity),
+                mq.getRowCount(rel.getLeft()));
+        }
+
+        // Row count estimates of 0 will be rounded up to 1.
+        // So, use maxRowCount where the product is very small.
+        final Double left = mq.getRowCount(rel.getLeft());
+        final Double right = mq.getRowCount(rel.getRight());
+
+        if (left == null || right == null)
+            return null;
+
+        if (left <= 1D || right <= 1D) {
+            Double max = mq.getMaxRowCount(rel);
+            if (max != null && max <= 1D)
+                return max;
+        }
+
+        JoinInfo joinInfo = rel.analyzeCondition();
+
+        ImmutableIntList leftKeys = joinInfo.leftKeys;
+        ImmutableIntList rightKeys = joinInfo.rightKeys;
+
+        if (F.isEmpty(leftKeys) || F.isEmpty(rightKeys)) {
+            if (F.isEmpty(leftKeys))
+                return left * right;
+            else
+                return left * right * mq.getSelectivity(rel, rel.getCondition());
+        }
+

Review comment:
       because rel.estimateRowCount(mq) uses this method estimates row count




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [ignite] korlov42 commented on a change in pull request #8456: IGNITE-13544 Calcite integration. Merge joins

Posted by GitBox <gi...@apache.org>.
korlov42 commented on a change in pull request #8456:
URL: https://github.com/apache/ignite/pull/8456#discussion_r531078939



##########
File path: modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/rel/IgniteMergeJoin.java
##########
@@ -0,0 +1,634 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ignite.internal.processors.query.calcite.rel;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableSet;
+import org.apache.calcite.plan.RelOptCluster;
+import org.apache.calcite.plan.RelOptCost;
+import org.apache.calcite.plan.RelOptPlanner;
+import org.apache.calcite.plan.RelTraitSet;
+import org.apache.calcite.rel.RelCollation;
+import org.apache.calcite.rel.RelCollations;
+import org.apache.calcite.rel.RelDistribution;
+import org.apache.calcite.rel.RelFieldCollation;
+import org.apache.calcite.rel.RelInput;
+import org.apache.calcite.rel.RelNode;
+import org.apache.calcite.rel.RelNodes;
+import org.apache.calcite.rel.RelWriter;
+import org.apache.calcite.rel.core.CorrelationId;
+import org.apache.calcite.rel.core.Join;
+import org.apache.calcite.rel.core.JoinInfo;
+import org.apache.calcite.rel.core.JoinRelType;
+import org.apache.calcite.rel.metadata.RelMdUtil;
+import org.apache.calcite.rel.metadata.RelMetadataQuery;
+import org.apache.calcite.rex.RexNode;
+import org.apache.calcite.sql.SqlExplainLevel;
+import org.apache.calcite.util.ImmutableBitSet;
+import org.apache.calcite.util.ImmutableIntList;
+import org.apache.calcite.util.Pair;
+import org.apache.calcite.util.Util;
+import org.apache.ignite.internal.processors.query.calcite.trait.CorrelationTrait;
+import org.apache.ignite.internal.processors.query.calcite.trait.DistributionFunction;
+import org.apache.ignite.internal.processors.query.calcite.trait.IgniteDistribution;
+import org.apache.ignite.internal.processors.query.calcite.trait.RewindabilityTrait;
+import org.apache.ignite.internal.processors.query.calcite.trait.TraitUtils;
+import org.apache.ignite.internal.processors.query.calcite.trait.TraitsAwareIgniteRel;
+import org.apache.ignite.internal.processors.query.calcite.util.Commons;
+import org.apache.ignite.internal.util.typedef.F;
+import org.jetbrains.annotations.Nullable;
+
+import static org.apache.calcite.rel.RelDistribution.Type.BROADCAST_DISTRIBUTED;
+import static org.apache.calcite.rel.RelDistribution.Type.HASH_DISTRIBUTED;
+import static org.apache.calcite.rel.RelDistribution.Type.SINGLETON;
+import static org.apache.calcite.rel.core.JoinRelType.INNER;
+import static org.apache.calcite.rel.core.JoinRelType.LEFT;
+import static org.apache.calcite.rel.core.JoinRelType.RIGHT;
+import static org.apache.calcite.util.NumberUtil.multiply;
+import static org.apache.ignite.internal.processors.query.calcite.trait.IgniteDistributions.broadcast;
+import static org.apache.ignite.internal.processors.query.calcite.trait.IgniteDistributions.hash;
+import static org.apache.ignite.internal.processors.query.calcite.trait.IgniteDistributions.single;
+
+/** */
+public class IgniteMergeJoin extends Join implements TraitsAwareIgniteRel {
+    /** */
+    public IgniteMergeJoin(RelOptCluster cluster, RelTraitSet traitSet, RelNode left, RelNode right,
+        RexNode condition, Set<CorrelationId> variablesSet, JoinRelType joinType) {
+        super(cluster, traitSet, left, right, condition, variablesSet, joinType);
+    }
+
+    /** */
+    public IgniteMergeJoin(RelInput input) {
+        this(input.getCluster(),
+            input.getTraitSet().replace(IgniteConvention.INSTANCE),
+            input.getInputs().get(0),
+            input.getInputs().get(1),
+            input.getExpression("condition"),
+            ImmutableSet.copyOf(Commons.transform(input.getIntegerList("variablesSet"), CorrelationId::new)),
+            input.getEnum("joinType", JoinRelType.class));
+    }
+
+    /** {@inheritDoc} */
+    @Override public Join copy(RelTraitSet traitSet, RexNode condition, RelNode left, RelNode right,
+        JoinRelType joinType, boolean semiJoinDone) {
+        return new IgniteMergeJoin(getCluster(), traitSet, left, right, condition, variablesSet, joinType);
+    }
+
+    /** {@inheritDoc} */
+    @Override public <T> T accept(IgniteRelVisitor<T> visitor) {
+        return visitor.visit(this);
+    }
+
+    /** {@inheritDoc} */
+    @Override public IgniteRel clone(RelOptCluster cluster, List<IgniteRel> inputs) {
+        return new IgniteMergeJoin(cluster, getTraitSet(), inputs.get(0), inputs.get(1), getCondition(), getVariablesSet(), getJoinType());
+    }
+
+    /** {@inheritDoc} */
+    @Override public RelWriter explainTerms(RelWriter pw) {
+        return super.explainTerms(pw)
+            .itemIf(
+                "variablesSet",
+                Commons.transform(variablesSet.asList(), CorrelationId::getId),
+                pw.getDetailLevel() == SqlExplainLevel.ALL_ATTRIBUTES
+            );
+    }
+
+    /** {@inheritDoc} */
+    @Override public List<Pair<RelTraitSet, List<RelTraitSet>>> deriveCollation(
+        RelTraitSet nodeTraits,
+        List<RelTraitSet> inputTraits
+    ) {
+        RelTraitSet left = inputTraits.get(0), right = inputTraits.get(1);
+        RelCollation leftCollation = TraitUtils.collation(left), rightCollation = TraitUtils.collation(right);
+
+        List<Integer> newLeftCollation, newRightCollation;
+
+        if (isPrefix(leftCollation.getKeys(), joinInfo.leftKeys)) { // preserve left collation
+            newLeftCollation = new ArrayList<>(leftCollation.getKeys());
+
+            Map<Integer, Integer> leftToRight = joinInfo.pairs().stream()
+                .collect(Collectors.toMap(p -> p.source, p -> p.target));
+
+            newRightCollation = newLeftCollation.stream().map(leftToRight::get).collect(Collectors.toList());
+        }
+        else if (isPrefix(rightCollation.getKeys(), joinInfo.rightKeys)) { // preserve right collation
+            newRightCollation = new ArrayList<>(rightCollation.getKeys());
+
+            Map<Integer, Integer> rightToLeft = joinInfo.pairs().stream()
+                .collect(Collectors.toMap(p -> p.target, p -> p.source));
+
+            newLeftCollation = newRightCollation.stream().map(rightToLeft::get).collect(Collectors.toList());
+        }
+        else { // generate new collations
+            // TODO: generate permutations when there will be multitraits
+
+            newLeftCollation = new ArrayList<>(joinInfo.leftKeys);
+            newRightCollation = new ArrayList<>(joinInfo.rightKeys);
+        }
+
+        leftCollation = createCollation(newLeftCollation);
+        rightCollation = createCollation(newRightCollation);
+
+        return ImmutableList.of(
+            Pair.of(
+                nodeTraits.replace(leftCollation),
+                ImmutableList.of(
+                    left.replace(leftCollation),
+                    right.replace(rightCollation)
+                )
+            )
+        );
+    }
+
+    /** {@inheritDoc} */
+    @Override public List<Pair<RelTraitSet, List<RelTraitSet>>> deriveRewindability(
+        RelTraitSet nodeTraits,
+        List<RelTraitSet> inputTraits
+    ) {
+        // The node is rewindable only if both sources are rewindable.
+
+        RelTraitSet left = inputTraits.get(0), right = inputTraits.get(1);
+
+        RewindabilityTrait leftRewindability = TraitUtils.rewindability(left);
+        RewindabilityTrait rightRewindability = TraitUtils.rewindability(right);
+
+        RelTraitSet outTraits, leftTraits, rightTraits;
+
+        if (leftRewindability.rewindable() && rightRewindability.rewindable()) {
+            outTraits = nodeTraits.replace(RewindabilityTrait.REWINDABLE);
+            leftTraits = left.replace(RewindabilityTrait.REWINDABLE);
+            rightTraits = right.replace(RewindabilityTrait.REWINDABLE);
+        }
+        else {
+            outTraits = nodeTraits.replace(RewindabilityTrait.ONE_WAY);
+            leftTraits = left.replace(RewindabilityTrait.ONE_WAY);
+            rightTraits = right.replace(RewindabilityTrait.ONE_WAY);
+        }
+
+        return ImmutableList.of(Pair.of(outTraits, ImmutableList.of(leftTraits, rightTraits)));
+    }
+
+    /** {@inheritDoc} */
+    @Override public List<Pair<RelTraitSet, List<RelTraitSet>>> deriveDistribution(
+        RelTraitSet nodeTraits,
+        List<RelTraitSet> inputTraits
+    ) {
+        // Tere are several rules:
+        // 1) any join is possible on broadcast or single distribution
+        // 2) hash distributed join is possible when join keys equal to source distribution keys
+        // 3) hash and broadcast distributed tables can be joined when join keys equal to hash
+        //    distributed table distribution keys and:
+        //      3.1) it's a left join and a hash distributed table is at left
+        //      3.2) it's a right join and a hash distributed table is at right
+        //      3.3) it's an inner join, this case a hash distributed table may be at any side
+
+        RelTraitSet left = inputTraits.get(0), right = inputTraits.get(1);
+
+        List<Pair<RelTraitSet, List<RelTraitSet>>> res = new ArrayList<>();
+
+        IgniteDistribution leftDistr = TraitUtils.distribution(left);
+        IgniteDistribution rightDistr = TraitUtils.distribution(right);
+
+        RelTraitSet outTraits, leftTraits, rightTraits;
+
+        if (leftDistr == broadcast() || rightDistr == broadcast()) {
+            outTraits = nodeTraits.replace(broadcast());
+            leftTraits = left.replace(broadcast());
+            rightTraits = right.replace(broadcast());
+
+            res.add(Pair.of(outTraits, ImmutableList.of(leftTraits, rightTraits)));
+        }
+
+        if (leftDistr == single() || rightDistr == single()) {
+            outTraits = nodeTraits.replace(single());
+            leftTraits = left.replace(single());
+            rightTraits = right.replace(single());
+
+            res.add(Pair.of(outTraits, ImmutableList.of(leftTraits, rightTraits)));
+        }
+
+        if (!F.isEmpty(joinInfo.pairs())) {
+            Set<DistributionFunction> functions = new HashSet<>();
+
+            if (leftDistr.getType() == HASH_DISTRIBUTED
+                && Objects.equals(joinInfo.leftKeys, leftDistr.getKeys()))
+                functions.add(leftDistr.function());
+
+            if (rightDistr.getType() == HASH_DISTRIBUTED
+                && Objects.equals(joinInfo.rightKeys, rightDistr.getKeys()))
+                functions.add(rightDistr.function());
+
+            functions.add(DistributionFunction.hash());
+
+            for (DistributionFunction function : functions) {
+                leftTraits = left.replace(hash(joinInfo.leftKeys, function));
+                rightTraits = right.replace(hash(joinInfo.rightKeys, function));
+
+                // TODO distribution multitrait support
+                outTraits = nodeTraits.replace(hash(joinInfo.leftKeys, function));
+                res.add(Pair.of(outTraits, ImmutableList.of(leftTraits, rightTraits)));
+
+                outTraits = nodeTraits.replace(hash(joinInfo.rightKeys, function));
+                res.add(Pair.of(outTraits, ImmutableList.of(leftTraits, rightTraits)));
+
+                if (joinType == INNER || joinType == LEFT) {
+                    outTraits = nodeTraits.replace(hash(joinInfo.leftKeys, function));
+                    leftTraits = left.replace(hash(joinInfo.leftKeys, function));
+                    rightTraits = right.replace(broadcast());
+
+                    res.add(Pair.of(outTraits, ImmutableList.of(leftTraits, rightTraits)));
+                }
+
+                if (joinType == INNER || joinType == RIGHT) {
+                    outTraits = nodeTraits.replace(hash(joinInfo.rightKeys, function));
+                    leftTraits = left.replace(broadcast());
+                    rightTraits = right.replace(hash(joinInfo.rightKeys, function));
+
+                    res.add(Pair.of(outTraits, ImmutableList.of(leftTraits, rightTraits)));
+                }
+            }
+        }
+
+        if (!res.isEmpty())
+            return ImmutableList.of();

Review comment:
       fixed




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [ignite] zstan commented on a change in pull request #8456: IGNITE-13544 Calcite integration. Merge joins

Posted by GitBox <gi...@apache.org>.
zstan commented on a change in pull request #8456:
URL: https://github.com/apache/ignite/pull/8456#discussion_r530885570



##########
File path: modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/metadata/IgniteMdRowCount.java
##########
@@ -47,6 +48,63 @@
         return joinRowCount(mq, rel);
     }
 
+    /** */
+    public Double getRowCount(IgniteCorrelatedNestedLoopJoin rel, RelMetadataQuery mq) {
+        if (!rel.getJoinType().projectsRight()) {
+            // Create a RexNode representing the selectivity of the
+            // semijoin filter and pass it to getSelectivity
+            RexNode semiJoinSelectivity =
+                RelMdUtil.makeSemiJoinSelectivityRexNode(mq, rel);
+
+            return multiply(mq.getSelectivity(rel.getLeft(), semiJoinSelectivity),
+                mq.getRowCount(rel.getLeft()));
+        }
+
+        // Row count estimates of 0 will be rounded up to 1.
+        // So, use maxRowCount where the product is very small.
+        final Double left = mq.getRowCount(rel.getLeft());
+        final Double right = mq.getRowCount(rel.getRight());
+
+        if (left == null || right == null)
+            return null;
+
+        if (left <= 1D || right <= 1D) {
+            Double max = mq.getMaxRowCount(rel);
+            if (max != null && max <= 1D)
+                return max;
+        }
+
+        JoinInfo joinInfo = rel.analyzeCondition();
+
+        ImmutableIntList leftKeys = joinInfo.leftKeys;
+        ImmutableIntList rightKeys = joinInfo.rightKeys;
+
+        if (F.isEmpty(leftKeys) || F.isEmpty(rightKeys)) {
+            if (F.isEmpty(leftKeys))
+                return left * right;
+            else
+                return left * right * mq.getSelectivity(rel, rel.getCondition());
+        }
+

Review comment:
       wht we can`t replace all upper stuff with : final Double rowCount = rel.estimateRowCount(mq); ?

##########
File path: modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/metadata/IgniteMdRowCount.java
##########
@@ -47,6 +48,63 @@
         return joinRowCount(mq, rel);
     }
 
+    /** */
+    public Double getRowCount(IgniteCorrelatedNestedLoopJoin rel, RelMetadataQuery mq) {
+        if (!rel.getJoinType().projectsRight()) {
+            // Create a RexNode representing the selectivity of the
+            // semijoin filter and pass it to getSelectivity
+            RexNode semiJoinSelectivity =
+                RelMdUtil.makeSemiJoinSelectivityRexNode(mq, rel);
+
+            return multiply(mq.getSelectivity(rel.getLeft(), semiJoinSelectivity),
+                mq.getRowCount(rel.getLeft()));
+        }
+
+        // Row count estimates of 0 will be rounded up to 1.
+        // So, use maxRowCount where the product is very small.
+        final Double left = mq.getRowCount(rel.getLeft());
+        final Double right = mq.getRowCount(rel.getRight());
+
+        if (left == null || right == null)
+            return null;
+
+        if (left <= 1D || right <= 1D) {
+            Double max = mq.getMaxRowCount(rel);
+            if (max != null && max <= 1D)
+                return max;
+        }
+
+        JoinInfo joinInfo = rel.analyzeCondition();
+
+        ImmutableIntList leftKeys = joinInfo.leftKeys;
+        ImmutableIntList rightKeys = joinInfo.rightKeys;
+
+        if (F.isEmpty(leftKeys) || F.isEmpty(rightKeys)) {
+            if (F.isEmpty(leftKeys))
+                return left * right;
+            else
+                return left * right * mq.getSelectivity(rel, rel.getCondition());
+        }
+

Review comment:
       why we can`t replace all upper stuff with : final Double rowCount = rel.estimateRowCount(mq); ?




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [ignite] zstan commented on a change in pull request #8456: IGNITE-13544 Calcite integration. Merge joins

Posted by GitBox <gi...@apache.org>.
zstan commented on a change in pull request #8456:
URL: https://github.com/apache/ignite/pull/8456#discussion_r525320362



##########
File path: modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/rule/MergeJoinConverterRule.java
##########
@@ -0,0 +1,74 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ignite.internal.processors.query.calcite.rule;
+
+import org.apache.calcite.plan.RelOptCluster;
+import org.apache.calcite.plan.RelOptPlanner;
+import org.apache.calcite.plan.RelOptRule;
+import org.apache.calcite.plan.RelOptRuleCall;
+import org.apache.calcite.plan.RelTraitSet;
+import org.apache.calcite.rel.PhysicalNode;
+import org.apache.calcite.rel.RelCollations;
+import org.apache.calcite.rel.RelNode;
+import org.apache.calcite.rel.core.JoinInfo;
+import org.apache.calcite.rel.logical.LogicalJoin;
+import org.apache.calcite.rel.metadata.RelMetadataQuery;
+import org.apache.ignite.internal.processors.query.calcite.rel.IgniteConvention;
+import org.apache.ignite.internal.processors.query.calcite.rel.IgniteMergeJoin;
+import org.apache.ignite.internal.util.typedef.F;
+
+/**
+ * Ignite Join converter.
+ */
+public class MergeJoinConverterRule extends AbstractIgniteConverterRule<LogicalJoin> {
+    /** */
+    public static final RelOptRule INSTANCE = new MergeJoinConverterRule();
+
+    /**
+     * Creates a converter.
+     */
+    public MergeJoinConverterRule() {
+        super(LogicalJoin.class, "MergeJoinConverterRule");
+    }
+
+    /** {@inheritDoc} */
+    @Override public boolean matches(RelOptRuleCall call) {
+        LogicalJoin logicalJoin = call.rel(0);
+
+        return !F.isEmpty(logicalJoin.analyzeCondition().pairs());

Review comment:
       does cortesian and unequality i.e.
   _select *
   from dealer d1 
   join dealer d2  
   on d1.id=d2.id AND d1.product>=d2.product_ joins need to be covered here too ? 




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [ignite] zstan commented on a change in pull request #8456: IGNITE-13544 Calcite integration. Merge joins

Posted by GitBox <gi...@apache.org>.
zstan commented on a change in pull request #8456:
URL: https://github.com/apache/ignite/pull/8456#discussion_r530513981



##########
File path: modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/rule/MergeJoinConverterRule.java
##########
@@ -0,0 +1,74 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ignite.internal.processors.query.calcite.rule;
+
+import org.apache.calcite.plan.RelOptCluster;
+import org.apache.calcite.plan.RelOptPlanner;
+import org.apache.calcite.plan.RelOptRule;
+import org.apache.calcite.plan.RelOptRuleCall;
+import org.apache.calcite.plan.RelTraitSet;
+import org.apache.calcite.rel.PhysicalNode;
+import org.apache.calcite.rel.RelCollations;
+import org.apache.calcite.rel.RelNode;
+import org.apache.calcite.rel.core.JoinInfo;
+import org.apache.calcite.rel.logical.LogicalJoin;
+import org.apache.calcite.rel.metadata.RelMetadataQuery;
+import org.apache.ignite.internal.processors.query.calcite.rel.IgniteConvention;
+import org.apache.ignite.internal.processors.query.calcite.rel.IgniteMergeJoin;
+import org.apache.ignite.internal.util.typedef.F;
+
+/**
+ * Ignite Join converter.
+ */
+public class MergeJoinConverterRule extends AbstractIgniteConverterRule<LogicalJoin> {
+    /** */
+    public static final RelOptRule INSTANCE = new MergeJoinConverterRule();
+
+    /**
+     * Creates a converter.
+     */
+    public MergeJoinConverterRule() {
+        super(LogicalJoin.class, "MergeJoinConverterRule");
+    }
+
+    /** {@inheritDoc} */
+    @Override public boolean matches(RelOptRuleCall call) {
+        LogicalJoin logicalJoin = call.rel(0);
+
+        return !F.isEmpty(logicalJoin.analyzeCondition().pairs());

Review comment:
       of course - no, we needn`t cover them, we need to return false in such cases, isn`t it ?




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [ignite] korlov42 commented on a change in pull request #8456: IGNITE-13544 Calcite integration. Merge joins

Posted by GitBox <gi...@apache.org>.
korlov42 commented on a change in pull request #8456:
URL: https://github.com/apache/ignite/pull/8456#discussion_r530930772



##########
File path: modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/metadata/IgniteMdRowCount.java
##########
@@ -68,9 +126,9 @@
             return null;
 
         if (left <= 1D || right <= 1D) {
-          Double max = mq.getMaxRowCount(rel);
-          if (max != null && max <= 1D)
-              return max;
+            Double max = mq.getMaxRowCount(rel);
+            if (max != null && max <= 1D)

Review comment:
       see answer above




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [ignite] zstan commented on a change in pull request #8456: IGNITE-13544 Calcite integration. Merge joins

Posted by GitBox <gi...@apache.org>.
zstan commented on a change in pull request #8456:
URL: https://github.com/apache/ignite/pull/8456#discussion_r530927395



##########
File path: modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/metadata/IgniteMdRowCount.java
##########
@@ -68,9 +126,9 @@
             return null;
 
         if (left <= 1D || right <= 1D) {
-          Double max = mq.getMaxRowCount(rel);
-          if (max != null && max <= 1D)
-              return max;
+            Double max = mq.getMaxRowCount(rel);
+            if (max != null && max <= 1D)

Review comment:
       10 need to be a constant.




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [ignite] zstan commented on a change in pull request #8456: IGNITE-13544 Calcite integration. Merge joins

Posted by GitBox <gi...@apache.org>.
zstan commented on a change in pull request #8456:
URL: https://github.com/apache/ignite/pull/8456#discussion_r525338040



##########
File path: modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/rule/MergeJoinConverterRule.java
##########
@@ -0,0 +1,74 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ignite.internal.processors.query.calcite.rule;
+
+import org.apache.calcite.plan.RelOptCluster;
+import org.apache.calcite.plan.RelOptPlanner;
+import org.apache.calcite.plan.RelOptRule;
+import org.apache.calcite.plan.RelOptRuleCall;
+import org.apache.calcite.plan.RelTraitSet;
+import org.apache.calcite.rel.PhysicalNode;
+import org.apache.calcite.rel.RelCollations;
+import org.apache.calcite.rel.RelNode;
+import org.apache.calcite.rel.core.JoinInfo;
+import org.apache.calcite.rel.logical.LogicalJoin;
+import org.apache.calcite.rel.metadata.RelMetadataQuery;
+import org.apache.ignite.internal.processors.query.calcite.rel.IgniteConvention;
+import org.apache.ignite.internal.processors.query.calcite.rel.IgniteMergeJoin;
+import org.apache.ignite.internal.util.typedef.F;
+
+/**
+ * Ignite Join converter.
+ */
+public class MergeJoinConverterRule extends AbstractIgniteConverterRule<LogicalJoin> {
+    /** */
+    public static final RelOptRule INSTANCE = new MergeJoinConverterRule();
+
+    /**
+     * Creates a converter.
+     */
+    public MergeJoinConverterRule() {
+        super(LogicalJoin.class, "MergeJoinConverterRule");
+    }
+
+    /** {@inheritDoc} */
+    @Override public boolean matches(RelOptRuleCall call) {
+        LogicalJoin logicalJoin = call.rel(0);
+
+        return !F.isEmpty(logicalJoin.analyzeCondition().pairs());
+    }
+
+    /** {@inheritDoc} */
+    @Override protected PhysicalNode convert(RelOptPlanner planner, RelMetadataQuery mq, LogicalJoin rel) {
+        RelOptCluster cluster = rel.getCluster();
+
+        JoinInfo joinInfo = JoinInfo.of(rel.getLeft(), rel.getRight(), rel.getCondition());
+
+        RelTraitSet leftInTraits = cluster.traitSetOf(IgniteConvention.INSTANCE)
+            .replace(RelCollations.of(joinInfo.leftKeys));
+        RelTraitSet outTraits = cluster.traitSetOf(IgniteConvention.INSTANCE)
+            .replace(RelCollations.of(joinInfo.leftKeys)); // preserve collation of the left input

Review comment:
       why do we take only left into account here ? If other cases will be produced by pass through or derive - we need additional tests here. 




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [ignite] zstan commented on a change in pull request #8456: IGNITE-13544 Calcite integration. Merge joins

Posted by GitBox <gi...@apache.org>.
zstan commented on a change in pull request #8456:
URL: https://github.com/apache/ignite/pull/8456#discussion_r531065417



##########
File path: modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/rel/IgniteMergeJoin.java
##########
@@ -0,0 +1,634 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ignite.internal.processors.query.calcite.rel;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableSet;
+import org.apache.calcite.plan.RelOptCluster;
+import org.apache.calcite.plan.RelOptCost;
+import org.apache.calcite.plan.RelOptPlanner;
+import org.apache.calcite.plan.RelTraitSet;
+import org.apache.calcite.rel.RelCollation;
+import org.apache.calcite.rel.RelCollations;
+import org.apache.calcite.rel.RelDistribution;
+import org.apache.calcite.rel.RelFieldCollation;
+import org.apache.calcite.rel.RelInput;
+import org.apache.calcite.rel.RelNode;
+import org.apache.calcite.rel.RelNodes;
+import org.apache.calcite.rel.RelWriter;
+import org.apache.calcite.rel.core.CorrelationId;
+import org.apache.calcite.rel.core.Join;
+import org.apache.calcite.rel.core.JoinInfo;
+import org.apache.calcite.rel.core.JoinRelType;
+import org.apache.calcite.rel.metadata.RelMdUtil;
+import org.apache.calcite.rel.metadata.RelMetadataQuery;
+import org.apache.calcite.rex.RexNode;
+import org.apache.calcite.sql.SqlExplainLevel;
+import org.apache.calcite.util.ImmutableBitSet;
+import org.apache.calcite.util.ImmutableIntList;
+import org.apache.calcite.util.Pair;
+import org.apache.calcite.util.Util;
+import org.apache.ignite.internal.processors.query.calcite.trait.CorrelationTrait;
+import org.apache.ignite.internal.processors.query.calcite.trait.DistributionFunction;
+import org.apache.ignite.internal.processors.query.calcite.trait.IgniteDistribution;
+import org.apache.ignite.internal.processors.query.calcite.trait.RewindabilityTrait;
+import org.apache.ignite.internal.processors.query.calcite.trait.TraitUtils;
+import org.apache.ignite.internal.processors.query.calcite.trait.TraitsAwareIgniteRel;
+import org.apache.ignite.internal.processors.query.calcite.util.Commons;
+import org.apache.ignite.internal.util.typedef.F;
+import org.jetbrains.annotations.Nullable;
+
+import static org.apache.calcite.rel.RelDistribution.Type.BROADCAST_DISTRIBUTED;
+import static org.apache.calcite.rel.RelDistribution.Type.HASH_DISTRIBUTED;
+import static org.apache.calcite.rel.RelDistribution.Type.SINGLETON;
+import static org.apache.calcite.rel.core.JoinRelType.INNER;
+import static org.apache.calcite.rel.core.JoinRelType.LEFT;
+import static org.apache.calcite.rel.core.JoinRelType.RIGHT;
+import static org.apache.calcite.util.NumberUtil.multiply;
+import static org.apache.ignite.internal.processors.query.calcite.trait.IgniteDistributions.broadcast;
+import static org.apache.ignite.internal.processors.query.calcite.trait.IgniteDistributions.hash;
+import static org.apache.ignite.internal.processors.query.calcite.trait.IgniteDistributions.single;
+
+/** */
+public class IgniteMergeJoin extends Join implements TraitsAwareIgniteRel {
+    /** */
+    public IgniteMergeJoin(RelOptCluster cluster, RelTraitSet traitSet, RelNode left, RelNode right,
+        RexNode condition, Set<CorrelationId> variablesSet, JoinRelType joinType) {
+        super(cluster, traitSet, left, right, condition, variablesSet, joinType);
+    }
+
+    /** */
+    public IgniteMergeJoin(RelInput input) {
+        this(input.getCluster(),
+            input.getTraitSet().replace(IgniteConvention.INSTANCE),
+            input.getInputs().get(0),
+            input.getInputs().get(1),
+            input.getExpression("condition"),
+            ImmutableSet.copyOf(Commons.transform(input.getIntegerList("variablesSet"), CorrelationId::new)),
+            input.getEnum("joinType", JoinRelType.class));
+    }
+
+    /** {@inheritDoc} */
+    @Override public Join copy(RelTraitSet traitSet, RexNode condition, RelNode left, RelNode right,
+        JoinRelType joinType, boolean semiJoinDone) {
+        return new IgniteMergeJoin(getCluster(), traitSet, left, right, condition, variablesSet, joinType);
+    }
+
+    /** {@inheritDoc} */
+    @Override public <T> T accept(IgniteRelVisitor<T> visitor) {
+        return visitor.visit(this);
+    }
+
+    /** {@inheritDoc} */
+    @Override public IgniteRel clone(RelOptCluster cluster, List<IgniteRel> inputs) {
+        return new IgniteMergeJoin(cluster, getTraitSet(), inputs.get(0), inputs.get(1), getCondition(), getVariablesSet(), getJoinType());
+    }
+
+    /** {@inheritDoc} */
+    @Override public RelWriter explainTerms(RelWriter pw) {
+        return super.explainTerms(pw)
+            .itemIf(
+                "variablesSet",
+                Commons.transform(variablesSet.asList(), CorrelationId::getId),
+                pw.getDetailLevel() == SqlExplainLevel.ALL_ATTRIBUTES
+            );
+    }
+
+    /** {@inheritDoc} */
+    @Override public List<Pair<RelTraitSet, List<RelTraitSet>>> deriveCollation(
+        RelTraitSet nodeTraits,
+        List<RelTraitSet> inputTraits
+    ) {
+        RelTraitSet left = inputTraits.get(0), right = inputTraits.get(1);
+        RelCollation leftCollation = TraitUtils.collation(left), rightCollation = TraitUtils.collation(right);
+
+        List<Integer> newLeftCollation, newRightCollation;
+
+        if (isPrefix(leftCollation.getKeys(), joinInfo.leftKeys)) { // preserve left collation
+            newLeftCollation = new ArrayList<>(leftCollation.getKeys());
+
+            Map<Integer, Integer> leftToRight = joinInfo.pairs().stream()
+                .collect(Collectors.toMap(p -> p.source, p -> p.target));
+
+            newRightCollation = newLeftCollation.stream().map(leftToRight::get).collect(Collectors.toList());
+        }
+        else if (isPrefix(rightCollation.getKeys(), joinInfo.rightKeys)) { // preserve right collation
+            newRightCollation = new ArrayList<>(rightCollation.getKeys());
+
+            Map<Integer, Integer> rightToLeft = joinInfo.pairs().stream()
+                .collect(Collectors.toMap(p -> p.target, p -> p.source));
+
+            newLeftCollation = newRightCollation.stream().map(rightToLeft::get).collect(Collectors.toList());
+        }
+        else { // generate new collations
+            // TODO: generate permutations when there will be multitraits
+
+            newLeftCollation = new ArrayList<>(joinInfo.leftKeys);
+            newRightCollation = new ArrayList<>(joinInfo.rightKeys);
+        }
+
+        leftCollation = createCollation(newLeftCollation);
+        rightCollation = createCollation(newRightCollation);
+
+        return ImmutableList.of(
+            Pair.of(
+                nodeTraits.replace(leftCollation),
+                ImmutableList.of(
+                    left.replace(leftCollation),
+                    right.replace(rightCollation)
+                )
+            )
+        );
+    }
+
+    /** {@inheritDoc} */
+    @Override public List<Pair<RelTraitSet, List<RelTraitSet>>> deriveRewindability(
+        RelTraitSet nodeTraits,
+        List<RelTraitSet> inputTraits
+    ) {
+        // The node is rewindable only if both sources are rewindable.
+
+        RelTraitSet left = inputTraits.get(0), right = inputTraits.get(1);
+
+        RewindabilityTrait leftRewindability = TraitUtils.rewindability(left);
+        RewindabilityTrait rightRewindability = TraitUtils.rewindability(right);
+
+        RelTraitSet outTraits, leftTraits, rightTraits;
+
+        if (leftRewindability.rewindable() && rightRewindability.rewindable()) {
+            outTraits = nodeTraits.replace(RewindabilityTrait.REWINDABLE);
+            leftTraits = left.replace(RewindabilityTrait.REWINDABLE);
+            rightTraits = right.replace(RewindabilityTrait.REWINDABLE);
+        }
+        else {
+            outTraits = nodeTraits.replace(RewindabilityTrait.ONE_WAY);
+            leftTraits = left.replace(RewindabilityTrait.ONE_WAY);
+            rightTraits = right.replace(RewindabilityTrait.ONE_WAY);
+        }
+
+        return ImmutableList.of(Pair.of(outTraits, ImmutableList.of(leftTraits, rightTraits)));
+    }
+
+    /** {@inheritDoc} */
+    @Override public List<Pair<RelTraitSet, List<RelTraitSet>>> deriveDistribution(
+        RelTraitSet nodeTraits,
+        List<RelTraitSet> inputTraits
+    ) {
+        // Tere are several rules:
+        // 1) any join is possible on broadcast or single distribution
+        // 2) hash distributed join is possible when join keys equal to source distribution keys
+        // 3) hash and broadcast distributed tables can be joined when join keys equal to hash
+        //    distributed table distribution keys and:
+        //      3.1) it's a left join and a hash distributed table is at left
+        //      3.2) it's a right join and a hash distributed table is at right
+        //      3.3) it's an inner join, this case a hash distributed table may be at any side
+
+        RelTraitSet left = inputTraits.get(0), right = inputTraits.get(1);
+
+        List<Pair<RelTraitSet, List<RelTraitSet>>> res = new ArrayList<>();
+
+        IgniteDistribution leftDistr = TraitUtils.distribution(left);
+        IgniteDistribution rightDistr = TraitUtils.distribution(right);
+
+        RelTraitSet outTraits, leftTraits, rightTraits;
+
+        if (leftDistr == broadcast() || rightDistr == broadcast()) {
+            outTraits = nodeTraits.replace(broadcast());
+            leftTraits = left.replace(broadcast());
+            rightTraits = right.replace(broadcast());
+
+            res.add(Pair.of(outTraits, ImmutableList.of(leftTraits, rightTraits)));
+        }
+
+        if (leftDistr == single() || rightDistr == single()) {
+            outTraits = nodeTraits.replace(single());
+            leftTraits = left.replace(single());
+            rightTraits = right.replace(single());
+
+            res.add(Pair.of(outTraits, ImmutableList.of(leftTraits, rightTraits)));
+        }
+
+        if (!F.isEmpty(joinInfo.pairs())) {
+            Set<DistributionFunction> functions = new HashSet<>();
+
+            if (leftDistr.getType() == HASH_DISTRIBUTED
+                && Objects.equals(joinInfo.leftKeys, leftDistr.getKeys()))
+                functions.add(leftDistr.function());
+
+            if (rightDistr.getType() == HASH_DISTRIBUTED
+                && Objects.equals(joinInfo.rightKeys, rightDistr.getKeys()))
+                functions.add(rightDistr.function());
+
+            functions.add(DistributionFunction.hash());
+
+            for (DistributionFunction function : functions) {
+                leftTraits = left.replace(hash(joinInfo.leftKeys, function));
+                rightTraits = right.replace(hash(joinInfo.rightKeys, function));
+
+                // TODO distribution multitrait support
+                outTraits = nodeTraits.replace(hash(joinInfo.leftKeys, function));
+                res.add(Pair.of(outTraits, ImmutableList.of(leftTraits, rightTraits)));
+
+                outTraits = nodeTraits.replace(hash(joinInfo.rightKeys, function));
+                res.add(Pair.of(outTraits, ImmutableList.of(leftTraits, rightTraits)));
+
+                if (joinType == INNER || joinType == LEFT) {
+                    outTraits = nodeTraits.replace(hash(joinInfo.leftKeys, function));
+                    leftTraits = left.replace(hash(joinInfo.leftKeys, function));
+                    rightTraits = right.replace(broadcast());
+
+                    res.add(Pair.of(outTraits, ImmutableList.of(leftTraits, rightTraits)));
+                }
+
+                if (joinType == INNER || joinType == RIGHT) {
+                    outTraits = nodeTraits.replace(hash(joinInfo.rightKeys, function));
+                    leftTraits = left.replace(broadcast());
+                    rightTraits = right.replace(hash(joinInfo.rightKeys, function));
+
+                    res.add(Pair.of(outTraits, ImmutableList.of(leftTraits, rightTraits)));
+                }
+            }
+        }
+
+        if (!res.isEmpty())
+            return ImmutableList.of();

Review comment:
       empty result here ?




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [ignite] korlov42 commented on a change in pull request #8456: IGNITE-13544 Calcite integration. Merge joins

Posted by GitBox <gi...@apache.org>.
korlov42 commented on a change in pull request #8456:
URL: https://github.com/apache/ignite/pull/8456#discussion_r531001071



##########
File path: modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/rel/IgniteMergeJoin.java
##########
@@ -0,0 +1,634 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ignite.internal.processors.query.calcite.rel;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableSet;
+import org.apache.calcite.plan.RelOptCluster;
+import org.apache.calcite.plan.RelOptCost;
+import org.apache.calcite.plan.RelOptPlanner;
+import org.apache.calcite.plan.RelTraitSet;
+import org.apache.calcite.rel.RelCollation;
+import org.apache.calcite.rel.RelCollations;
+import org.apache.calcite.rel.RelDistribution;
+import org.apache.calcite.rel.RelFieldCollation;
+import org.apache.calcite.rel.RelInput;
+import org.apache.calcite.rel.RelNode;
+import org.apache.calcite.rel.RelNodes;
+import org.apache.calcite.rel.RelWriter;
+import org.apache.calcite.rel.core.CorrelationId;
+import org.apache.calcite.rel.core.Join;
+import org.apache.calcite.rel.core.JoinInfo;
+import org.apache.calcite.rel.core.JoinRelType;
+import org.apache.calcite.rel.metadata.RelMdUtil;
+import org.apache.calcite.rel.metadata.RelMetadataQuery;
+import org.apache.calcite.rex.RexNode;
+import org.apache.calcite.sql.SqlExplainLevel;
+import org.apache.calcite.util.ImmutableBitSet;
+import org.apache.calcite.util.ImmutableIntList;
+import org.apache.calcite.util.Pair;
+import org.apache.calcite.util.Util;
+import org.apache.ignite.internal.processors.query.calcite.trait.CorrelationTrait;
+import org.apache.ignite.internal.processors.query.calcite.trait.DistributionFunction;
+import org.apache.ignite.internal.processors.query.calcite.trait.IgniteDistribution;
+import org.apache.ignite.internal.processors.query.calcite.trait.RewindabilityTrait;
+import org.apache.ignite.internal.processors.query.calcite.trait.TraitUtils;
+import org.apache.ignite.internal.processors.query.calcite.trait.TraitsAwareIgniteRel;
+import org.apache.ignite.internal.processors.query.calcite.util.Commons;
+import org.apache.ignite.internal.util.typedef.F;
+import org.jetbrains.annotations.Nullable;
+
+import static org.apache.calcite.rel.RelDistribution.Type.BROADCAST_DISTRIBUTED;
+import static org.apache.calcite.rel.RelDistribution.Type.HASH_DISTRIBUTED;
+import static org.apache.calcite.rel.RelDistribution.Type.SINGLETON;
+import static org.apache.calcite.rel.core.JoinRelType.INNER;
+import static org.apache.calcite.rel.core.JoinRelType.LEFT;
+import static org.apache.calcite.rel.core.JoinRelType.RIGHT;
+import static org.apache.calcite.util.NumberUtil.multiply;
+import static org.apache.ignite.internal.processors.query.calcite.trait.IgniteDistributions.broadcast;
+import static org.apache.ignite.internal.processors.query.calcite.trait.IgniteDistributions.hash;
+import static org.apache.ignite.internal.processors.query.calcite.trait.IgniteDistributions.single;
+
+/** */
+public class IgniteMergeJoin extends Join implements TraitsAwareIgniteRel {
+    /** */
+    public IgniteMergeJoin(RelOptCluster cluster, RelTraitSet traitSet, RelNode left, RelNode right,
+        RexNode condition, Set<CorrelationId> variablesSet, JoinRelType joinType) {
+        super(cluster, traitSet, left, right, condition, variablesSet, joinType);

Review comment:
       it was just copy-pasted. So fixed




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org