rubenada commented on a change in pull request #2329:
URL: https://github.com/apache/calcite/pull/2329#discussion_r561680662
##########
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;
Review comment:
It's a good idea, I'll work on that.
##########
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()) {
+ return;
+ }
+
+ final Union union = call.rel(1);
+ final int unionInputsSize = union.getInputs().size();
+ if (unionInputsSize < 2) {
+ return;
+ }
+
+ // Push down sort limit, if possible.
+ RexNode inputFetch = null;
+ if (sort.fetch != null) {
+ if (sort.offset == null) {
+ inputFetch = sort.fetch;
+ } else if (sort.fetch instanceof RexLiteral && sort.offset instanceof
RexLiteral) {
+ inputFetch = call.builder().literal(
+ RexLiteral.intValue(sort.fetch) +
RexLiteral.intValue(sort.offset));
+ }
+ }
+
+ final List<RelNode> inputs = new ArrayList<>(unionInputsSize);
+ for (RelNode input : union.getInputs()) {
+ final RelNode newInput = sort.copy(sort.getTraitSet(), input, collation,
null, inputFetch);
Review comment:
Each Sort has a different input (each input from the union)
##########
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()) {
+ return;
+ }
+
+ final Union union = call.rel(1);
+ final int unionInputsSize = union.getInputs().size();
+ if (unionInputsSize < 2) {
+ return;
+ }
+
+ // Push down sort limit, if possible.
+ RexNode inputFetch = null;
+ if (sort.fetch != null) {
+ if (sort.offset == null) {
+ inputFetch = sort.fetch;
+ } else if (sort.fetch instanceof RexLiteral && sort.offset instanceof
RexLiteral) {
+ inputFetch = call.builder().literal(
+ RexLiteral.intValue(sort.fetch) +
RexLiteral.intValue(sort.offset));
+ }
+ }
+
+ final List<RelNode> inputs = new ArrayList<>(unionInputsSize);
+ for (RelNode input : union.getInputs()) {
+ final RelNode newInput = sort.copy(sort.getTraitSet(), input, collation,
null, inputFetch);
+ inputs.add(
+ convert(newInput,
newInput.getTraitSet().replace(EnumerableConvention.INSTANCE)));
+ }
+
+ RelNode result = EnumerableMergeUnion.create(sort.getCollation(), inputs,
union.all);
+
+ // If Sort contained a LIMIT / OFFSET, then put it back as an
EnumerableLimit.
+ // The output of the MergeUnion is already sorted, so we do not need a
sort anymore.
+ if (sort.offset != null || sort.fetch != null) {
+ result = EnumerableLimit.create(result, sort.offset, sort.fetch);
Review comment:
This is already taken care of by E`numerableLimit#create` method, which
calls `RelMdCollation.limit(mq, input)` (which just takes the collation from
the limit's input).
##########
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;
Review comment:
Optimization committed
##########
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:
If I don't annotate the TKey I get the following error:
````
error: [argument.type.incompatible] incompatible argument for parameter arg0
of compare.
return this.sortComparator.compare(key1, key2);
^
found : TKey[ extends @Initialized @Nullable Object super @Initialized
@Nullable Void]
required: TKey[ extends @Initialized @Nullable Object super @Initialized
@NonNull Void]
```
How should I annotate the TKey?
##########
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:
If I don't annotate the TKey I get the following error:
```
error: [argument.type.incompatible] incompatible argument for parameter arg0
of compare.
return this.sortComparator.compare(key1, key2);
^
found : TKey[ extends @Initialized @Nullable Object super @Initialized
@Nullable Void]
required: TKey[ extends @Initialized @Nullable Object super @Initialized
@NonNull Void]
```
How should I annotate the TKey?
##########
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:
No. CheckerFramework flags `wrapper.apply` as a possible NPE because
`wrapper` can be theoretically null. However, `wrapper` is null only when
`processed` is null (and vice-versa), and since the method checks for
`processed` nullability at the beginning, we can never get a NPE on
`wrapper.apply`
##########
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:
Yes, this is about `initEnumerators`:
```
error: [method.invocation.invalid] call to initEnumerators() not allowed on
the given receiver.
this.initEnumerators();
^
found :
@UnderInitialization(org.apache.calcite.linq4j.EnumerableDefaults.MergeUnionEnumerator.class)
@NonNull MergeUnionEnumerator
required: @Initialized @NonNull MergeUnionEnumerator
```
Sorry, I did not understand your problem, how should I fix it?
##########
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:
Yes, this is about `initEnumerators`:
```
error: [method.invocation.invalid] call to initEnumerators() not allowed on
the given receiver.
this.initEnumerators();
^
found :
@UnderInitialization(org.apache.calcite.linq4j.EnumerableDefaults.MergeUnionEnumerator.class)
@NonNull MergeUnionEnumerator
required: @Initialized @NonNull MergeUnionEnumerator
```
Sorry, I did not understand your suggestion, how should I fix it?
##########
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>
Review comment:
Agree, I'll move to a separate file once the other discussions get
resolved.
##########
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:
I fear that you suggestion might trigger a NPE inside
`sortKeySelector.apply` if we pass a null element e1/e2.
BTW `sortComparator.compare` should be able to handle (in some cases) null
keys (e.g. when we have nulls first or nulls last, and the comparator must
handle nulls accordingly when compared to a non-null 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(
Review comment:
I understand. The complication is that this `sortKeySelector` is / can
be created by dynamic code (`PhysTpe#generateCollationKey`), and (it's not so
easy to guess) I believe a null in there can lead to a NPE.
I have committed a new workaround based on
`@SuppressWarnings("argument.type.incompatible")`
##########
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")
Review comment:
Done
##########
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:
Done
##########
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:
Done
##########
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:
You're right, in other parts of `EnumerableDefaults` using
`Function1<TSource, TKey> keySelector` there is no null check before calling
`keySelector.apply`, I'll remove the null handling here.
##########
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,
Review comment:
Reviewed
##########
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:
Change committed. Thanks for your input @vlsi
##########
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:
matches method overridden with checks
##########
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:
exception message improved
----------------------------------------------------------------
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]