vlsi commented on a change in pull request #2329:
URL: https://github.com/apache/calcite/pull/2329#discussion_r561920915



##########
File path: 
linq4j/src/main/java/org/apache/calcite/linq4j/EnumerableDefaults.java
##########
@@ -4683,4 +4683,191 @@ private void flush() {
       }
     };
   }
+
+  /**
+   * Merge Union Enumerable.
+   * Performs a union (or union all) of all its inputs (which must be already 
sorted),
+   * respecting the order.
+   *
+   * @param sources input enumerables (must be already sorted)
+   * @param sortKeySelector sort key selector
+   * @param sortComparator sort comparator to decide the next item
+   * @param all whether duplicates will be considered or not
+   * @param equalityComparer {@link EqualityComparer} to control duplicates,
+   *                         only used if {@code all} is {@code false}
+   * @param <TSource> record type
+   * @param <TKey> sort key
+   */
+  public static <TSource, @Nullable TKey> Enumerable<TSource> mergeUnion(
+      List<Enumerable<TSource>> sources,
+      Function1<TSource, @Nullable TKey> sortKeySelector,
+      Comparator<TKey> sortComparator,
+      boolean all,
+      EqualityComparer<TSource> equalityComparer) {
+    return new AbstractEnumerable<TSource>() {
+      @Override public Enumerator<TSource> enumerator() {
+        return new MergeUnionEnumerator<>(
+            sources,
+            sortKeySelector,
+            sortComparator,
+            all,
+            equalityComparer);
+      }
+    };
+  }
+
+  /**
+   * Performs a union (or union all) of all its inputs (which must be already 
sorted),
+   * respecting the order.
+   * @param <TSource> record type
+   * @param <TKey> sort key
+   */
+  @SuppressWarnings("unchecked")
+  private static class MergeUnionEnumerator<TSource, @Nullable TKey>
+      implements Enumerator<TSource> {
+    private final List<Enumerator<TSource>> inputs;
+    private final TSource[] currentInputsValues;
+    private final Function1<TSource, @Nullable TKey> sortKeySelector;
+    private final Comparator<@Nullable TKey> sortComparator;
+    private TSource currentValue;
+    private int activeInputs;
+
+    // Set to control duplicates, only used if "all" is false
+    private final @Nullable Set<Wrapped<TSource>> processed;
+    private final @Nullable Function1<TSource, Wrapped<TSource>> wrapper;
+
+    private static final Object NOT_INIT = new Object();
+    private static final Object FINISHED = new Object();
+
+    @SuppressWarnings("method.invocation.invalid")
+    private MergeUnionEnumerator(
+        List<Enumerable<TSource>> sources,
+        Function1<TSource, @Nullable TKey> sortKeySelector,
+        Comparator<@Nullable TKey> sortComparator,
+        boolean all,
+        EqualityComparer<TSource> equalityComparer) {
+      this.sortKeySelector = sortKeySelector;
+      this.sortComparator = sortComparator;
+
+      if (all) {
+        this.processed = null;
+        this.wrapper = null;
+      } else {
+        this.processed = new HashSet<>();
+        this.wrapper = wrapperFor(equalityComparer);
+      }
+
+      final int size = sources.size();
+      this.inputs = new ArrayList<>(size);
+      for (Enumerable<TSource> source : sources) {
+        this.inputs.add(source.enumerator());
+      }
+
+      this.currentInputsValues = (TSource[]) new Object[size];
+      this.activeInputs = this.currentInputsValues.length;
+      this.currentValue = (TSource) NOT_INIT;
+
+      this.initEnumerators();
+    }
+
+    private void initEnumerators() {
+      for (int i = 0; i < this.inputs.size(); i++) {
+        this.moveEnumerator(i);
+      }
+    }
+
+    private void moveEnumerator(int i) {
+      final Enumerator<TSource> enumerator = this.inputs.get(i);
+      if (!enumerator.moveNext()) {
+        this.activeInputs--;
+        this.currentInputsValues[i] = (TSource) FINISHED;
+      } else {
+        this.currentInputsValues[i] = enumerator.current();
+      }
+    }
+
+    @SuppressWarnings("dereference.of.nullable")

Review comment:
       If you intend to suppress a single case only, please use 
`SuppressWarnings` for a local variable declaration like in
   
   ```java
   @SuppressWarnings("dereference.of.nullable")
   final Wrapped<TSource> wrapped = this.wrapper.apply(value);
   ```
   
   

##########
File path: 
linq4j/src/main/java/org/apache/calcite/linq4j/EnumerableDefaults.java
##########
@@ -4683,4 +4683,191 @@ private void flush() {
       }
     };
   }
