This is an automated email from the ASF dual-hosted git repository.
hello-stephen pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/doris.git
The following commit(s) were added to refs/heads/master by this push:
new e46677d8008 [improvement](nereids) Support OR expansion for right
joins (#70471)
e46677d8008 is described below
commit e46677d80082fff2bf442993e35a9d1911f4a2cf
Author: minghong <[email protected]>
AuthorDate: Thu Nov 26 20:13:49 2026 +0800
[improvement](nereids) Support OR expansion for right joins (#70471)
### Background
RBO normally uses SemiJoinCommute to normalize RIGHT OUTER and RIGHT
ANTI joins to their left equivalents before OR expansion. This
normalization is skipped when join reordering is disabled, the join is
marked LEADING, or it has a distribution hint. OR expansion replaces
eligible disjunctive joins with hash join branches, using anti joins for
unmatched outer/anti rows.
### What problem does this PR solve?
Issue Number: None
Related PR: #67067 (join-order rewrite context; master retains
SemiJoinCommute)
PR Type: Enhancement
Problem Summary:
When an eligible RIGHT OUTER or RIGHT ANTI join survives RBO
normalization, OR expansion skips it because its supported-type set only
includes INNER, LEFT OUTER, FULL OUTER and LEFT ANTI. For example,
setting disable_join_reorder=true keeps the original right join but does
not disable OR_EXPANSION. Extend both right types using the
right-preserving anti expansion already used by FULL OUTER JOIN,
preserving original output slots and ordering. Ordinary right joins that
are already normalized to left can use the existing expansion path; the
new regression explicitly prevents that normalization so it exercises
the added right-join paths.
### Details
- **Change map:** 16 changed production lines in OrExpansion.java; 176
changed test lines across OrExpansionTest.java and the new regression
suite; 223 generated expected-result lines.
- **Before and after:** When a right join reaches OrExpansion, RIGHT
OUTER now combines matching branches with unmatched right rows and
null-pads the left output. RIGHT ANTI returns unmatched right rows using
the existing left anti helper with producers and slot maps swapped
together. Previously these right types were skipped.
- **Configs and defaults:** No new settings. The existing OR_EXPANSION
switch controls expansion; mark joins and ineligible hash disjuncts
remain excluded. The regression sets disable_join_reorder=true
specifically to preserve right joins through RBO and prevent CBO commute
from obscuring the baseline direction.
- **Impact on existing users:** Eligible right joins that survive
normalization can use hash joins instead of nested loop joins. Existing
left/inner/full expansion paths remain covered.
JoinExtractOrFromCaseWhen shares the eligibility check, so right-side
CASE extraction is also covered.
- **Behavior change:** Plans for retained right joins can change; SQL
result semantics remain the same. No BE operator, protocol or storage
change is needed.
### Testing
Run locally with the compiled FE and an existing ASAN BE:
- `MAVEN_ARGS='-Ddisable.obs=true' bash run-fe-ut.sh --run
org.apache.doris.nereids.rules.rewrite.OrExpansionTest`: 14 tests passed
for the production implementation, including direct right-join
expansion, output ExprIds/order/nullability, CTE nesting, expression
keys, residual predicates and non-hash rejection.
- `bash build.sh --fe --exclude-obs-dependencies -j8`: passed, including
FE core Checkstyle with 0 violations. The follow-up changes only the
Groovy regression suite and this description.
- `bash run-regression-test.sh --conf
/tmp/or-expansion-regression-conf.groovy --run -d query_p0/union -s
or_expansion_right_join`: passed after the coverage correction. With
reordering disabled, EXPLAIN checks require RIGHT OUTER/RIGHT ANTI
nested loop joins when expansion is disabled, and hash joins with no
nested loop joins when expansion is enabled. CASE extraction has the
same positive/negative plan checks.
- All 30 result blocks match the existing auto-generated expected file,
and all 15 enabled/disabled result pairs are identical. Coverage
includes duplicates, overlapping disjuncts, NULLs, null-safe equality,
residual predicates, CASE extraction, aggregation and empty inputs. No
expected-output changes were necessary.
- Earlier implementation validation also passed the existing
or_expansion and join_extract_or_from_case_when suites. The temporary
configuration selects the isolated local cluster.
### Release note
Support OR expansion for eligible RIGHT OUTER and RIGHT ANTI joins that
survive RBO join-direction normalization, allowing these queries to use
hash joins.
### Check List (For Author)
- Behavior changed: Yes (see Details).
- Does this need documentation: No.
- Pre-submission status: Ready.
### AI Disclosure
- Tool: Codex (GPT-6).
- Generated: Implementation, tests and this PR description.
- Human review: Pending author review.
---
.../doris/nereids/rules/rewrite/OrExpansion.java | 21 +-
.../nereids/rules/rewrite/OrExpansionTest.java | 86 +++++++-
.../query_p0/union/or_expansion_right_join.out | 223 +++++++++++++++++++++
.../query_p0/union/or_expansion_right_join.groovy | 117 +++++++++++
4 files changed, 437 insertions(+), 10 deletions(-)
diff --git
a/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/OrExpansion.java
b/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/OrExpansion.java
index aed58ae002f..281a5158f54 100644
---
a/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/OrExpansion.java
+++
b/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/OrExpansion.java
@@ -74,7 +74,9 @@ public class OrExpansion extends
DefaultPlanRewriter<OrExpandsionContext> implem
.Builder<JoinType>()
.add(JoinType.INNER_JOIN)
.add(JoinType.LEFT_ANTI_JOIN)
+ .add(JoinType.RIGHT_ANTI_JOIN)
.add(JoinType.LEFT_OUTER_JOIN)
+ .add(JoinType.RIGHT_OUTER_JOIN)
.add(JoinType.FULL_OUTER_JOIN)
.build();
@@ -160,19 +162,23 @@ public class OrExpansion extends
DefaultPlanRewriter<OrExpandsionContext> implem
joins.addAll(expandInnerJoin(ctx.cascadesContext,
hashOtherConditions,
join, leftProducer, rightProducer, leftCloneToLeft,
rightCloneToRight));
} else if (join.getJoinType().isOuterJoin()) {
- // left outer join = inner join union left anti join
+ // Outer join = matching rows union unmatched rows from each
preserved side.
joins.addAll(expandInnerJoin(ctx.cascadesContext,
hashOtherConditions,
join, leftProducer, rightProducer, leftCloneToLeft,
rightCloneToRight));
- joins.add(expandLeftAntiJoin(ctx.cascadesContext,
- hashOtherConditions, join, leftProducer, rightProducer,
leftCloneToLeft, rightCloneToRight));
- if (join.getJoinType().equals(JoinType.FULL_OUTER_JOIN)) {
- // full outer join = inner join union left anti join union
right anti join
+ if (join.getJoinType().isLeftOuterJoin() ||
join.getJoinType().isFullOuterJoin()) {
+ joins.add(expandLeftAntiJoin(ctx.cascadesContext,
+ hashOtherConditions, join, leftProducer,
rightProducer, leftCloneToLeft, rightCloneToRight));
+ }
+ if (join.getJoinType().isRightOuterJoin() ||
join.getJoinType().isFullOuterJoin()) {
joins.add(expandLeftAntiJoin(ctx.cascadesContext,
hashOtherConditions,
join, rightProducer, leftProducer, rightCloneToRight,
leftCloneToLeft));
}
} else if (join.getJoinType().equals(JoinType.LEFT_ANTI_JOIN)) {
joins.add(expandLeftAntiJoin(ctx.cascadesContext,
hashOtherConditions,
join, leftProducer, rightProducer, leftCloneToLeft,
rightCloneToRight));
+ } else if (join.getJoinType().isRightAntiJoin()) {
+ joins.add(expandLeftAntiJoin(ctx.cascadesContext,
hashOtherConditions,
+ join, rightProducer, leftProducer, rightCloneToRight,
leftCloneToLeft));
} else {
throw new RuntimeException("or-expansion is not supported for " +
join);
}
@@ -217,7 +223,10 @@ public class OrExpansion extends
DefaultPlanRewriter<OrExpandsionContext> implem
if (join.isMarkJoin() || !JoinUtils.shouldNestedLoopJoin(join)) {
return false;
}
- return supportJoinType.contains(join.getJoinType());
+ // OR expansion can evaluate an ON expression in more than one branch
or move it into a hash key.
+ return supportJoinType.contains(join.getJoinType())
+ && join.getOtherJoinConjuncts().stream()
+
.noneMatch(Expression::containsVolatileOrNoneMovableExpression);
}
private Map<Slot, Slot> constructReplaceMap(LogicalCTEConsumer
leftConsumer, Map<Slot, Slot> leftCloneToLeft,
diff --git
a/fe/fe-core/src/test/java/org/apache/doris/nereids/rules/rewrite/OrExpansionTest.java
b/fe/fe-core/src/test/java/org/apache/doris/nereids/rules/rewrite/OrExpansionTest.java
index 9a1094079b8..587ac94a66d 100644
---
a/fe/fe-core/src/test/java/org/apache/doris/nereids/rules/rewrite/OrExpansionTest.java
+++
b/fe/fe-core/src/test/java/org/apache/doris/nereids/rules/rewrite/OrExpansionTest.java
@@ -17,15 +17,25 @@
package org.apache.doris.nereids.rules.rewrite;
+import org.apache.doris.nereids.trees.expressions.Slot;
+import org.apache.doris.nereids.trees.plans.JoinType;
import org.apache.doris.nereids.trees.plans.Plan;
import org.apache.doris.nereids.trees.plans.logical.LogicalCTEAnchor;
import org.apache.doris.nereids.trees.plans.logical.LogicalCTEConsumer;
+import org.apache.doris.nereids.trees.plans.logical.LogicalCTEProducer;
+import org.apache.doris.nereids.trees.plans.logical.LogicalJoin;
+import org.apache.doris.nereids.trees.plans.logical.LogicalUnion;
import org.apache.doris.nereids.util.MemoPatternMatchSupported;
import org.apache.doris.nereids.util.PlanChecker;
import org.apache.doris.utframe.TestWithFeService;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.EnumSource;
+
+import java.util.List;
+import java.util.stream.Collectors;
class OrExpansionTest extends TestWithFeService implements
MemoPatternMatchSupported {
@Override
@@ -63,15 +73,16 @@ class OrExpansionTest extends TestWithFeService implements
MemoPatternMatchSuppo
Assertions.assertTrue(plan.child(1) instanceof LogicalCTEAnchor);
}
- @Test
- void testOrExpandCTE() {
+ @ParameterizedTest
+ @EnumSource(value = JoinType.class, names = {"INNER_JOIN",
"RIGHT_OUTER_JOIN", "RIGHT_ANTI_JOIN"})
+ void testOrExpandCTE(JoinType joinType) {
connectContext.getSessionVariable().setDisableNereidsRules("PRUNE_EMPTY_PARTITION");
connectContext.getSessionVariable().inlineCTEReferencedThreshold = 0;
String sql = "with t3 as (select t1.id1 + 1 as id1, t1.id2 + 2 as id2
from t1), "
+ "t4 as (select t2.id1 + 1 as id1, t2.id2 + 2 as id2 from
t2) "
- + "select t3.id1 from "
+ + "select t4.id1 from "
+ "(select id1, id2 from t3 group by id1, id2) t3 "
- + " join "
+ + " " + joinType.name().replace('_', ' ') + " "
+ "(select id1, id2 from t4 group by id1, id2) t4 "
+ "on t3.id1 = t4.id1 or t3.id2 = t4.id2";
Plan plan = PlanChecker.from(connectContext)
@@ -87,4 +98,71 @@ class OrExpansionTest extends TestWithFeService implements
MemoPatternMatchSuppo
Assertions.assertTrue(plan.child(1).child(1).child(1)
.anyMatch(x -> x instanceof LogicalCTEConsumer));
}
+
+ @ParameterizedTest
+ @EnumSource(value = JoinType.class, names = {
+ "INNER_JOIN", "LEFT_OUTER_JOIN", "RIGHT_OUTER_JOIN",
"FULL_OUTER_JOIN",
+ "LEFT_ANTI_JOIN", "RIGHT_ANTI_JOIN"})
+ void testExpansionPreservesOutput(JoinType joinType) {
+ String sql = "select * from t1 " + joinType.name().replace('_', ' ') +
" t2"
+ + " on t1.id1 = t2.id1 or t1.id2 = t2.id2";
+ PlanChecker checker = PlanChecker.from(connectContext).analyze(sql);
+ List<Slot> output = checker.getPlan().getOutput();
+ Plan plan = checker.applyCustom(OrExpansion.INSTANCE).getPlan();
+ Assertions.assertEquals(output, plan.getOutput());
+
Assertions.assertEquals(output.stream().map(Slot::nullable).collect(Collectors.toList()),
+
plan.getOutput().stream().map(Slot::nullable).collect(Collectors.toList()));
+ List<LogicalUnion> unions =
plan.collectToList(LogicalUnion.class::isInstance);
+ Assertions.assertEquals(1, unions.size(), plan.treeString());
+ int innerBranches = joinType.isInnerJoin() || joinType.isOuterJoin() ?
2 : 0;
+ int antiBranches = joinType.isFullOuterJoin() ? 2 :
(joinType.isInnerJoin() ? 0 : 1);
+ Assertions.assertEquals(innerBranches + antiBranches,
unions.get(0).arity(), plan.treeString());
+ }
+
+ @ParameterizedTest
+ @EnumSource(value = JoinType.class, names = {
+ "INNER_JOIN", "LEFT_OUTER_JOIN", "RIGHT_OUTER_JOIN",
"FULL_OUTER_JOIN",
+ "LEFT_ANTI_JOIN", "RIGHT_ANTI_JOIN"})
+ void testExpansionKeepsVolatileOrNonMovableOnPredicates(JoinType joinType)
{
+ for (String predicate : List.of("rand() < 0.5", "assert_true(t1.id1 <
t2.id2, 'invalid pair')")) {
+ String sql = "select * from t1 " + joinType.name().replace('_', '
') + " t2"
+ + " on (t1.id1 = t2.id1 or t1.id2 = t2.id2) and " +
predicate;
+ Plan plan =
PlanChecker.from(connectContext).analyze(sql).applyCustom(OrExpansion.INSTANCE).getPlan();
+
Assertions.assertFalse(plan.anyMatch(LogicalUnion.class::isInstance),
plan.treeString());
+ }
+ }
+
+ @ParameterizedTest
+ @EnumSource(value = JoinType.class, names = {"RIGHT_OUTER_JOIN",
"RIGHT_ANTI_JOIN"})
+ void testRightExpansionPreservesRightInput(JoinType joinType) {
+ String sql = "select * from t1 " + joinType.name().replace('_', ' ') +
" t2"
+ + " on (t1.id1 + 1 = t2.id1 or t1.id2 = t2.id2 + 1 or t2.id1 +
2 = t1.id2)"
+ + " and t1.id1 < t2.id2";
+ Plan plan =
PlanChecker.from(connectContext).analyze(sql).applyCustom(OrExpansion.INSTANCE).getPlan();
+ List<LogicalCTEProducer> producers =
plan.collectToList(LogicalCTEProducer.class::isInstance);
+ LogicalUnion union = (LogicalUnion)
plan.collectToList(LogicalUnion.class::isInstance).get(0);
+ Plan unmatched = union.child(union.arity() - 1);
+ List<LogicalCTEConsumer> consumers =
unmatched.collectToList(LogicalCTEConsumer.class::isInstance);
+ // The preserved right input is read once; each OR disjunct removes
matches from it.
+ Assertions.assertEquals(1, consumers.stream()
+ .filter(c ->
c.getCteId().equals(producers.get(1).getCteId())).count(), plan.treeString());
+ Assertions.assertEquals(3, consumers.stream()
+ .filter(c ->
c.getCteId().equals(producers.get(0).getCteId())).count(), plan.treeString());
+ List<LogicalJoin> antiJoins =
unmatched.collectToList(LogicalJoin.class::isInstance);
+ Assertions.assertEquals(3, antiJoins.size(), plan.treeString());
+ for (LogicalJoin<?, ?> antiJoin : antiJoins) {
+ Assertions.assertEquals(JoinType.LEFT_ANTI_JOIN,
antiJoin.getJoinType());
+ Assertions.assertEquals(1, antiJoin.getHashJoinConjuncts().size());
+ Assertions.assertEquals(1,
antiJoin.getOtherJoinConjuncts().size());
+ }
+ }
+
+ @ParameterizedTest
+ @EnumSource(value = JoinType.class, names = {"RIGHT_OUTER_JOIN",
"RIGHT_ANTI_JOIN"})
+ void testRightExpansionRequiresHashDisjuncts(JoinType joinType) {
+ String sql = "select * from t1 " + joinType.name().replace('_', ' ') +
" t2"
+ + " on t1.id1 = t2.id1 or t1.id2 > t2.id2";
+ Plan plan =
PlanChecker.from(connectContext).analyze(sql).applyCustom(OrExpansion.INSTANCE).getPlan();
+ Assertions.assertFalse(plan.anyMatch(LogicalUnion.class::isInstance),
plan.treeString());
+ }
}
diff --git a/regression-test/data/query_p0/union/or_expansion_right_join.out
b/regression-test/data/query_p0/union/or_expansion_right_join.out
new file mode 100644
index 00000000000..76167bde330
--- /dev/null
+++ b/regression-test/data/query_p0/union/or_expansion_right_join.out
@@ -0,0 +1,223 @@
+-- This file is automatically generated. You should know what you did if you
want to edit this
+-- !enabled --
+\N \N \N 105 \N \N 5
+\N \N \N 106 7 70 6
+\N \N \N 106 7 70 6
+1 1 10 101 1 10 1
+2 2 20 102 9 20 2
+2 2 20 102 9 20 2
+3 \N 30 103 \N 30 3
+4 4 \N 104 4 \N 4
+
+-- !disabled --
+\N \N \N 105 \N \N 5
+\N \N \N 106 7 70 6
+\N \N \N 106 7 70 6
+1 1 10 101 1 10 1
+2 2 20 102 9 20 2
+2 2 20 102 9 20 2
+3 \N 30 103 \N 30 3
+4 4 \N 104 4 \N 4
+
+-- !enabled --
+\N \N \N 103 \N 30 3
+\N \N \N 104 4 \N 4
+\N \N \N 105 \N \N 5
+\N \N \N 106 7 70 6
+\N \N \N 106 7 70 6
+1 1 10 101 1 10 1
+2 2 20 102 9 20 2
+2 2 20 102 9 20 2
+
+-- !disabled --
+\N \N \N 103 \N 30 3
+\N \N \N 104 4 \N 4
+\N \N \N 105 \N \N 5
+\N \N \N 106 7 70 6
+\N \N \N 106 7 70 6
+1 1 10 101 1 10 1
+2 2 20 102 9 20 2
+2 2 20 102 9 20 2
+
+-- !enabled --
+\N \N \N 101 1 10 1
+\N \N \N 102 9 20 2
+\N \N \N 103 \N 30 3
+\N \N \N 104 4 \N 4
+\N \N \N 105 \N \N 5
+6 6 60 106 7 70 6
+6 6 60 106 7 70 6
+
+-- !disabled --
+\N \N \N 101 1 10 1
+\N \N \N 102 9 20 2
+\N \N \N 103 \N 30 3
+\N \N \N 104 4 \N 4
+\N \N \N 105 \N \N 5
+6 6 60 106 7 70 6
+6 6 60 106 7 70 6
+
+-- !enabled --
+\N \N \N 106 7 70 6
+\N \N \N 106 7 70 6
+1 1 10 101 1 10 1
+2 2 20 102 9 20 2
+2 2 20 102 9 20 2
+3 \N 30 103 \N 30 3
+3 \N 30 105 \N \N 5
+4 4 \N 104 4 \N 4
+5 \N \N 103 \N 30 3
+5 \N \N 105 \N \N 5
+
+-- !disabled --
+\N \N \N 106 7 70 6
+\N \N \N 106 7 70 6
+1 1 10 101 1 10 1
+2 2 20 102 9 20 2
+2 2 20 102 9 20 2
+3 \N 30 103 \N 30 3
+3 \N 30 105 \N \N 5
+4 4 \N 104 4 \N 4
+5 \N \N 103 \N 30 3
+5 \N \N 105 \N \N 5
+
+-- !case_enabled --
+\N \N \N 102 9 20 2
+\N \N \N 103 \N 30 3
+\N \N \N 104 4 \N 4
+\N \N \N 105 \N \N 5
+\N \N \N 106 7 70 6
+\N \N \N 106 7 70 6
+1 1 10 101 1 10 1
+
+-- !case_disabled --
+\N \N \N 102 9 20 2
+\N \N \N 103 \N 30 3
+\N \N \N 104 4 \N 4
+\N \N \N 105 \N \N 5
+\N \N \N 106 7 70 6
+\N \N \N 106 7 70 6
+1 1 10 101 1 10 1
+
+-- !enabled --
+105 \N \N 5
+106 7 70 6
+106 7 70 6
+
+-- !disabled --
+105 \N \N 5
+106 7 70 6
+106 7 70 6
+
+-- !enabled --
+103 \N 30 3
+104 4 \N 4
+105 \N \N 5
+106 7 70 6
+106 7 70 6
+
+-- !disabled --
+103 \N 30 3
+104 4 \N 4
+105 \N \N 5
+106 7 70 6
+106 7 70 6
+
+-- !enabled --
+101 1 10 1
+102 9 20 2
+103 \N 30 3
+104 4 \N 4
+105 \N \N 5
+
+-- !disabled --
+101 1 10 1
+102 9 20 2
+103 \N 30 3
+104 4 \N 4
+105 \N \N 5
+
+-- !enabled --
+106 7 70 6
+106 7 70 6
+
+-- !disabled --
+106 7 70 6
+106 7 70 6
+
+-- !case_enabled --
+102 9 20 2
+103 \N 30 3
+104 4 \N 4
+105 \N \N 5
+106 7 70 6
+106 7 70 6
+
+-- !case_disabled --
+102 9 20 2
+103 \N 30 3
+104 4 \N 4
+105 \N \N 5
+106 7 70 6
+106 7 70 6
+
+-- !aggregate --
+101 1 10 1
+102 2 40 4
+103 1 30 3
+104 1 \N 4
+105 0 \N 5
+106 0 \N 12
+
+-- !aggregate_disabled --
+101 1 10 1
+102 2 40 4
+103 1 30 3
+104 1 \N 4
+105 0 \N 5
+106 0 \N 12
+
+-- !empty_enabled --
+\N \N \N 101 1 10 1
+\N \N \N 102 9 20 2
+\N \N \N 103 \N 30 3
+\N \N \N 104 4 \N 4
+\N \N \N 105 \N \N 5
+\N \N \N 106 7 70 6
+\N \N \N 106 7 70 6
+
+-- !empty_disabled --
+\N \N \N 101 1 10 1
+\N \N \N 102 9 20 2
+\N \N \N 103 \N 30 3
+\N \N \N 104 4 \N 4
+\N \N \N 105 \N \N 5
+\N \N \N 106 7 70 6
+\N \N \N 106 7 70 6
+
+-- !empty_enabled --
+
+-- !empty_disabled --
+
+-- !empty_enabled --
+101 1 10 1
+102 9 20 2
+103 \N 30 3
+104 4 \N 4
+105 \N \N 5
+106 7 70 6
+106 7 70 6
+
+-- !empty_disabled --
+101 1 10 1
+102 9 20 2
+103 \N 30 3
+104 4 \N 4
+105 \N \N 5
+106 7 70 6
+106 7 70 6
+
+-- !empty_enabled --
+
+-- !empty_disabled --
+
diff --git
a/regression-test/suites/query_p0/union/or_expansion_right_join.groovy
b/regression-test/suites/query_p0/union/or_expansion_right_join.groovy
new file mode 100644
index 00000000000..eac8a3021e5
--- /dev/null
+++ b/regression-test/suites/query_p0/union/or_expansion_right_join.groovy
@@ -0,0 +1,117 @@
+// 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.
+
+suite("or_expansion_right_join", "p0") {
+ // Keep RIGHT joins through RBO: SemiJoinCommute would otherwise normalize
them to LEFT joins.
+ sql "SET disable_join_reorder = true"
+ sql "DROP TABLE IF EXISTS or_expansion_right_join_l"
+ sql "DROP TABLE IF EXISTS or_expansion_right_join_r"
+ sql """CREATE TABLE or_expansion_right_join_l (id INT NOT NULL, a INT, b
INT)
+ DUPLICATE KEY(id) DISTRIBUTED BY HASH(id) BUCKETS 1
+ PROPERTIES("replication_num" = "1")"""
+ sql """CREATE TABLE or_expansion_right_join_r (id BIGINT NOT NULL, a
BIGINT, b BIGINT, v INT)
+ DUPLICATE KEY(id) DISTRIBUTED BY HASH(id) BUCKETS 1
+ PROPERTIES("replication_num" = "1")"""
+ // Include duplicate matches, overlapping OR branches, UNKNOWN predicates
and unmatched rows.
+ sql """INSERT INTO or_expansion_right_join_l VALUES
+ (1, 1, 10), (2, 2, 20), (2, 2, 20), (3, NULL, 30),
+ (4, 4, NULL), (5, NULL, NULL), (6, 6, 60)"""
+ sql """INSERT INTO or_expansion_right_join_r VALUES
+ (101, 1, 10, 1), (102, 9, 20, 2), (103, NULL, 30, 3),
+ (104, 4, NULL, 4), (105, NULL, NULL, 5), (106, 7, 70, 6), (106, 7, 70,
6)"""
+
+ for (String joinType : ["RIGHT OUTER", "RIGHT ANTI"]) {
+ for (String condition : [
+ "l.a = r.a OR l.b = r.b",
+ "(l.a = r.a OR l.b = r.b) AND l.id + r.v < 6",
+ "(l.a + 1 = r.a OR l.b = r.b + 1 OR r.a + 2 = l.b) AND l.id <
r.id",
+ "l.a <=> r.a OR l.b = r.b"]) {
+ String query = """SELECT %s * FROM or_expansion_right_join_l l
+ ${joinType} JOIN or_expansion_right_join_r r ON ${condition}"""
+ explain {
+ sql String.format(query, "")
+ contains "VHASH JOIN"
+ notContains "VNESTED LOOP JOIN"
+ }
+ explain {
+ sql String.format(query, "/*+
SET_VAR(disable_nereids_rules='OR_EXPANSION') */")
+ contains "${joinType} JOIN"
+ contains "VNESTED LOOP JOIN"
+ notContains "VHASH JOIN"
+ }
+ order_qt_enabled String.format(query, "")
+ order_qt_disabled String.format(query, "/*+
SET_VAR(disable_nereids_rules='OR_EXPANSION') */")
+ }
+
+ // Enlarging OrExpansion's supported types also enables CASE
extraction for right joins.
+ String caseQuery = """SELECT %s * FROM or_expansion_right_join_l l
+ ${joinType} JOIN or_expansion_right_join_r r
+ ON CASE WHEN r.v < 3 THEN l.a ELSE l.b END = r.a"""
+ explain {
+ sql String.format(caseQuery, "")
+ contains "VHASH JOIN"
+ notContains "VNESTED LOOP JOIN"
+ }
+ explain {
+ sql String.format(caseQuery,
+ "/*+
SET_VAR(disable_nereids_rules='OR_EXPANSION,JOIN_EXTRACT_OR_FROM_CASE_WHEN')
*/")
+ contains "${joinType} JOIN"
+ contains "VNESTED LOOP JOIN"
+ notContains "VHASH JOIN"
+ }
+ order_qt_case_enabled String.format(caseQuery, "")
+ order_qt_case_disabled String.format(caseQuery,
+ "/*+
SET_VAR(disable_nereids_rules='OR_EXPANSION,JOIN_EXTRACT_OR_FROM_CASE_WHEN')
*/")
+ }
+
+ // Matching and unmatched branches must agree on each candidate pair.
+ for (String joinType : ["LEFT OUTER", "RIGHT OUTER"]) {
+ for (String predicate : ["rand() < 0.5", "assert_true(l.id < r.id,
'invalid pair')"]) {
+ explain {
+ sql """SELECT * FROM or_expansion_right_join_l l
+ ${joinType} JOIN or_expansion_right_join_r r
+ ON (l.a = r.a OR l.b = r.b) AND ${predicate}"""
+ contains "${joinType} JOIN"
+ contains "VNESTED LOOP JOIN"
+ notContains "VHASH JOIN"
+ }
+ }
+ }
+
+ // Exercise the full rewrite pipeline with aggregation above the right
join.
+ order_qt_aggregate """SELECT r.id, COUNT(l.id), SUM(l.b), SUM(r.v)
+ FROM or_expansion_right_join_l l RIGHT OUTER JOIN
or_expansion_right_join_r r
+ ON l.a = r.a OR l.b = r.b GROUP BY r.id"""
+ order_qt_aggregate_disabled """SELECT /*+
SET_VAR(disable_nereids_rules='OR_EXPANSION') */
+ r.id, COUNT(l.id), SUM(l.b), SUM(r.v)
+ FROM or_expansion_right_join_l l RIGHT OUTER JOIN
or_expansion_right_join_r r
+ ON l.a = r.a OR l.b = r.b GROUP BY r.id"""
+
+ // Test empty inputs on each side while keeping an equijoin OR predicate.
+ for (String joinType : ["RIGHT OUTER", "RIGHT ANTI"]) {
+ for (String emptySide : ["l", "r"]) {
+ String left = emptySide == "l"
+ ? "(SELECT * FROM or_expansion_right_join_l WHERE id < 0)"
: "or_expansion_right_join_l"
+ String right = emptySide == "r"
+ ? "(SELECT * FROM or_expansion_right_join_r WHERE id < 0)"
: "or_expansion_right_join_r"
+ String query = """SELECT %s * FROM ${left} l ${joinType} JOIN
${right} r
+ ON l.a = r.a OR l.b = r.b"""
+ order_qt_empty_enabled String.format(query, "")
+ order_qt_empty_disabled String.format(query, "/*+
SET_VAR(disable_nereids_rules='OR_EXPANSION') */")
+ }
+ }
+}
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]