Repository navigation
Conversation
|
I think you can squash the commits for merging |
…e when aliased Extend AliasNamespace's CALCITE-5779 COLLECTION_TABLE check to also cover UNNEST when the array's component type is a struct. With allowAliasUnnestItems=true (Trino), UNNEST does not expand struct columns and instead uses the alias directly.
vlsi
left a comment
There was a problem hiding this comment.
The fix makes d.a resolve, but it also changes column names and NATURAL JOIN results for existing queries, leaves two variants of the same bug unfixed, and the test does not guard the half of the contract that keeps the alias usable. Details are in the inline comments.
Commit message and PR description
- The PR title is cut off ("loses the field nam…"), and the description starts with "…e when aliased". Please put the full title into the title field.
- In "Extend AliasNamespace's CALCITE-5779 COLLECTION_TABLE check", the ticket number carries the meaning. Please name the mechanism instead, for example "the single-column alias that keeps the original field name, added in CALCITE-5779".
- "(Trino)" is incomplete:
allowAliasUnnestItemsis true for bothPRESTOandBIG_QUERY. - The commit message should state the user-visible change.
select *over such an UNNEST now returns the field name instead of the alias, andNATURAL JOINmatches on the field name. The JIRA needs the same note so that it reaches the release notes.
|
It looks like some of these objections are legitimate, I will wait until you reply to them. |
- Correct a stale comment claiming the alias always names the sole column - Extracted the || condition into a local isStructUnnest boolean for readability - Address WITH ORDINALITY: select d.a from R with ordinality as d keeps its field name - Address sub-query operand issue: isUnnestOfStructArray now unwraps a struct-typed operand - Corrected the Javadocs
|
@vlsi Thank you for the thorough review. I believe I have addressed all of your concerns. Let me know if you see anything else. |
vlsi
left a comment
There was a problem hiding this comment.
Thanks for the update. d.a now resolves for a plain UNNEST, a sub-query operand, and WITH ORDINALITY, and the PRESTO case has its own test. The remaining problems are below, with details in the inline comments.
In the examples, R = unnest(cast(array[row(1)] as row(a integer) array)). I ran each query on this PR and on its base, 9634752f1a.
Behavior
WITH ORDINALITYnow loses the alias:select d from R with ordinality as dreturned(D)on the base and now fails withColumn 'D' not found in any table. WithoutWITH ORDINALITY,select d from R as dstill works, so the two forms follow different rules.- The reply in the naming thread says the alias is "only usable to qualify" the column, but
select d, d.a from R as dreturns(D, A)in the new test, andselect * from R as d join (values 1) t(d) using (d)is still accepted and returns a column namedA. Please decide whether the alias names the column or only qualifies it, and make the code, the tests, and the comments say the same thing. - MULTISET changes too:
select * from unnest(cast(multiset[row(1)] as row(a integer) multiset)) as dreturned(D)and now returns(A). It has no test.
Commit message and JIRA
- The commit message is unchanged from the first round. It still says "Extend AliasNamespace's CALCITE-5779 COLLECTION_TABLE check" and "(Trino)", and it does not state the user-visible change.
- The PR description has the same first sentence about CALCITE-5779. It also says that the fix holds for
WITH ORDINALITYand that "both the alias and the field name resolve"; with this PR,select d from R with ordinality as dfails, so the second claim is false forWITH ORDINALITY. Please fix the description before reusing it for the commit message. - The commit subject says "a single-field ROW array", and the JIRA summary and the PR title say "a ROW array". Please make them agree; if "single-field" is the accurate scope, the JIRA summary can change.
- The JIRA has no note about the change for the release notes:
select *over such an UNNEST returns the field name instead of the alias, andNATURAL JOINmatches on the field name.
Not found
- I did not find a JIRA for the
CompileException: Cannot cast "Baz$Record1_0" to "java.lang.Object[]"failure that blocks an end-to-end test. If you have filed one, please link it from CALCITE-7791.
|
sbroeder, mihaibudiu, thanks for the ping. I was literally reviewing the PR, so it ended up like "mihaibudiu requested review and vlsi posted a comment 5 minutes later" :) |
SingleColumnAliasRelDataType.java — generalized to support a multi-field original
so it can now dual-name the first field of a struct-array WITH ORDINALITY result too,
not just a single-column UNNEST.
AliasNamespace.java:
- Addressed WITH ORDINALITY again: the data column now uses SingleColumnAliasRelDataType
instead of just returning rowType unchanged. That was silently breaking
select d / USING (d) for the ordinality case
- Reworded and moved comments.
- Renamed isUnnestOfStructArray to keepsElementFieldName
SqlUnnestOperator.java — added another static helper, unwrapOperandType, so the subquery
unwrap step is no longer duplicated between inferReturnType and AliasNamespace. Both new
helpers are now @API(since = "1.43", status = INTERNAL). fixed the Javadoc wording and @params.
SqlValidatorTest.java:
- Fixed comments and wording
- WITH ORDINALITY test now asserts the full select * row type and adds a select d, d.a case.
- Added missing USING and MULTISET cases.
|
@vlsi Thank you for another thorough review. I believe I've addressed your concerns and filed related JIRA https://issues.apache.org/jira/browse/CALCITE-7831. Please let me know if I have inadvertently overlooked something. |
vlsi
left a comment
There was a problem hiding this comment.
Thanks, the inline comments from the last round are addressed, apart from the USING wording below, and thanks for filing CALCITE-7831.
In the examples, R = unnest(cast(array[row(1)] as row(a integer) array)). I ran the queries below on this PR and on its base, 9634752f1a, through the validator and SqlToRelConverter.
select d, d.a from R with ordinality as dreturns(D, A), and the plan projects$0twice.- The sub-query operand with
WITH ORDINALITYresolvesdagain:(D)on the base, an error on the previous headf407a58297, and(D)now. NATURAL JOINandUSING (d)behave the same withWITH ORDINALITYas without it.- A scalar array, a MAP, a ROW with two fields, and PRESTO give the same row types as on the base.
The remaining points:
Behavior
- An alias equal to
ORDINALITYnow resolves where the base failed, and the order of the lookups inSingleColumnAliasRelDataType.getFielddecides which column an unqualified name means. Details are in the inline comment ongetFieldCount, the line that lets the type have more than one field.
Comments and description
- The test comment above the
NATURAL JOINcases says thatUSINGmatches the field name and not the alias, and theUSING (d)case below it shows thatUSINGmatches both. The PR description says the same: "NATURAL JOIN and USING, which now match on the field name rather than the alias".
Commit message and JIRA
- The first commit's message still says "Extend AliasNamespace's CALCITE-5779 COLLECTION_TABLE check" and "(Trino)". The PR description no longer has either, so, once the
USINGsentence is fixed, it can serve as the message when the commits are squashed. - The JIRA still has no note for the release notes:
select *over such an UNNEST returns the field name instead of the alias, andNATURAL JOINmatches on the field name.
- Update comments to reflect actual behavior and remove ambiguity. - Add new tests in SqlValidatorTest and SqlToRelConverterTest.
|
@vlsi I've posted another revision. Please let me know if you have other requests. |
vlsi
left a comment
There was a problem hiding this comment.
Thanks. The class Javadoc, the getField Javadoc, the new WITH ORDINALITY tests, the PR description, and the release note in the JIRA cover what I asked for in the last round. Four threads are still open; the replies are in those threads:
- The two test comments about
USINGare unchanged. - The query with an alias equal to
ORDINALITYhas no test yet. - The new comment in
AliasNamespacesays "columns" where only one column takes the alias.
The comment said 'NATURAL JOIN and USING match the field name' but the USING (d) case below shows USING also accepts the alias. Split into two sentences: NATURAL JOIN matches the field name; USING accepts either name.
|
@vlsi Anything else needed on this one? |
vlsi
left a comment
There was a problem hiding this comment.
The branch has six commits, and five of them are review follow-ups ("More review comments addressed", "Remove check warning"). Please squash them into one commit whose message is the PR description; the first commit's message still says "Extend AliasNamespace's CALCITE-5779 COLLECTION_TABLE check" and "(Trino)".
This is normal during the review process. The squashing should be done after the PR is approved. |
- Reuse dataColumnAlias in AliasNamespace.java - testUnnestSingleFieldRowWithOrdinality renamed to testUnnestAliasOrdinalityResolvesToOrdinalityColumn - Added Javadoc to testUnnestAliasOrdinalityResolvesToOrdinalityColumn and testUnnestSingleFieldRowWithOrdinalityAllColumns
@vlsi, Per recommendation from @mihaibudiu I will squash the commits once the PR is approved. |
vlsi
left a comment
There was a problem hiding this comment.
Two things block the merge for me. A column of an aliased single-field ROW UNNEST that sits on the nullable side of an outer join now fails conversion to relational algebra (F1), and an aliased UNNEST of an anonymous ROW(1) array now names its column EXPR$0 instead of the alias, which turns a NATURAL JOIN of two such UNNESTs from a cross join into an equi-join (F2).
The rest block nothing.
Not inline
F3 minor, medium confidence The change alters select * column names and NATURAL JOIN results of existing queries, and site/_docs/history.md gets no CALCITE-7791 entry under the 1.43.0 "Breaking Changes" section.
Problem: An upgrader reads the release page, not JIRA. In this release cycle the commits that change observable query results add their own bullet to the unreleased 1.43.0 "Breaking Changes" section, so a JIRA-only note leaves the page without the entry that explains why select * from unnest(...) as d returns A instead of D and why natural join (select 1 as d) became a cross join. The 2026-10-03 review round accepted "the release note in the JIRA"; no thread considered history.md.
Proposed solution: Add a CALCITE-7791 bullet under #### Breaking Changes of the 1.43.0 block in site/_docs/history.md, in the shape of the neighbouring entries: under the default conformance select * over an aliased UNNEST of single-field ROW values (plain, WITH ORDINALITY, sub-query operand, MULTISET) returns the field name instead of the alias, NATURAL JOIN matches the field name, USING accepts either name, and PRESTO and BIG_QUERY are unaffected; name the workaround (AS d (d) or USING (d)). Alternatively, say in the thread why this entry is left to the release manager.
Reviewed at 07ea9f1e.
| aliasedType = node.getKind() == SqlKind.COLLECTION_TABLE || keepsElementFieldName | ||
| ? new SingleColumnAliasRelDataType(rowType, singleColumnAlias) : singleColumnAlias; | ||
| // If the sub-query is UNNEST with ordinality | ||
| // and the sub-query has two columns: data column, ordinality column | ||
| // then the namespace's sole column is named after the alias. | ||
| } else if (node.getKind() == SqlKind.UNNEST && rowType.getFieldCount() == 2 | ||
| && ((SqlUnnestOperator) ((SqlBasicCall) node).getOperator()).withOrdinality) { | ||
| aliasedType = validator.getTypeFactory().builder() | ||
| // WITH ORDINALITY: data column, ordinality column. The data | ||
| // column is named after the alias, same as the single-column case. | ||
| final RelDataType dataColumnAlias = validator.getTypeFactory().builder() | ||
| .kind(rowType.getStructKind()) | ||
| .add(((SqlIdentifier) operands.get(1)).getSimple(), | ||
| rowType.getFieldList().get(0).getType()) | ||
| .add(rowType.getFieldList().get(1)) | ||
| .build(); | ||
| aliasedType = keepsElementFieldName | ||
| ? new SingleColumnAliasRelDataType(rowType, dataColumnAlias) |
There was a problem hiding this comment.
F1 major An aliased UNNEST of a single-field ROW array on the null-generating side of a LEFT or RIGHT JOIN now validates its column as NOT NULL, and SqlToRelConverter rejects the query, which converted on the base.
Problem: The validator's outer-join nullability does not reach a SingleColumnAliasRelDataType, so a column reference through it (d, d.a, d + 1, d.ordinality) keeps NOT NULL while the converted plan makes it nullable, and conversion throws AssertionError: Conversion to relational algebra failed to preserve datatypes. The throw is unconditional, so it does not depend on -ea. Plain UNNEST and WITH ORDINALITY fail alike; only select * converts. TABLE(...) AS alias, which the base already wraps, fails the same way at the base, so a fix inside the UNNEST branch alone leaves it.
Reproducer
// SqlToRelConverterTest
@Test void testUnnestSingleFieldRowAliasOnNullableSide() {
sql("select d, d.a from (values 1) as t (x)\n"
+ "left join unnest(cast(array[row(1)] as row(a integer) array)) as d on true").ok();
sql("select d, d.ordinality from (values 1) as t (x)\n"
+ "left join unnest(cast(array[row(1)] as row(a integer) array))\n"
+ " with ordinality as d on true").ok();
sql("select d from unnest(cast(array[row(1)] as row(a integer) array)) as d\n"
+ "right join (values 1) as t (x) on true").ok();
// head: AssertionError: Conversion to relational algebra failed to preserve datatypes
// validated type: RecordType(INTEGER NOT NULL D) NOT NULL
// converted type: RecordType(INTEGER D) NOT NULL
// expected (base 9634752f for `d`): validated RecordType(INTEGER D) NOT NULL, plan converts
}Proposed solution: Make the nullable copy of a SingleColumnAliasRelDataType a SingleColumnAliasRelDataType over nullable copies of both wrapped types, for example in RelDataTypeFactoryImpl.createTypeWithNullability, which fixes TABLE(...) AS alias with it. Add SqlToRelConverterTest cases, with their validator types in testUnnestAlias, for the aliased UNNEST on the null-generating side of a LEFT and a RIGHT JOIN, plain and WITH ORDINALITY, selecting the alias and the field name.
| private boolean keepsElementFieldName(SqlCall unnestCall) { | ||
| final RelDataType operandType = | ||
| SqlUnnestOperator.unwrapOperandType( | ||
| validator.getValidatedNodeType(unnestCall.operand(0))); | ||
| final RelDataType componentType = operandType.getComponentType(); | ||
| return componentType != null | ||
| && SqlUnnestOperator.expandsStructIntoColumns(componentType, | ||
| validator.config().conformance().allowAliasUnnestItems()); | ||
| } |
There was a problem hiding this comment.
F2 major An aliased UNNEST of an anonymous single-field ROW array now exposes the generated field name EXPR$0 instead of the alias, so select * loses the alias and NATURAL JOIN of two such UNNESTs becomes an equi-join.
Problem: keepsElementFieldName is true for every single-field ROW element, including ROW(1), whose field name is generated. Two aliased UNNESTs in one FROM clause give EXPR$0, EXPR$00 instead of A, B, and a NATURAL JOIN between them now filters rows where the base did a cross join, without an error. WITH ORDINALITY and a sub-query operand behave the same. The thread that settled the field name as canonical ("the field name is what star-expansion and NATURAL JOIN use") considered a declared name such as A, not a generated one.
select * from unnest(array[row(1)]) as d;
-- head: RecordType(INTEGER NOT NULL EXPR$0) base: RecordType(INTEGER NOT NULL D)
select * from unnest(array[row(1)]) as a natural join unnest(array[row(2)]) as b;
-- head: (EXPR$0), LogicalJoin(condition=[=($0, $1)]), no rows
-- base: (A, B), LogicalJoin(condition=[true])
select * from unnest(array[row(1)]) with ordinality as d;
-- head: (EXPR$0, ORDINALITY) base: (D, ORDINALITY)Proposed solution: Keep the base behavior, the alias as the column name, when the element's single field name is generated, for example by also requiring !SqlUtil.isGeneratedAlias(...) of that name in keepsElementFieldName, and add a testUnnestAlias case for unnest(array[row(1)]) as d. If the generated name is meant to win, state it in the PR description and the JIRA release note and pin it with a test.
|
|
||
| @Override public int getFieldCount() { | ||
| return 1; | ||
| return original.getFieldCount(); |
There was a problem hiding this comment.
F5 minor No test observes SingleColumnAliasRelDataType.getFieldCount(): the mutant that returns 0 survives, though a wrong count binds a correlated reference to the wrong column.
Problem: The change makes getFieldCount() report the wrapped type's count so that WITH ORDINALITY works through the wrapper. SqlToRelConverter adds each namespace's field count to the offset of the correlation fields after it, so a FROM item to the right of an aliased ROW-element UNNEST WITH ORDINALITY that a correlated sub-query references is where the count shows.
@Test void testUnnestSingleFieldRowAliasWithOrdinalityCorrelatedOffset() {
final String sql = "select t.name\n"
+ "from unnest(cast(array[row(1)] as row(a integer) array))\n"
+ " with ordinality as d, dept as t\n"
+ "where exists (select 1 from emp e\n"
+ " where e.deptno = t.deptno and e.empno = d.ordinality)";
// head: LogicalFilter(condition=[AND(=($7, $cor0.DEPTNO), =($0, $cor0.ORDINALITY))])
// getFieldCount() mutated to `return 0;`: =($7, $cor0.A)
sql(sql).withDecorrelate(false).withExpand(false).ok();
}Proposed solution: Add a SqlToRelConverterTest case with an aliased ROW-element UNNEST WITH ORDINALITY followed by another table in the same FROM, and a correlated sub-query that references that table, so the plan pins the correlation field.
| if (rowType.getFieldCount() == 1) { | ||
| final RelDataType singleColumnAlias = validator.getTypeFactory().builder() | ||
| .kind(rowType.getStructKind()) | ||
| .add(((SqlIdentifier) operands.get(1)).getSimple(), | ||
| rowType.getFieldList().get(0).getType()) | ||
| .build(); | ||
| aliasedType = node.getKind() == SqlKind.COLLECTION_TABLE | ||
| aliasedType = node.getKind() == SqlKind.COLLECTION_TABLE || keepsElementFieldName | ||
| ? new SingleColumnAliasRelDataType(rowType, singleColumnAlias) : singleColumnAlias; | ||
| // If the sub-query is UNNEST with ordinality | ||
| // and the sub-query has two columns: data column, ordinality column | ||
| // then the namespace's sole column is named after the alias. | ||
| } else if (node.getKind() == SqlKind.UNNEST && rowType.getFieldCount() == 2 | ||
| && ((SqlUnnestOperator) ((SqlBasicCall) node).getOperator()).withOrdinality) { | ||
| aliasedType = validator.getTypeFactory().builder() | ||
| // WITH ORDINALITY: data column, ordinality column. The data | ||
| // column is named after the alias, same as the single-column case. | ||
| final RelDataType dataColumnAlias = validator.getTypeFactory().builder() | ||
| .kind(rowType.getStructKind()) | ||
| .add(((SqlIdentifier) operands.get(1)).getSimple(), | ||
| rowType.getFieldList().get(0).getType()) | ||
| .add(rowType.getFieldList().get(1)) | ||
| .build(); |
There was a problem hiding this comment.
F6 nit The single-column branch and the WITH ORDINALITY branch build the same aliased data-column type with identical five-line builders.
Problem: singleColumnAlias and dataColumnAlias are the same expression and both feed new SingleColumnAliasRelDataType(rowType, ...), so a later change to how the data column is aliased has to be made twice; T27 merged the copies inside the ORDINALITY branch but left this pair.
Proposed solution: Build the aliased data-column type in one place, for example a private helper that both branches call, or a builder computed once under a condition that covers both branches.
| public SingleColumnAliasRelDataType(RelDataType original, RelDataType alias) { | ||
| assert original.isStruct() && original.getFieldCount() == 1; | ||
| assert alias.isStruct() && alias.getFieldCount() == 1; | ||
| checkArgument(original.isStruct() && original.getFieldCount() >= 1); | ||
| checkArgument(alias.isStruct() && alias.getFieldCount() == 1); |
There was a problem hiding this comment.
F7 nit The public constructor of SingleColumnAliasRelDataType now throws IllegalArgumentException on preconditions that nothing documents, including that the alias's single field stands for the first field of original.
Problem: A caller cannot tell from the class comment what to pass as alias: a one-field struct named after the alias whose field has the type of original's first field. The checks throw without a message.
Proposed solution: Give the constructor a doc comment: @param original the row type, a struct with at least one field; @param alias a struct with one field, named after the alias, whose type is that of the first field of original; @throws IllegalArgumentException when either shape does not hold.
Co-authored-by: Vladimir Sitnikov <sitnikov.vladimir@gmail.com>
- Preserve nullability of aliased UNNEST/TABLE on the null-generating side of
an outer join: createTypeWithNullability now keeps
SingleColumnAliasRelDataType and applies nullability to both wrapped types.
Adds converter and validator tests for aliased UNNEST and TABLE(...) on the
null-generating side of LEFT/RIGHT JOIN.
- Keep alias as column name when UNNEST ROW element's field name is generated:
keepsElementFieldName no longer applies when the element's first field has a
generated name such as EXPR$0, so 'unnest(array[row(1)]) as d' yields column D
and NATURAL JOIN of two such UNNESTs stays a cross join, as before.
- Build the aliased data-column type in one place (AliasNamespace).
- Document the SingleColumnAliasRelDataType constructor contract and add
messages to its argument checks.
- Add tests: generated and "EXPR$"-prefixed names, `AS d (d)`, and a
correlated sub-query over a table to the right of an aliased UNNEST WITH
ORDINALITY (pins SingleColumnAliasRelDataType.getFieldCount).
- Add a CALCITE-7791 entry under Breaking Changes in history.md.
|
@vlsi Thank you for the valuable input. I believe I have addressed everything you have raised. Please let me know if there is anything else required. |
|



An aliased UNNEST of a collection of single-field ROW values renames the
field to the alias and discards its real name.
AliasNamespacealreadywraps a single column in
SingleColumnAliasRelDataTypefor table functions(CALCITE-5779), but only for
COLLECTION_TABLE.