+
+  /**
+   * Merge Union Enumerable.
+   * Performs a union (or union all) of all its inputs (which must be already 
sorted),
+   * respecting the order.
+   *
+   * @param sources input enumerables (must be already sorted)
+   * @param sortKeySelector sort key selector
+   * @param sortComparator sort comparator to decide the next item
+   * @param all whether duplicates will be considered or not
+   * @param equalityComparer {@link EqualityComparer} to control duplicates,
+   *                         only used if {@code all} is {@code false}
+   * @param <TSource> record type
+   * @param <TKey> sort key
+   */
+  public static <TSource, @Nullable TKey> Enumerable<TSource> mergeUnion(
+      List<Enumerable<TSource>> sources,
+      Function1<TSource, @Nullable TKey> sortKeySelector,
+      Comparator<TKey> sortComparator,
+      boolean all,
+      EqualityComparer<TSource> equalityComparer) {
+    return new AbstractEnumerable<TSource>() {
+      @Override public Enumerator<TSource> enumerator() {
+        return new MergeUnionEnumerator<>(
+            sources,
+            sortKeySelector,
+            sortComparator,
+            all,
+            equalityComparer);
+      }
+    };
+  }
+
+  /**
+   * Performs a union (or union all) of all its inputs (which must be already 
sorted),
+   * respecting the order.
+   * @param <TSource> record type
+   * @param <TKey> sort key
+   */
+  @SuppressWarnings("unchecked")
+  private static class MergeUnionEnumerator<TSource, @Nullable TKey>
+      implements Enumerator<TSource> {
+    private final List<Enumerator<TSource>> inputs;
+    private final TSource[] currentInputsValues;
+    private final Function1<TSource, @Nullable TKey> sortKeySelector;
+    private final Comparator<@Nullable TKey> sortComparator;
+    private TSource currentValue;
+    private int activeInputs;
+
+    // Set to control duplicates, only used if "all" is false
+    private final @Nullable Set<Wrapped<TSource>> processed;
+    private final @Nullable Function1<TSource, Wrapped<TSource>> wrapper;
+
+    private static final Object NOT_INIT = new Object();
+    private static final Object FINISHED = new Object();
+
+    @SuppressWarnings("method.invocation.invalid")

Review comment:
       In general,`suppressions` should be targeted. If you add 
`SuppressWarnings` to the full constructor, it might allow unexpected warnings 
to creep in.
   
   In other words, suppressions should be confined to their minimal scope.
   
   For instance,
   
   ```java
       @RequiresNonNull("inputs")
       @SuppressWarnings("method.invocation.invalid")
       private void initEnumerators(
           EnumerableDefaults.@UnknownInitialization 
MergeUnionEnumerator<TSource, TKey> this
       ) {
         for (int i = 0; i < this.inputs.size(); i++) {
           this.moveEnumerator(i);
         }
       }
   ```

##########
File path: 
linq4j/src/main/java/org/apache/calcite/linq4j/EnumerableDefaults.java
##########
@@ -4683,4 +4683,191 @@ private void flush() {
       }
     };
   }
+
+  /**
+   * Merge Union Enumerable.
+   * Performs a union (or union all) of all its inputs (which must be already 
sorted),
+   * respecting the order.
+   *
+   * @param sources input enumerables (must be already sorted)
+   * @param sortKeySelector sort key selector
+   * @param sortComparator sort comparator to decide the next item
+   * @param all whether duplicates will be considered or not
+   * @param equalityComparer {@link EqualityComparer} to control duplicates,
+   *                         only used if {@code all} is {@code false}
+   * @param <TSource> record type
+   * @param <TKey> sort key
+   */
+  public static <TSource, @Nullable TKey> Enumerable<TSource> mergeUnion(

Review comment:
       ```java
       private int compare(TSource e1, TSource e2) {
         final TKey key1 = e1 == null ? null : this.sortKeySelector.apply(e1);
         final TKey key2 = e2 == null ? null : this.sortKeySelector.apply(e2);
         return this.sortComparator.compare(key1, key2);
       }
   ```
   
   Ok, what does the error mean here?
   It says that the comparison key can become `null` even in the case 
`sortKeySelector` never returns nulls. I believe if the user passes 
`sortKeySelector` which never returns nulls, they won't expect that 
`mergeUnion` would silently skip `keySelector`.
   
   Unfortunately, you do not declare the behavior with regards to the `null` 
values for `TSource` elements in `List<Enumerable<TSource>> sources`.
   
   ---
   
   I believe the way to fix this is to remove custom `null` handling and just 
pass the keys to `sortKeySelector` as is:
   
   ```java
       private int compare(TSource e1, TSource e2) {
         final TKey key1 = this.sortKeySelector.apply(e1);
         final TKey key2 = this.sortKeySelector.apply(e2);
         return this.sortComparator.compare(key1, key2);
       }
   ```
   

##########
File path: 
linq4j/src/main/java/org/apache/calcite/linq4j/EnumerableDefaults.java
##########
@@ -4683,4 +4683,191 @@ private void flush() {
       }
     };
   }
