asolimando commented on code in PR #5031:
URL: https://github.com/apache/calcite/pull/5031#discussion_r4481530346
##########
core/src/main/java/org/apache/calcite/util/BuiltInMethod.java:
##########
@@ -340,10 +340,9 @@ public enum BuiltInMethod {
@SuppressWarnings("deprecation")
PAIR_LIST_COPY_OF(PairList.Helper.class, "copyOf", Object.class,
Object.class,
Object[].class),
- FLAT_ZIP(SqlFunctions.class, "flatZip", int[].class, boolean.class,
- FlatProductInputType[].class, boolean.class),
- FLAT_LIST(SqlFunctions.class, "flatList"),
- FLAT_LIST_OUTER(SqlFunctions.class, "flatListOuter"),
+ FLAT_UNCOLLECT(SqlFunctions.class, "flatUncollect", int[].class, int[].class,
Review Comment:
Removing `SqlFunctions.flatList()` and `BuiltInMethod.FLAT_LIST` is a
breaking change, as both are public in 1.42.0. If we can't keep them as
deprecated, we should at least mark the PR as carrying a breaking change (there
is a label both in GitHub and Jira to ease compiling release notes, and we need
an entry in the file tracking breaking changes too).
##########
core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableUncollect.java:
##########
@@ -164,13 +162,22 @@ public static EnumerableUncollect create(RelTraitSet
traitSet, RelNode input,
}
}
- final Expression lambda = lambdaForStructWithSingleItem != null
- ? lambdaForStructWithSingleItem
- : Expressions.call(BuiltInMethod.FLAT_ZIP.method,
- Expressions.constant(Ints.toArray(fieldCounts)),
- Expressions.constant(withOrdinality),
+ final Expression child_ = builder.append("child", childResult.block);
Review Comment:
With `topDownGeneralDecorrelationEnabled=true`, `select *` over a reflective
table followed by `UNNEST` fails, because `EnumerableUncollect` is placed
directly over `EnumerableTableScan`:
```
EnumerableUncollect(passthrough=[[deptno, name, employees, location]],
collectionFields=[[employees]])
EnumerableTableScan(table=[[hr, depts]])
```
The scan returns rows in CUSTOM format (Java objects), but `rowToList`
treats a row that is neither a `List` nor an `Object[]` as a single field, so
reading the next input field fails.
Reproducer (for `JdbcTest`):
```java
@Test void testUncollectPassthroughOverReflectiveScan() {
final String sql = "select *\n"
+ "from \"hr\".\"depts\" d, unnest(d.\"employees\") as e";
CalciteAssert.hr()
.with(CalciteConnectionProperty.TOPDOWN_GENERAL_DECORRELATION_ENABLED, true)
.query(sql)
.returnsCount(3);
}
```
The test currently fails as follows:
```
Caused by: java.lang.IndexOutOfBoundsException: Index: 2, Size: 1
at
org.apache.calcite.runtime.SqlFunctions.lambda$flatUncollectRows$0(SqlFunctions.java:8075)
```
With the property set to false, the query returns 3 rows. On the base commit
of this PR (a7f3290), the test passes with the property set to true. A query
that selects fewer columns, such as `select d."deptno", e."empid"`, does not
fail: an `EnumerableCalc` between the scan and `EnumerableUncollect` then
produces array rows.
It's been a while since the last time I took a look at reflective tables,
but I think the input rows should probably be converted using the input's
`PhysType`.
##########
core/src/main/java/org/apache/calcite/rel/rel2sql/RelToSqlConverter.java:
##########
@@ -1686,6 +1708,54 @@ public Result visit(Uncollect e) {
return result(asNode, ImmutableList.of(Clause.FROM), e, null);
}
+ /**
+ * Rewrites a generalized {@link Uncollect} (passthrough fields, a subset of
+ * collection fields, or outer semantics) into the equivalent
+ * {@code Project(Correlate(input, Uncollect(Project($cor.c...))))}.
+ * This is the inverse of
+ * {@link org.apache.calcite.rel.rules.CoreRules#CORRELATE_UNCOLLECT_MERGE}.
+ */
+ private static RelNode generalizedUncollectToCorrelate(Uncollect e) {
+ final RelOptCluster cluster = e.getCluster();
+ final RexBuilder rexBuilder = cluster.getRexBuilder();
+ final RelNode input = e.getInput();
+ final int inputFieldCount = input.getRowType().getFieldCount();
+
+ final CorrelationId corrId = cluster.createCorrel();
+ final RexNode corr = rexBuilder.makeCorrel(input.getRowType(), corrId);
+ final List<RexNode> collectionExprs = new ArrayList<>();
+ final List<String> collectionNames = new ArrayList<>();
+ for (int i : e.getCollectionFieldIndices()) {
+ collectionExprs.add(rexBuilder.makeFieldAccess(corr, i));
+ collectionNames.add(input.getRowType().getFieldList().get(i).getName());
+ }
+ final RelNode innerProject =
+ LogicalProject.create(LogicalValues.createOneRow(cluster),
+ ImmutableList.of(), collectionExprs, collectionNames,
+ ImmutableSet.of());
+ final Uncollect plainUncollect =
+ Uncollect.create(e.getTraitSet(), innerProject, e.withOrdinality,
Review Comment:
With PRESTO conformance, `UNNEST` keeps each element of an `ARRAY<ROW(X,
Y)>` as one ROW column (honoring `expandStructFields=false`). For example, for
the row `ID = 1, ITEMS = [ROW(1, 2), ROW(3, 4)]`:
```sql
select t.id, r
from s.t2 as t, unnest(t.items) with ordinality as r
```
returns `(1, ROW(ROW(1, 2), 1))` and `(1, ROW(ROW(3, 4), 2))`.
With `topDownGeneralDecorrelationEnabled=true`, the plan before conversion
is correct:
```
LogicalProject(ID=[$0], R=[ROW($1, $2)])
Uncollect(passthrough=[[ID]], collectionFields=[[ITEMS]],
withOrdinality=[true], expandStructFields=[false])
LogicalTableScan(table=[[S, T2]])
```
`generalizedUncollectToCorrelate` rebuilds a classic `Uncollect` with empty
item aliases, so its constructor sets `expandStructFields=true`
(`Uncollect.java:122`). The converter then treats the `UNNEST` output as `(X,
Y, ORDINALITY)` instead of `(element, ORDINALITY)`, and `ROW($1, $2)` selects
`X` and `Y`:
```
SELECT "$cor1"."ID", ROW("t00"."X", "t00"."Y") AS "R"
FROM "S"."T2" AS "$cor1",
LATERAL UNNEST((SELECT "$cor1"."ITEMS"
FROM (VALUES (0)) AS "t" ("ZERO"))) WITH ORDINALITY AS "t00" ("X", "Y",
"ORDINALITY")
```
The ordinality is lost, and the SQL is invalid: with PRESTO conformance,
this `UNNEST` returns 2 columns, but the SQL has 3 aliases.
Reproducer (for `RelToSqlConverterTest`):
```java
@Test void testGeneralizedUncollectUnexpandedStruct() throws Exception {
final SchemaPlus rootSchema = Frameworks.createRootSchema(true);
rootSchema.add("S", new AbstractSchema()).add("T2", new AbstractTable() {
@Override public RelDataType getRowType(RelDataTypeFactory tf) {
final RelDataType row = tf.builder()
.add("X", tf.createSqlType(SqlTypeName.INTEGER))
.add("Y", tf.createSqlType(SqlTypeName.INTEGER))
.kind(StructKind.PEEK_FIELDS)
.build();
return tf.builder()
.add("ID", tf.createSqlType(SqlTypeName.INTEGER))
.add("ITEMS", tf.createArrayType(row, -1))
.build();
}
});
final Properties props = new Properties();
props.setProperty(CalciteConnectionProperty.CONFORMANCE.camelName(),
"PRESTO");
props.setProperty(
CalciteConnectionProperty.TOPDOWN_GENERAL_DECORRELATION_ENABLED.camelName(),
"true");
final CalciteConnectionConfigImpl connConfig = new
CalciteConnectionConfigImpl(props);
final FrameworkConfig config = Frameworks.newConfigBuilder()
.parserConfig(SqlParser.config().withConformance(connConfig.conformance()))
.defaultSchema(rootSchema)
.context(Contexts.of(connConfig))
.programs(Programs.standard())
.build();
final Planner planner = Frameworks.getPlanner(config);
final String sql = "select t.id, r\n"
+ "from s.t2 as t, unnest(t.items) with ordinality as r";
final RelNode rel =
planner.rel(planner.validate(planner.parse(sql))).project();
final String generated = new RelToSqlConverter(CalciteSqlDialect.DEFAULT)
.visitRoot(rel).asStatement()
.toSqlString(CalciteSqlDialect.DEFAULT).getSql();
// The generated SQL must be valid
final Planner planner2 = Frameworks.getPlanner(config);
planner2.validate(planner2.parse(generated));
}
```
The test currently fails as follows:
```
org.apache.calcite.tools.ValidationException:
org.apache.calcite.runtime.CalciteContextException: From line 4, column 63 to
line 4, column 84: List of column aliases must have same degree as table; table
has 2 columns ('EXPR$0', 'ORDINALITY'), whereas alias list has 3 columns
```
On the base commit of this PR (a7f3290), the test passes: the generated SQL
ends with `AS "t00" ("col_0", "ORDINALITY")`.
To fix this it should be enough to pass the original `expandStructFields`
value to the rebuilt `Uncollect`
##########
core/src/main/java/org/apache/calcite/rel/core/Uncollect.java:
##########
@@ -100,43 +116,86 @@ public Uncollect(RelOptCluster cluster, RelTraitSet
traitSet, RelNode input,
// Non-empty item aliases historically implied that struct elements are not
// expanded (Presto dialect), so this constructor derives
// {@code expandStructFields} from their absence.
- this(cluster, traitSet, input, withOrdinality, itemAliases,
itemAliases.isEmpty(),
- false);
+ this(cluster, traitSet, input, withOrdinality, itemAliases,
+ ImmutableBitSet.of(),
+ ImmutableBitSet.range(input.getRowType().getFieldCount()),
+ itemAliases.isEmpty(), false);
}
- /** Creates an Uncollect.
+ /** Creates an Uncollect, with explicit control over which input fields are
+ * passed through unchanged and which are unnested.
*
- * @param input Input relational expression
- * @param withOrdinality Whether output should contain an ORDINALITY
column
- * @param itemAliases Aliases for the operand items
- * @param expandStructFields If true, a collection whose element type is a
struct
- * produces one output column per struct field; if
false,
- * a single column typed as the whole element
- * @param isOuter If true, an empty or NULL collection yields one
row of
- * NULLs (LEFT JOIN); if false, it yields no rows
(INNER)
+ * @param input Input relational expression
+ * @param withOrdinality Whether output should contain an
ORDINALITY column
+ * @param itemAliases Aliases for the operand items; only
meaningful when
+ * {@code passthroughFieldIndices} is empty
and
+ * {@code collectionFieldIndices} covers
every input field
+ * @param passthroughFieldIndices 0-based indices of the input fields to
pass through
+ * unchanged
+ * @param collectionFieldIndices 0-based indices of the input fields whose
values are
+ * collections to unnest
+ * @param expandStructFields If true, a collection whose element type
is a struct
+ * produces one output column per struct
field; if false,
+ * a single column typed as the whole element
+ * @param isOuter If true, preserves input rows with
null/empty
+ * collections (LEFT JOIN); if false, drops
them (INNER)
*/
@SuppressWarnings("method.invocation.invalid")
public Uncollect(RelOptCluster cluster, RelTraitSet traitSet, RelNode input,
- boolean withOrdinality, List<String> itemAliases, boolean
expandStructFields,
- boolean isOuter) {
+ boolean withOrdinality, List<String> itemAliases,
+ ImmutableBitSet passthroughFieldIndices, ImmutableBitSet
collectionFieldIndices,
+ boolean expandStructFields, boolean isOuter) {
super(cluster, traitSet, input);
this.withOrdinality = withOrdinality;
this.itemAliases = ImmutableList.copyOf(itemAliases);
+ this.passthroughFieldIndices =
+ requireNonNull(passthroughFieldIndices, "passthroughFieldIndices");
+ this.collectionFieldIndices =
+ requireNonNull(collectionFieldIndices, "collectionFieldIndices");
+ if (collectionFieldIndices.isEmpty()) {
+ throw new IllegalArgumentException("collectionFieldIndices must not be
empty");
+ }
this.expandStructFields = expandStructFields;
this.isOuter = isOuter;
requireNonNull(deriveRowType(), "invalid child rowType");
}
/**
* Creates an Uncollect by parsing serialized output.
+ *
+ * <p>Called from {@link org.apache.calcite.rel.externalize.RelJsonReader}
+ * using reflection when deserializing a JSON plan. Reads the attributes that
+ * {@link #explainTerms(RelWriter)} writes.
*/
public Uncollect(RelInput input) {
+ // note: itemAliases are not serialized, so we do not read them back
this(input.getCluster(), input.getTraitSet(), input.getInput(),
input.getBoolean("withOrdinality", false), Collections.emptyList(),
+ deserializeIndices(input, "passthrough", ImmutableBitSet.of()),
+ deserializeIndices(input, "collectionFields",
+
ImmutableBitSet.range(input.getInput().getRowType().getFieldCount())),
input.getBoolean("expandStructFields", true),
input.getBoolean("isOuter", false));
}
+ /** Reads the input-field names serialized under {@code tag} (see
+ * as field indices; returns {@code defaultSet} when the attribute is
absent. */
+ private static ImmutableBitSet deserializeIndices(RelInput input, String tag,
+ ImmutableBitSet defaultSet) {
+ final List<String> names = input.getStringList(tag);
+ if (names == null) {
+ return defaultSet;
+ }
+ final RelDataType inputRowType = input.getInput().getRowType();
+ final ImmutableBitSet.Builder builder = ImmutableBitSet.builder();
+ for (String name : names) {
+ builder.set(
+ requireNonNull(inputRowType.getField(name, true, false),
Review Comment:
Writing a plan to JSON and reading it back changes the plan when an
`Uncollect` input has repeated field names: in the example below, the row type
loses a column. Repeated names occur with two UNNESTs of the same column: the
inner `Uncollect` outputs both the array `A` and its element `A`.
`explainTerms` writes the pass-through and collection fields as names, and
this seems to cause problems when reading the plan back: `getField(name)`
returns the first field with that name, so both `A` resolve to the same field.
Reproducer (for `RelWriterTest`; the plan comes from SQL and is decorrelated
by `TopDownGeneralDecorrelator.decorrelateQuery`, the method the planner calls
when `topDownGeneralDecorrelationEnabled` is true):
```java
@Test void testUncollectPassthroughDuplicateNamesRoundTrip() throws
Exception {
final String sql = "select * from (values (1, array[10, 20])) as v(k,
a),\n"
+ " unnest(v.a) u1(x), unnest(v.a) u2(y)";
final AtomicReference<RelNode> ref = new AtomicReference<>();
CalciteAssert.hr()
.query(sql)
.withHook(Hook.TRIMMED, (Consumer<RelNode>) ref::set)
.runs();
final RelNode rel =
TopDownGeneralDecorrelator.decorrelateQuery(ref.get(),
RelFactories.LOGICAL_BUILDER.create(ref.get().getCluster(),
null));
final RelJsonWriter writer = new RelJsonWriter();
rel.explain(writer);
final String json = writer.asString();
final RelNode rel2 = new RelJsonReader(rel.getCluster(), null,
null).read(json);
assertThat(rel2.getRowType(), is(rel.getRowType()));
}
```
The outer `Uncollect` is serialized with `"passthrough": ["K", "A", "A"]`,
and both `"A"` resolve to the first `A`. The test currently fails as follows:
```
Expected: is <RecordType(INTEGER K, INTEGER ARRAY A, INTEGER A0, INTEGER A)>
but: was <RecordType(INTEGER K, INTEGER ARRAY A, INTEGER A)>
```
The first solution that comes to mind is to store field positions instead of
names, wdyt?
##########
core/src/main/java/org/apache/calcite/sql2rel/TopDownGeneralDecorrelator.java:
##########
@@ -232,14 +233,32 @@ public static RelNode decorrelateQuery(RelNode rel,
RelBuilder builder) {
prePlanner.setRoot(rel);
RelNode preparedRel = prePlanner.findBestExp();
+ // Extract computations over correlated variables from the right side of
+ // a Correlate into its left input, like RelDecorrelator does. Rewrites
+ // that require the right side to access correlated fields directly (such
+ // as CorrelateUncollectMergeRule) can then apply.
+ preparedRel = preparedRel.accept(new
CorrelateProjectExtractor(RelFactories.LOGICAL_BUILDER));
Review Comment:
With top-down decorrelation, a non-deterministic expression in a correlated
subquery is evaluated once per left row instead of once per right row, so in
the query below `rand()` returns the same value for both rows of the subquery.
The extractor does not seem to check whether expressions are deterministic
before moving them to the left input.
Reproducer (for `JdbcTest`):
```java
@Test void testTopDownDecorrelateRandPerRightRow() throws Exception {
final String sql = "select t.i, l.x, l.r\n"
+ "from (values 1) as t(i),\n"
+ "lateral (\n"
+ " select u.x as x, rand() + t.i as r\n"
+ " from (values 0, 0) as u(x), unnest(array[t.i]) as z) as l";
final List<Double> rs = new ArrayList<>();
try (Connection connection = CalciteAssert.that()
.with(CalciteConnectionProperty.TOPDOWN_GENERAL_DECORRELATION_ENABLED, true)
.connect();
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(sql)) {
while (resultSet.next()) {
rs.add(resultSet.getDouble(3));
}
}
assertThat(rs, hasSize(2));
assertThat(rs.get(1), not(rs.get(0)));
}
```
On this PR the test fails on every run: the two `r` values are equal (for
example `1.870888760803722` twice). On the base commit (a7f3290) the test
passes: the values differ.
Plans with the property set to true:
- base: `RAND() + $cor1.I` stays in the `EnumerableCalc` on the right side
of `EnumerableCorrelate`.
- this PR: `RAND()` is computed in the `EnumerableCalc` over the left input,
below `EnumerableCorrelate`.
The problem pre-dates your PR, but now it also affects top-down
decorrelation; before, it affected only bottom-up decorrelation. Could
non-deterministic expressions be left in place?
--
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]