tanclary commented on code in PR #3367:
URL: https://github.com/apache/calcite/pull/3367#discussion_r1306863310


##########
core/src/test/java/org/apache/calcite/test/RelOptRulesTest.java:
##########
@@ -2699,6 +2699,35 @@ private void 
checkPushJoinThroughUnionOnRightDoesNotMatchSemiOrAntiJoin(JoinRelT
         .check();
   }
 
+  /** Tests {@link org.apache.calcite.rel.rules.MinusToDistinctRule},
+   * which rewrites an {@link Minus} operator with 3 inputs. */
+  @Test void testMinusToDistinct() {
+    final String sql = "select EMPNO,ENAME,JOB from emp where deptno = 10\n"
+        + "except\n"
+        + "select EMPNO,ENAME,JOB from emp where deptno = 20\n"
+        + "except\n"
+        + "select EMPNO,ENAME,JOB from emp where deptno = 30\n";
+    sql(sql)
+        .withRule(CoreRules.MINUS_MERGE,
+            CoreRules.MINUS_TO_DISTINCT)
+        .check();
+  }
+
+  /** Tests {@link org.apache.calcite.rel.rules.MinusToDistinctRule},
+   *  correctly ignores an {@code EXCEPT ALL}. It can only handle
+   *    * {@code EXCEPT DISTINCT}.*/

Review Comment:
   Is this comment formatted incorrectly? Looks like there is an extra * and 
could use a space at the end



##########
core/src/main/java/org/apache/calcite/rel/rules/MinusToDistinctRule.java:
##########
@@ -0,0 +1,179 @@
+/*
+ * 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.calcite.rel.rules;
+
+import org.apache.calcite.plan.RelOptCluster;
+import org.apache.calcite.plan.RelOptRuleCall;
+import org.apache.calcite.plan.RelRule;
+import org.apache.calcite.rel.RelNode;
+import org.apache.calcite.rel.core.Minus;
+import org.apache.calcite.rel.logical.LogicalMinus;
+import org.apache.calcite.rex.RexBuilder;
+import org.apache.calcite.rex.RexNode;
+import org.apache.calcite.sql.SqlOperator;
+import org.apache.calcite.sql.fun.SqlStdOperatorTable;
+import org.apache.calcite.tools.RelBuilder;
+import org.apache.calcite.tools.RelBuilderFactory;
+import org.apache.calcite.util.ImmutableBitSet;
+import org.apache.calcite.util.Util;
+
+import com.google.common.collect.ImmutableList;
+
+import org.immutables.value.Value;
+
+import java.math.BigDecimal;
+
+/**
+ * Planner rule that translates a distinct
+ * {@link org.apache.calcite.rel.core.Minus}
+ * (<code>all</code> = <code>false</code>)
+ * into a group of operators composed of
+ * {@link org.apache.calcite.rel.core.Union},
+ * {@link org.apache.calcite.rel.core.Aggregate},
+ * {@link org.apache.calcite.rel.core.Filter},etc.
+ *
+ * <p>For example, the query
+
+ * <blockquote><pre>{@code
+ *  select a,b from t1
+ *   except
+ *  select a,b from t2
+ *   except
+ *  select a,b from t3
+ * }</pre></blockquote>
+ *
+ * <p> will convert to
+ *
+ * <blockquote><pre>{@code
+ *  select a,b
+ *  from (select a,b,0 as m from t1
+ *  union all
+ *  select a,b,1 as m from t2
+ *  union all
+ *  select a,b,2 as m from t3)
+ *  group by a,b
+ *  having count(*) filter (where m = 0) > 0
+ *   and count(*) filter (where m = 1) = 0
+ *   and count(*) filter (where m = 2) = 0
+ * }</pre></blockquote>
+ *
+ * @see CoreRules#MINUS_TO_DISTINCT
+ */
[email protected]
+public class MinusToDistinctRule
+    extends RelRule<MinusToDistinctRule.Config>
+    implements TransformationRule {
+
+  protected MinusToDistinctRule(Config config) {
+    super(config);
+  }
+
+  @Deprecated // to be removed before 2.0
+  public MinusToDistinctRule(Class<? extends Minus> minusClass,
+      RelBuilderFactory relBuilderFactory) {
+    
this(MinusToDistinctRule.Config.DEFAULT.withRelBuilderFactory(relBuilderFactory)
+        .as(MinusToDistinctRule.Config.class)
+        .withOperandFor(minusClass));
+  }
+
+  @Override public void onMatch(RelOptRuleCall call) {
+    Minus minus = call.rel(0);
+
+    if (minus.all) {
+      // Nothing we can do
+      return;
+    }
+
+    final RelOptCluster cluster = minus.getCluster();
+    final RelBuilder relBuilder = call.builder();
+    final RexBuilder rexBuilder = cluster.getRexBuilder();
+    final int branchCount = minus.getInputs().size();
+
+    // For each child branch in minus,add a column which indicates branch index
+    // e.g. select EMPNO from emp -> select EMPNO,0 from emp
+    // 0 indicates that it comes from minus the first child branch
+    for (int i = 0; i < branchCount; i++) {
+      relBuilder.push(minus.getInput(i));
+      relBuilder.projectPlus(relBuilder.literal(new BigDecimal(i)));
+    }
+
+    // create a union above all the branches
+    relBuilder.union(true, branchCount);
+
+    final RelNode union = relBuilder.peek();
+    final int originalFieldCnt = union.getRowType().getFieldCount() - 1;
+
+    ImmutableList.Builder<RexNode> projects = ImmutableList.builder();
+    // skip the branch index column
+    projects.addAll(Util.first(relBuilder.fields(), originalFieldCnt));
+
+    // On top of the Union, add a Project and add branch cnt number boolean 
columns
+    // e.g. LogicalProject(EMPNO=[$0], $f1=[=($1, 0)], $f2=[=($1, 1)], 
$f3=[=($1, 2)])
+    // $f1,$f2,$f3 are the boolean indicate whether it comes from the 
corresponding branch
+    for (int i = 0; i < branchCount; i++) {
+      projects.add(
+          relBuilder.equals(relBuilder.field(originalFieldCnt),
+              relBuilder.literal(new BigDecimal(i))));
+    }
+
+    relBuilder.project(projects.build());
+
+    // Add the count(*) filter $f1(..) for each branch
+    ImmutableList.Builder<RelBuilder.AggCall> aggCalls = 
ImmutableList.builder();
+    for (int i = 0; i < branchCount; i++) {
+      
aggCalls.add(relBuilder.countStar(null).filter(relBuilder.field(originalFieldCnt
 + i)));
+    }

Review Comment:
   Is there anyway to combine these `for` loops? I noticed we iterate through 
the branch count multiple times.



##########
core/src/test/java/org/apache/calcite/test/RelOptRulesTest.java:
##########
@@ -2699,6 +2699,35 @@ private void 
checkPushJoinThroughUnionOnRightDoesNotMatchSemiOrAntiJoin(JoinRelT
         .check();
   }
 
+  /** Tests {@link org.apache.calcite.rel.rules.MinusToDistinctRule},

Review Comment:
   +1, also wondering



-- 
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.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to