+
+  /**
+   * Merge Union Enumerable.
+   * Performs a union (or union all) of all its inputs (which must be already 
sorted),
+   * respecting the order.
+   *
+   * @param sources input enumerables (must be already sorted)
+   * @param sortKeySelector sort key selector
+   * @param sortComparator sort comparator to decide the next item
+   * @param all whether duplicates will be considered or not
+   * @param equalityComparer {@link EqualityComparer} to control duplicates,
+   *                         only used if {@code all} is {@code false}
+   * @param <TSource> record type
+   * @param <TKey> sort key
+   */
+  public static <TSource, @Nullable TKey> Enumerable<TSource> mergeUnion(

Review comment:
       Currently you declare `sortKeySelector` as `Function1<TSource, TKey> 
sortKeySelector`.
   In other words, it **must** work for all `TSource` values no matter if 
`TSource` is null or not.
   
   On the other hand, if you implement custom `null` behavior, you basically 
augment user-provided `sortKeySelector`, and you basically forbid users to 
handle `nulls` differently.
   
   I believe this silent implementation detail is worse than a clear NPE in 
case the user-provided function fails to handle nulls.

##########
File path: 
linq4j/src/main/java/org/apache/calcite/linq4j/EnumerableDefaults.java
##########
@@ -4683,4 +4683,191 @@ private void flush() {
       }
     };
   }
+
+  /**
+   * Merge Union Enumerable.
+   * Performs a union (or union all) of all its inputs (which must be already 
sorted),
+   * respecting the order.
+   *
+   * @param sources input enumerables (must be already sorted)
+   * @param sortKeySelector sort key selector
+   * @param sortComparator sort comparator to decide the next item
+   * @param all whether duplicates will be considered or not
+   * @param equalityComparer {@link EqualityComparer} to control duplicates,
+   *                         only used if {@code all} is {@code false}
+   * @param <TSource> record type
+   * @param <TKey> sort key
+   */
+  public static <TSource, @Nullable TKey> Enumerable<TSource> mergeUnion(

Review comment:
       > and (it's not so easy to guess) I believe a null in there can lead to 
a NPE.
   
   `linq4j` is a general-purpose library, and it must not depend on `PhysType` 
quirks

##########
File path: 
linq4j/src/main/java/org/apache/calcite/linq4j/EnumerableDefaults.java
##########
@@ -4683,4 +4683,191 @@ private void flush() {
       }
     };
   }
+
+  /**
+   * Merge Union Enumerable.
+   * Performs a union (or union all) of all its inputs (which must be already 
sorted),
+   * respecting the order.
+   *
+   * @param sources input enumerables (must be already sorted)
+   * @param sortKeySelector sort key selector
+   * @param sortComparator sort comparator to decide the next item
+   * @param all whether duplicates will be considered or not
+   * @param equalityComparer {@link EqualityComparer} to control duplicates,
+   *                         only used if {@code all} is {@code false}
+   * @param <TSource> record type
+   * @param <TKey> sort key
+   */
+  public static <TSource, @Nullable TKey> Enumerable<TSource> mergeUnion(

Review comment:
       The problem with `e1 == null ? null` is that behavior is not documented, 
and it is not tested (there's no test which checks what happens in case 
user-provided `keySelector` wants to convert `null` to something non-`null`).
   
   `mergeUnion` method is already very generic (it has customization for 
`keySelector`, `comparator`), so I see no reasons why the method should have 
its own `null-handling`. It is generic enough to let users decide what they 
want to do with nulls.

##########
File path: 
core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableMergeUnion.java
##########
@@ -0,0 +1,118 @@
+/*
+ * 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.adapter.enumerable;
+
+import org.apache.calcite.linq4j.Ord;
+import org.apache.calcite.linq4j.tree.BlockBuilder;
+import org.apache.calcite.linq4j.tree.Expression;
+import org.apache.calcite.linq4j.tree.Expressions;
+import org.apache.calcite.linq4j.tree.ParameterExpression;
+import org.apache.calcite.plan.RelOptCluster;
+import org.apache.calcite.plan.RelTraitSet;
+import org.apache.calcite.rel.RelCollation;
+import org.apache.calcite.rel.RelCollations;
+import org.apache.calcite.rel.RelNode;
+import org.apache.calcite.util.BuiltInMethod;
+import org.apache.calcite.util.Pair;
+import org.apache.calcite.util.Util;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/** Implementation of {@link org.apache.calcite.rel.core.Union} in
+ * {@link org.apache.calcite.adapter.enumerable.EnumerableConvention 
enumerable calling convention}.
+ * Performs a union (or union all) of all its inputs (which must be already 
sorted),
+ * respecting the order. */
+public class EnumerableMergeUnion extends EnumerableUnion {
+
+  protected EnumerableMergeUnion(RelOptCluster cluster, RelTraitSet traitSet, 
List<RelNode> inputs,
+      boolean all) {
+    super(cluster, traitSet, inputs, all);
+    final RelCollation collation = traitSet.getCollation();
+    if (collation == null || collation == RelCollations.EMPTY) {
+      throw new IllegalArgumentException("EnumerableMergeUnion with no 
collation");
+    }
+    for (RelNode input : inputs) {
+      final RelCollation inputCollation = input.getTraitSet().getCollation();
+      if (inputCollation == null || !inputCollation.satisfies(collation)) {
+        throw new IllegalArgumentException("EnumerableMergeUnion input does 
not satisfy collation "
+            + input);

Review comment:
       It would probably help if both collations were included to the exception 
message

##########
File path: 
core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableMergeUnionRule.java
##########
@@ -0,0 +1,97 @@
+/*
+ * 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.adapter.enumerable;
+
+import org.apache.calcite.plan.RelOptRuleCall;
+import org.apache.calcite.plan.RelRule;
+import org.apache.calcite.rel.RelCollation;
+import org.apache.calcite.rel.RelNode;
+import org.apache.calcite.rel.core.Sort;
+import org.apache.calcite.rel.core.Union;
+import org.apache.calcite.rel.logical.LogicalSort;
+import org.apache.calcite.rel.logical.LogicalUnion;
+import org.apache.calcite.rex.RexLiteral;
+import org.apache.calcite.rex.RexNode;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Rule to convert a {@link org.apache.calcite.rel.logical.LogicalSort} on top 
of a
+ * {@link org.apache.calcite.rel.logical.LogicalUnion} into a {@link 
EnumerableMergeUnion}.
+ *
+ * @see EnumerableRules#ENUMERABLE_MERGE_UNION_RULE
+ */
+public class EnumerableMergeUnionRule extends 
RelRule<EnumerableMergeUnionRule.Config> {
+
+  /** Rule configuration. */
+  public interface Config extends RelRule.Config {
+    Config DEFAULT_CONFIG = 
EMPTY.withDescription("EnumerableMergeUnionRule").withOperandSupplier(
+        b0 -> b0.operand(LogicalSort.class).oneInput(
+            b1 -> 
b1.operand(LogicalUnion.class).anyInputs())).as(Config.class);
+
+    @Override default EnumerableMergeUnionRule toRule() {
+      return new EnumerableMergeUnionRule(this);
+    }
+  }
+
+  public EnumerableMergeUnionRule(Config config) {
+    super(config);
+  }
+
+  @Override public void onMatch(RelOptRuleCall call) {
+    final Sort sort = call.rel(0);
+    final RelCollation collation = sort.getCollation();
+    if (collation == null || collation.getFieldCollations().isEmpty()) {

Review comment:
       Could you please move the checks to `matches` method or to the rule 
definition?
   
   Currently, the engine has to remember the rule match, execute it and only 
then it figures out the execution was useless (e.g. no collation).




----------------------------------------------------------------
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:
[email protected]


Reply via email to