From 802dca92be17e3ed03873be37e8f066133c68a4a Mon Sep 17 00:00:00 2001 From: Sean Broeder Date: Sat, 19 Sep 2026 08:25:29 -0500 Subject: [PATCH 1/9] [CALCITE-7791] UNNEST of a single-field ROW array loses the field name 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. --- .../calcite/sql/validate/AliasNamespace.java | 20 +++++++++++++++++++ .../apache/calcite/test/SqlValidatorTest.java | 19 ++++++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/core/src/main/java/org/apache/calcite/sql/validate/AliasNamespace.java b/core/src/main/java/org/apache/calcite/sql/validate/AliasNamespace.java index 99f84154e77b..3a3d9681926d 100644 --- a/core/src/main/java/org/apache/calcite/sql/validate/AliasNamespace.java +++ b/core/src/main/java/org/apache/calcite/sql/validate/AliasNamespace.java @@ -111,6 +111,7 @@ protected AliasNamespace( rowType.getFieldList().get(0).getType()) .build(); aliasedType = node.getKind() == SqlKind.COLLECTION_TABLE + || (node.getKind() == SqlKind.UNNEST && isUnnestOfStructArray((SqlCall) node)) ? new SingleColumnAliasRelDataType(rowType, singleColumnAlias) : singleColumnAlias; // If the sub-query is UNNEST with ordinality // and the sub-query has two columns: data column, ordinality column @@ -162,6 +163,25 @@ protected AliasNamespace( } } + /** + * Returns whether an UNNEST call's array operand has a struct element type. + * + *

{@link SqlUnnestOperator#inferReturnType} produces a 1-field row for + * both struct arrays and scalar arrays. Only the structs have a real field + * name worth preserving. + */ + private boolean isUnnestOfStructArray(SqlCall unnestCall) { + if (unnestCall.operandCount() != 1) { + return false; + } + if (validator.config().conformance().allowAliasUnnestItems()) { + return false; + } + final RelDataType operandType = validator.getValidatedNodeType(unnestCall.operand(0)); + final RelDataType componentType = operandType.getComponentType(); + return componentType != null && componentType.isStruct(); + } + private static String getString(RelDataType rowType) { StringBuilder buf = new StringBuilder(); buf.append("("); diff --git a/core/src/test/java/org/apache/calcite/test/SqlValidatorTest.java b/core/src/test/java/org/apache/calcite/test/SqlValidatorTest.java index 3915e5723cb8..a085653db364 100644 --- a/core/src/test/java/org/apache/calcite/test/SqlValidatorTest.java +++ b/core/src/test/java/org/apache/calcite/test/SqlValidatorTest.java @@ -1201,6 +1201,25 @@ void testDyadicCollateOperator() { }); } + /** Test case for + * [CALCITE-7791] + * UNNEST of a single-field ROW array loses the field name when aliased. */ + @Test void testUnnestSingleFieldRow() { + sql("select d.a\n" + + "from unnest(cast(array[row(1)] as row(a integer) array)) as d") + .columnType("INTEGER NOT NULL"); + // The array's real field name ("A") survives star-expansion too, not just + // the synthetic alias ("D"). + sql("select *\n" + + "from unnest(cast(array[row(1)] as row(a integer) array)) as d") + .type("RecordType(INTEGER NOT NULL A) NOT NULL"); + // Trino: struct not expanded; alias renames the ROW column. + sql("select *\n" + + "from unnest(cast(array[row(1)] as row(a integer) array)) as d") + .withConformance(SqlConformanceEnum.PRESTO) + .type("RecordType(RecordType(INTEGER NOT NULL A) NOT NULL D) NOT NULL"); + } + @Test void testOverlay() { expr("overlay('ABCdef' placing 'abc' from 1)").ok(); expr("overlay('ABCdef' placing 'abc' from 1 for 3)").ok(); From f407a5829752e8b1af6d12f47080d0573f8e13d6 Mon Sep 17 00:00:00 2001 From: Sean Broeder Date: Sat, 26 Sep 2026 16:26:57 -0700 Subject: [PATCH 2/9] Address review comments: - 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 --- .../apache/calcite/sql/SqlUnnestOperator.java | 14 ++-- .../calcite/sql/validate/AliasNamespace.java | 52 +++++++------- .../calcite/test/SqlToRelConverterTest.java | 11 +++ .../apache/calcite/test/SqlValidatorTest.java | 68 +++++++++++++------ .../calcite/test/SqlToRelConverterTest.xml | 14 ++++ 5 files changed, 109 insertions(+), 50 deletions(-) diff --git a/core/src/main/java/org/apache/calcite/sql/SqlUnnestOperator.java b/core/src/main/java/org/apache/calcite/sql/SqlUnnestOperator.java index 61ada978234f..1460c4dd95b9 100644 --- a/core/src/main/java/org/apache/calcite/sql/SqlUnnestOperator.java +++ b/core/src/main/java/org/apache/calcite/sql/SqlUnnestOperator.java @@ -99,10 +99,7 @@ public SqlUnnestOperator(boolean withOrdinality) { } else { RelDataType componentType = requireNonNull(type.getComponentType(), "componentType"); boolean isNullable = componentType.isNullable() || padNullable; - // Whether a struct element expands into one column per field depends - // on the SQL conformance; allowAliasUnnestItems describes how - // collections of ROW values are expanded. - if (!allowAliasUnnestItems(opBinding) && componentType.isStruct()) { + if (expandsStructIntoColumns(componentType, allowAliasUnnestItems(opBinding))) { for (RelDataTypeField field : componentType.getFieldList()) { RelDataType fieldType = field.getType(); if (isNullable) { @@ -130,6 +127,15 @@ public SqlUnnestOperator(boolean withOrdinality) { return builder.build(); } + /** + * Returns whether UNNEST expands {@code componentType} into one column + * per field, rather than a single column of the struct's own type. + */ + public static boolean expandsStructIntoColumns(RelDataType componentType, + boolean allowAliasUnnestItems) { + return componentType.isStruct() && !allowAliasUnnestItems; + } + private static boolean allowAliasUnnestItems(SqlOperatorBinding operatorBinding) { return (operatorBinding instanceof SqlCallBinding) && ((SqlCallBinding) operatorBinding) diff --git a/core/src/main/java/org/apache/calcite/sql/validate/AliasNamespace.java b/core/src/main/java/org/apache/calcite/sql/validate/AliasNamespace.java index 3a3d9681926d..27bb020daf78 100644 --- a/core/src/main/java/org/apache/calcite/sql/validate/AliasNamespace.java +++ b/core/src/main/java/org/apache/calcite/sql/validate/AliasNamespace.java @@ -100,30 +100,30 @@ protected AliasNamespace( final RelDataType aliasedType; if (operands.size() == 2) { final SqlNode node = operands.get(0); - // Alias is 'AS t' (no column list). - // If the sub-query is UNNEST or VALUES, - // and the sub-query has one column, - // then the namespace's sole column is named after the alias. + // 'AS t': the sole column is named after the alias, unless it's a + // struct-array UNNEST field (isUnnestOfStructArray), which keeps its name. + final boolean isStructUnnest = node.getKind() == SqlKind.UNNEST + && isUnnestOfStructArray((SqlCall) node); 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 - || (node.getKind() == SqlKind.UNNEST && isUnnestOfStructArray((SqlCall) node)) + aliasedType = node.getKind() == SqlKind.COLLECTION_TABLE || isStructUnnest ? 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. + // WITH ORDINALITY: data column named after the alias, unless it's + // a struct-array field, which keeps its name. } else if (node.getKind() == SqlKind.UNNEST && rowType.getFieldCount() == 2 && ((SqlUnnestOperator) ((SqlBasicCall) node).getOperator()).withOrdinality) { - aliasedType = validator.getTypeFactory().builder() - .kind(rowType.getStructKind()) - .add(((SqlIdentifier) operands.get(1)).getSimple(), - rowType.getFieldList().get(0).getType()) - .add(rowType.getFieldList().get(1)) - .build(); + aliasedType = isStructUnnest + ? rowType + : validator.getTypeFactory().builder() + .kind(rowType.getStructKind()) + .add(((SqlIdentifier) operands.get(1)).getSimple(), + rowType.getFieldList().get(0).getType()) + .add(rowType.getFieldList().get(1)) + .build(); } else { aliasedType = rowType; } @@ -164,22 +164,20 @@ protected AliasNamespace( } /** - * Returns whether an UNNEST call's array operand has a struct element type. - * - *

{@link SqlUnnestOperator#inferReturnType} produces a 1-field row for - * both struct arrays and scalar arrays. Only the structs have a real field - * name worth preserving. + * Returns whether the sole column of an aliased UNNEST is a field of + * the collection's ROW element, which keeps its own name, rather than + * a scalar column, which the alias renames. */ private boolean isUnnestOfStructArray(SqlCall unnestCall) { - if (unnestCall.operandCount() != 1) { - return false; - } - if (validator.config().conformance().allowAliasUnnestItems()) { - return false; + RelDataType operandType = validator.getValidatedNodeType(unnestCall.operand(0)); + if (operandType.isStruct()) { + // Sub-query operand: unwrap as SqlUnnestOperator#inferReturnType does. + operandType = operandType.getFieldList().get(0).getType(); } - final RelDataType operandType = validator.getValidatedNodeType(unnestCall.operand(0)); final RelDataType componentType = operandType.getComponentType(); - return componentType != null && componentType.isStruct(); + return componentType != null + && SqlUnnestOperator.expandsStructIntoColumns(componentType, + validator.config().conformance().allowAliasUnnestItems()); } private static String getString(RelDataType rowType) { diff --git a/core/src/test/java/org/apache/calcite/test/SqlToRelConverterTest.java b/core/src/test/java/org/apache/calcite/test/SqlToRelConverterTest.java index 88fa2a27c8e1..bb2bf618e13f 100644 --- a/core/src/test/java/org/apache/calcite/test/SqlToRelConverterTest.java +++ b/core/src/test/java/org/apache/calcite/test/SqlToRelConverterTest.java @@ -2314,6 +2314,17 @@ private void checkCallTypesConsistent(String sql) { sql(sql).ok(); } + /** + * Test case for + * [CALCITE-7791] + * UNNEST of a single-field ROW array loses the field name when aliased. + */ + @Test void testUnnestSingleFieldRowAliasKeepsFieldName() { + final String sql = "select d, d.a\n" + + "from unnest(cast(array[row(1)] as row(a integer) array)) as d"; + sql(sql).ok(); + } + @Test void testUnnestSubQuery() { final String sql = "select*from unnest(multiset(select*from dept))"; sql(sql).ok(); diff --git a/core/src/test/java/org/apache/calcite/test/SqlValidatorTest.java b/core/src/test/java/org/apache/calcite/test/SqlValidatorTest.java index a085653db364..a645a33e0b9b 100644 --- a/core/src/test/java/org/apache/calcite/test/SqlValidatorTest.java +++ b/core/src/test/java/org/apache/calcite/test/SqlValidatorTest.java @@ -1201,25 +1201,6 @@ void testDyadicCollateOperator() { }); } - /** Test case for - * [CALCITE-7791] - * UNNEST of a single-field ROW array loses the field name when aliased. */ - @Test void testUnnestSingleFieldRow() { - sql("select d.a\n" - + "from unnest(cast(array[row(1)] as row(a integer) array)) as d") - .columnType("INTEGER NOT NULL"); - // The array's real field name ("A") survives star-expansion too, not just - // the synthetic alias ("D"). - sql("select *\n" - + "from unnest(cast(array[row(1)] as row(a integer) array)) as d") - .type("RecordType(INTEGER NOT NULL A) NOT NULL"); - // Trino: struct not expanded; alias renames the ROW column. - sql("select *\n" - + "from unnest(cast(array[row(1)] as row(a integer) array)) as d") - .withConformance(SqlConformanceEnum.PRESTO) - .type("RecordType(RecordType(INTEGER NOT NULL A) NOT NULL D) NOT NULL"); - } - @Test void testOverlay() { expr("overlay('ABCdef' placing 'abc' from 1)").ok(); expr("overlay('ABCdef' placing 'abc' from 1 for 3)").ok(); @@ -10120,6 +10101,55 @@ void testGroupExpressionEquivalenceParams() { sql("select * from (SELECT ARRAY['banana'] as fruits) as t, UNNEST(t.fruits)") .type("RecordType(CHAR(6) NOT NULL ARRAY NOT NULL FRUITS, " + "CHAR(6) NOT NULL EXPR$0) NOT NULL").ok(); + + // Test case for [CALCITE-7791] UNNEST of a single-field ROW array loses + // the field name when aliased. The array's field name ("A") survives + // star-expansion, and the alias ("D") still works to qualify it. + sql("select d, d.a\n" + + "from unnest(cast(array[row(1)] as row(a integer) array)) as d") + .type("RecordType(INTEGER NOT NULL D, INTEGER NOT NULL A) NOT NULL"); + + // UNNEST ROW array in a sub-query. + sql("select *\n" + + "from unnest(\n" + + " (select cast(array[row(1)] as row(a integer) array)\n" + + " from (values (1)))) as d") + .type("RecordType(INTEGER NOT NULL A) NOT NULL"); + + // WITH ORDINALITY. + sql("select d.a\n" + + "from unnest(cast(array[row(1)] as row(a integer) array))\n" + + " with ordinality as d") + .columnType("INTEGER NOT NULL"); + + // NATURAL JOIN and USING match field name ("A"), not the alias ("D"). + // A column named after the alias does not count as a match. + sql("select *\n" + + "from unnest(cast(array[row(1)] as row(a integer) array)) as d\n" + + "natural join (select 1 as a) as t") + .type("RecordType(INTEGER NOT NULL A) NOT NULL"); + sql("select *\n" + + "from unnest(cast(array[row(1)] as row(a integer) array)) as d\n" + + "natural join (select 1 as d) as t") + .type("RecordType(INTEGER NOT NULL A, INTEGER NOT NULL D) NOT NULL"); + sql("select *\n" + + "from unnest(cast(array[row(1)] as row(a integer) array)) as d\n" + + "join (values (1)) as t (a) using (a)") + .type("RecordType(INTEGER NOT NULL A) NOT NULL"); + } + + /** Test case for + * [CALCITE-7791] + * UNNEST of a single-field ROW array loses the field name when aliased. + * + *

Under {@link SqlConformanceEnum#PRESTO} or {@code BIG_QUERY}, the + * struct element is not expanded into columns, so the alias renames the + * single ROW column instead of naming one of its fields. */ + @Test void testUnnestSingleFieldRowUnexpanded() { + sql("select *\n" + + "from unnest(cast(array[row(1)] as row(a integer) array)) as d") + .withConformance(SqlConformanceEnum.PRESTO) + .type("RecordType(RecordType(INTEGER NOT NULL A) NOT NULL D) NOT NULL"); } @Test void testCorrelationJoin() { diff --git a/core/src/test/resources/org/apache/calcite/test/SqlToRelConverterTest.xml b/core/src/test/resources/org/apache/calcite/test/SqlToRelConverterTest.xml index 2c32494f6061..917be8cb42e8 100644 --- a/core/src/test/resources/org/apache/calcite/test/SqlToRelConverterTest.xml +++ b/core/src/test/resources/org/apache/calcite/test/SqlToRelConverterTest.xml @@ -10315,6 +10315,20 @@ LogicalProject(EXPR$0=[$0]) Collect(field=[EXPR$0]) LogicalProject(EXPR$0=[$cor0.DEPTNO]) LogicalValues(tuples=[[{ 0 }]]) +]]> + + + + + + + + From bd11b19be240602b39d852b0d4fa822b51ed2fce Mon Sep 17 00:00:00 2001 From: Sean Broeder Date: Tue, 29 Sep 2026 14:42:31 -0700 Subject: [PATCH 3/9] More review comments addressed MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- .../type/SingleColumnAliasRelDataType.java | 12 ++++-- .../apache/calcite/sql/SqlUnnestOperator.java | 28 +++++++++++--- .../calcite/sql/validate/AliasNamespace.java | 30 ++++++++------- .../apache/calcite/test/SqlValidatorTest.java | 37 ++++++++++++++----- 4 files changed, 75 insertions(+), 32 deletions(-) diff --git a/core/src/main/java/org/apache/calcite/rel/type/SingleColumnAliasRelDataType.java b/core/src/main/java/org/apache/calcite/rel/type/SingleColumnAliasRelDataType.java index 28e0406f6717..050c8ed5c748 100644 --- a/core/src/main/java/org/apache/calcite/rel/type/SingleColumnAliasRelDataType.java +++ b/core/src/main/java/org/apache/calcite/rel/type/SingleColumnAliasRelDataType.java @@ -27,12 +27,16 @@ import java.util.List; /** - * Specific type of RelDataType that corresponds to a single column table, - * where column can have alias. + * Specific type of RelDataType where the first column can also be + * referenced by an alias. * *

For instance: *

select rmp, rmp.i from table(ramp(3)) as rmp;
* + *

{@code original} may have more than one field, for example a + * struct-array UNNEST WITH ORDINALITY, whose second field is ORDINALITY; + * only the first field gets the extra alias name. + * * @see org.apache.calcite.sql.validate.AliasNamespace */ public class SingleColumnAliasRelDataType implements RelDataType { @@ -40,7 +44,7 @@ public class SingleColumnAliasRelDataType implements RelDataType { private final RelDataType alias; public SingleColumnAliasRelDataType(RelDataType original, RelDataType alias) { - assert original.isStruct() && original.getFieldCount() == 1; + assert original.isStruct() && original.getFieldCount() >= 1; assert alias.isStruct() && alias.getFieldCount() == 1; this.original = original; this.alias = alias; @@ -59,7 +63,7 @@ public SingleColumnAliasRelDataType(RelDataType original, RelDataType alias) { } @Override public int getFieldCount() { - return 1; + return original.getFieldCount(); } @Override public StructKind getStructKind() { diff --git a/core/src/main/java/org/apache/calcite/sql/SqlUnnestOperator.java b/core/src/main/java/org/apache/calcite/sql/SqlUnnestOperator.java index 1460c4dd95b9..b53ec387577d 100644 --- a/core/src/main/java/org/apache/calcite/sql/SqlUnnestOperator.java +++ b/core/src/main/java/org/apache/calcite/sql/SqlUnnestOperator.java @@ -25,8 +25,11 @@ import org.apache.calcite.sql.type.OperandTypes; import org.apache.calcite.sql.type.SqlOperandCountRanges; import org.apache.calcite.sql.type.SqlTypeName; +import org.apache.calcite.sql.validate.SqlConformance; import org.apache.calcite.util.Util; +import org.apiguardian.api.API; + import static java.util.Objects.requireNonNull; /** @@ -76,9 +79,7 @@ public SqlUnnestOperator(boolean withOrdinality) { .build(); } - if (type.isStruct()) { - type = type.getFieldList().get(0).getType(); - } + type = unwrapOperandType(type); assert type instanceof ArraySqlType || type instanceof MultisetSqlType || type instanceof MapSqlType; @@ -128,9 +129,26 @@ public SqlUnnestOperator(boolean withOrdinality) { } /** - * Returns whether UNNEST expands {@code componentType} into one column - * per field, rather than a single column of the struct's own type. + * Returns the collection type that {@code operandType} denotes. + * + *

For a sub-query operand, {@code operandType} is a single-field + * struct; this returns the type of that field. + */ + @API(since = "1.43", status = API.Status.INTERNAL) + public static RelDataType unwrapOperandType(RelDataType operandType) { + return operandType.isStruct() ? operandType.getFieldList().get(0).getType() : operandType; + } + + /** + * Returns whether UNNEST expands an element of type {@code componentType} + * into one column per field. + * + * @param componentType element type of the collection + * @param allowAliasUnnestItems value of + * {@link SqlConformance#allowAliasUnnestItems()}; when true, a ROW + * element becomes a single column of the ROW type */ + @API(since = "1.43", status = API.Status.INTERNAL) public static boolean expandsStructIntoColumns(RelDataType componentType, boolean allowAliasUnnestItems) { return componentType.isStruct() && !allowAliasUnnestItems; diff --git a/core/src/main/java/org/apache/calcite/sql/validate/AliasNamespace.java b/core/src/main/java/org/apache/calcite/sql/validate/AliasNamespace.java index 27bb020daf78..3ae8107143a5 100644 --- a/core/src/main/java/org/apache/calcite/sql/validate/AliasNamespace.java +++ b/core/src/main/java/org/apache/calcite/sql/validate/AliasNamespace.java @@ -100,10 +100,11 @@ protected AliasNamespace( final RelDataType aliasedType; if (operands.size() == 2) { final SqlNode node = operands.get(0); - // 'AS t': the sole column is named after the alias, unless it's a - // struct-array UNNEST field (isUnnestOfStructArray), which keeps its name. + // 'AS t': the sole column is named after the alias, unless it is a + // field of the collection's ROW element. COLLECTION_TABLE's sole + // column keeps its own name the same way. final boolean isStructUnnest = node.getKind() == SqlKind.UNNEST - && isUnnestOfStructArray((SqlCall) node); + && keepsElementFieldName((SqlCall) node); if (rowType.getFieldCount() == 1) { final RelDataType singleColumnAlias = validator.getTypeFactory().builder() .kind(rowType.getStructKind()) @@ -112,12 +113,17 @@ protected AliasNamespace( .build(); aliasedType = node.getKind() == SqlKind.COLLECTION_TABLE || isStructUnnest ? new SingleColumnAliasRelDataType(rowType, singleColumnAlias) : singleColumnAlias; - // WITH ORDINALITY: data column named after the alias, unless it's - // a struct-array field, which keeps its name. } else if (node.getKind() == SqlKind.UNNEST && rowType.getFieldCount() == 2 && ((SqlUnnestOperator) ((SqlBasicCall) node).getOperator()).withOrdinality) { + // 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()) + .build(); aliasedType = isStructUnnest - ? rowType + ? new SingleColumnAliasRelDataType(rowType, dataColumnAlias) : validator.getTypeFactory().builder() .kind(rowType.getStructKind()) .add(((SqlIdentifier) operands.get(1)).getSimple(), @@ -164,16 +170,14 @@ protected AliasNamespace( } /** - * Returns whether the sole column of an aliased UNNEST is a field of + * Returns whether the data column of an aliased UNNEST is a field of * the collection's ROW element, which keeps its own name, rather than * a scalar column, which the alias renames. */ - private boolean isUnnestOfStructArray(SqlCall unnestCall) { - RelDataType operandType = validator.getValidatedNodeType(unnestCall.operand(0)); - if (operandType.isStruct()) { - // Sub-query operand: unwrap as SqlUnnestOperator#inferReturnType does. - operandType = operandType.getFieldList().get(0).getType(); - } + 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, diff --git a/core/src/test/java/org/apache/calcite/test/SqlValidatorTest.java b/core/src/test/java/org/apache/calcite/test/SqlValidatorTest.java index a645a33e0b9b..f28aa77144c2 100644 --- a/core/src/test/java/org/apache/calcite/test/SqlValidatorTest.java +++ b/core/src/test/java/org/apache/calcite/test/SqlValidatorTest.java @@ -10103,26 +10103,37 @@ void testGroupExpressionEquivalenceParams() { + "CHAR(6) NOT NULL EXPR$0) NOT NULL").ok(); // Test case for [CALCITE-7791] UNNEST of a single-field ROW array loses - // the field name when aliased. The array's field name ("A") survives - // star-expansion, and the alias ("D") still works to qualify it. + // the field name when aliased. The field name "A" survives + // star-expansion. The alias "D" still names the column and + // qualifies the field. sql("select d, d.a\n" + "from unnest(cast(array[row(1)] as row(a integer) array)) as d") .type("RecordType(INTEGER NOT NULL D, INTEGER NOT NULL A) NOT NULL"); - // UNNEST ROW array in a sub-query. + // A sub-query operand keeps the field name as well. sql("select *\n" + "from unnest(\n" + " (select cast(array[row(1)] as row(a integer) array)\n" + " from (values (1)))) as d") .type("RecordType(INTEGER NOT NULL A) NOT NULL"); - // WITH ORDINALITY. - sql("select d.a\n" + // WITH ORDINALITY keeps the field name and the alias still + // names the data column. + sql("select *\n" + "from unnest(cast(array[row(1)] as row(a integer) array))\n" + " with ordinality as d") - .columnType("INTEGER NOT NULL"); + .type("RecordType(INTEGER NOT NULL A, INTEGER NOT NULL ORDINALITY) NOT NULL"); + sql("select d, d.a\n" + + "from unnest(cast(array[row(1)] as row(a integer) array))\n" + + " with ordinality as d") + .type("RecordType(INTEGER NOT NULL D, INTEGER NOT NULL A) NOT NULL"); - // NATURAL JOIN and USING match field name ("A"), not the alias ("D"). + // UNNEST MULTISET gets the same treatment. + sql("select *\n" + + "from unnest(cast(multiset[row(1)] as row(a integer) multiset)) as d") + .type("RecordType(INTEGER NOT NULL A) NOT NULL"); + + // NATURAL JOIN and USING match the field name "A", not the alias "D". // A column named after the alias does not count as a match. sql("select *\n" + "from unnest(cast(array[row(1)] as row(a integer) array)) as d\n" @@ -10136,15 +10147,21 @@ void testGroupExpressionEquivalenceParams() { + "from unnest(cast(array[row(1)] as row(a integer) array)) as d\n" + "join (values (1)) as t (a) using (a)") .type("RecordType(INTEGER NOT NULL A) NOT NULL"); + // USING also accepts the alias, which resolves through the field. + sql("select *\n" + + "from unnest(cast(array[row(1)] as row(a integer) array)) as d\n" + + "join (values (1)) as t (d) using (d)") + .type("RecordType(INTEGER NOT NULL A) NOT NULL"); } /** Test case for * [CALCITE-7791] * UNNEST of a single-field ROW array loses the field name when aliased. * - *

Under {@link SqlConformanceEnum#PRESTO} or {@code BIG_QUERY}, the - * struct element is not expanded into columns, so the alias renames the - * single ROW column instead of naming one of its fields. */ + *

Under {@link SqlConformanceEnum#PRESTO} or + * {@link SqlConformanceEnum#BIG_QUERY}, the struct element is not + * expanded into columns, so the alias renames the single ROW column + * instead of naming one of its fields. */ @Test void testUnnestSingleFieldRowUnexpanded() { sql("select *\n" + "from unnest(cast(array[row(1)] as row(a integer) array)) as d") From 33a68262b7fe743024f0ccf6f7249dcd80ff0b65 Mon Sep 17 00:00:00 2001 From: Sean Broeder Date: Sat, 3 Oct 2026 08:17:43 -0700 Subject: [PATCH 4/9] More review comments addressed - Update comments to reflect actual behavior and remove ambiguity. - Add new tests in SqlValidatorTest and SqlToRelConverterTest. --- .../type/SingleColumnAliasRelDataType.java | 13 ++++++-- .../calcite/sql/validate/AliasNamespace.java | 12 ++++---- .../calcite/test/SqlToRelConverterTest.java | 14 +++++++++ .../apache/calcite/test/SqlValidatorTest.java | 20 +++++++++++++ .../calcite/test/SqlToRelConverterTest.xml | 30 +++++++++++++++++++ 5 files changed, 80 insertions(+), 9 deletions(-) diff --git a/core/src/main/java/org/apache/calcite/rel/type/SingleColumnAliasRelDataType.java b/core/src/main/java/org/apache/calcite/rel/type/SingleColumnAliasRelDataType.java index 050c8ed5c748..67516ba44af2 100644 --- a/core/src/main/java/org/apache/calcite/rel/type/SingleColumnAliasRelDataType.java +++ b/core/src/main/java/org/apache/calcite/rel/type/SingleColumnAliasRelDataType.java @@ -33,9 +33,11 @@ *

For instance: *

select rmp, rmp.i from table(ramp(3)) as rmp;
* - *

{@code original} may have more than one field, for example a - * struct-array UNNEST WITH ORDINALITY, whose second field is ORDINALITY; - * only the first field gets the extra alias name. + *

The wrapped type may have more than one field, for example + * UNNEST WITH ORDINALITY of a collection of single-field ROW values, whose + * second field is ORDINALITY; only the first field gets the extra alias name. + * If the alias equals the name of another field, that field wins (see + * {@link #getField}). * * @see org.apache.calcite.sql.validate.AliasNamespace */ @@ -70,6 +72,11 @@ public SingleColumnAliasRelDataType(RelDataType original, RelDataType alias) { return original.getStructKind(); } + /** + * Looks up {@code fieldName} in the wrapped type first, then in the alias. + * A name that matches a wrapped field resolves to that field; the alias is + * a fallback for names that match none. + */ @Override public @Nullable RelDataTypeField getField(final String fieldName, final boolean caseSensitive, final boolean elideRecord) { RelDataTypeField originalField = original.getField(fieldName, caseSensitive, elideRecord); diff --git a/core/src/main/java/org/apache/calcite/sql/validate/AliasNamespace.java b/core/src/main/java/org/apache/calcite/sql/validate/AliasNamespace.java index 3ae8107143a5..c98c8480705f 100644 --- a/core/src/main/java/org/apache/calcite/sql/validate/AliasNamespace.java +++ b/core/src/main/java/org/apache/calcite/sql/validate/AliasNamespace.java @@ -100,10 +100,10 @@ protected AliasNamespace( final RelDataType aliasedType; if (operands.size() == 2) { final SqlNode node = operands.get(0); - // 'AS t': the sole column is named after the alias, unless it is a - // field of the collection's ROW element. COLLECTION_TABLE's sole - // column keeps its own name the same way. - final boolean isStructUnnest = node.getKind() == SqlKind.UNNEST + // 'AS t': columns are named after the alias, except that a ROW element's + // field keeps its own name for star-expansion while the alias also names + // it. COLLECTION_TABLE handles its column the same way. + final boolean keepsElementFieldName = node.getKind() == SqlKind.UNNEST && keepsElementFieldName((SqlCall) node); if (rowType.getFieldCount() == 1) { final RelDataType singleColumnAlias = validator.getTypeFactory().builder() @@ -111,7 +111,7 @@ protected AliasNamespace( .add(((SqlIdentifier) operands.get(1)).getSimple(), rowType.getFieldList().get(0).getType()) .build(); - aliasedType = node.getKind() == SqlKind.COLLECTION_TABLE || isStructUnnest + aliasedType = node.getKind() == SqlKind.COLLECTION_TABLE || keepsElementFieldName ? new SingleColumnAliasRelDataType(rowType, singleColumnAlias) : singleColumnAlias; } else if (node.getKind() == SqlKind.UNNEST && rowType.getFieldCount() == 2 && ((SqlUnnestOperator) ((SqlBasicCall) node).getOperator()).withOrdinality) { @@ -122,7 +122,7 @@ protected AliasNamespace( .add(((SqlIdentifier) operands.get(1)).getSimple(), rowType.getFieldList().get(0).getType()) .build(); - aliasedType = isStructUnnest + aliasedType = keepsElementFieldName ? new SingleColumnAliasRelDataType(rowType, dataColumnAlias) : validator.getTypeFactory().builder() .kind(rowType.getStructKind()) diff --git a/core/src/test/java/org/apache/calcite/test/SqlToRelConverterTest.java b/core/src/test/java/org/apache/calcite/test/SqlToRelConverterTest.java index bb2bf618e13f..37e510c54d9c 100644 --- a/core/src/test/java/org/apache/calcite/test/SqlToRelConverterTest.java +++ b/core/src/test/java/org/apache/calcite/test/SqlToRelConverterTest.java @@ -2325,6 +2325,20 @@ private void checkCallTypesConsistent(String sql) { sql(sql).ok(); } + @Test void testUnnestSingleFieldRowWithOrdinality() { + final String sql = "select d, d.a\n" + + "from unnest(cast(array[row(1)] as row(a integer) array))\n" + + " with ordinality as d"; + sql(sql).ok(); + } + + @Test void testUnnestSingleFieldRowWithOrdinalityAllColumns() { + final String sql = "select d, d.a, d.ordinality\n" + + "from unnest(cast(array[row(1)] as row(a integer) array))\n" + + " with ordinality as d"; + sql(sql).ok(); + } + @Test void testUnnestSubQuery() { final String sql = "select*from unnest(multiset(select*from dept))"; sql(sql).ok(); diff --git a/core/src/test/java/org/apache/calcite/test/SqlValidatorTest.java b/core/src/test/java/org/apache/calcite/test/SqlValidatorTest.java index f28aa77144c2..9a9e0ec7bb9c 100644 --- a/core/src/test/java/org/apache/calcite/test/SqlValidatorTest.java +++ b/core/src/test/java/org/apache/calcite/test/SqlValidatorTest.java @@ -10127,6 +10127,26 @@ void testGroupExpressionEquivalenceParams() { + "from unnest(cast(array[row(1)] as row(a integer) array))\n" + " with ordinality as d") .type("RecordType(INTEGER NOT NULL D, INTEGER NOT NULL A) NOT NULL"); + // Sub-query operand with WITH ORDINALITY: alias names the data column. + sql("select d\n" + + "from unnest(\n" + + " (select cast(array[row(1)] as row(a integer) array)\n" + + " from (values (1))))\n" + + " with ordinality as d") + .type("RecordType(INTEGER NOT NULL D) NOT NULL"); + // USING (d) with WITH ORDINALITY: alias resolves, output keeps field names. + sql("select *\n" + + "from unnest(cast(array[row(1)] as row(a integer) array))\n" + + " with ordinality as d\n" + + "join (values (1)) as t (d) using (d)") + .type("RecordType(INTEGER NOT NULL A, INTEGER NOT NULL ORDINALITY) NOT NULL"); + // Correlated lateral: d, d.a, and d.ordinality all resolve. + sql("select d, d.a, d.ordinality\n" + + "from (values (array[row(1)])) as s (x),\n" + + " lateral unnest(cast(s.x as row(a integer) array))\n" + + " with ordinality as d") + .type("RecordType(INTEGER NOT NULL D, INTEGER NOT NULL A," + + " INTEGER NOT NULL ORDINALITY) NOT NULL"); // UNNEST MULTISET gets the same treatment. sql("select *\n" diff --git a/core/src/test/resources/org/apache/calcite/test/SqlToRelConverterTest.xml b/core/src/test/resources/org/apache/calcite/test/SqlToRelConverterTest.xml index 917be8cb42e8..666c3e966955 100644 --- a/core/src/test/resources/org/apache/calcite/test/SqlToRelConverterTest.xml +++ b/core/src/test/resources/org/apache/calcite/test/SqlToRelConverterTest.xml @@ -10329,6 +10329,36 @@ LogicalProject(D=[$0], A=[$0]) Uncollect LogicalProject(EXPR$0=[CAST(ARRAY(ROW(1))):RecordType(INTEGER NOT NULL A) NOT NULL ARRAY NOT NULL]) LogicalValues(tuples=[[{ 0 }]]) +]]> + + + + + + + + + + + + + + + + From 7c6b0c093afc87f0367dc8986866fadcfa66e684 Mon Sep 17 00:00:00 2001 From: Sean Broeder Date: Sun, 4 Oct 2026 06:36:21 -0700 Subject: [PATCH 5/9] Fix stale NATURAL JOIN / USING test comment 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. --- .../apache/calcite/sql/validate/AliasNamespace.java | 7 ++++--- .../apache/calcite/test/SqlToRelConverterTest.java | 6 ++++-- .../org/apache/calcite/test/SqlValidatorTest.java | 12 ++++++++++-- .../apache/calcite/test/SqlToRelConverterTest.xml | 6 +++--- 4 files changed, 21 insertions(+), 10 deletions(-) diff --git a/core/src/main/java/org/apache/calcite/sql/validate/AliasNamespace.java b/core/src/main/java/org/apache/calcite/sql/validate/AliasNamespace.java index c98c8480705f..d8f86d98ae5a 100644 --- a/core/src/main/java/org/apache/calcite/sql/validate/AliasNamespace.java +++ b/core/src/main/java/org/apache/calcite/sql/validate/AliasNamespace.java @@ -100,9 +100,10 @@ protected AliasNamespace( final RelDataType aliasedType; if (operands.size() == 2) { final SqlNode node = operands.get(0); - // 'AS t': columns are named after the alias, except that a ROW element's - // field keeps its own name for star-expansion while the alias also names - // it. COLLECTION_TABLE handles its column the same way. + // 'AS t' on a single-column result, or on UNNEST WITH ORDINALITY with one + // data column: the data column is named after the alias. A ROW element's + // field keeps its own name for star expansion, and the alias names it as + // well. COLLECTION_TABLE handles its column the same way. final boolean keepsElementFieldName = node.getKind() == SqlKind.UNNEST && keepsElementFieldName((SqlCall) node); if (rowType.getFieldCount() == 1) { diff --git a/core/src/test/java/org/apache/calcite/test/SqlToRelConverterTest.java b/core/src/test/java/org/apache/calcite/test/SqlToRelConverterTest.java index 37e510c54d9c..0c3c6f3beb56 100644 --- a/core/src/test/java/org/apache/calcite/test/SqlToRelConverterTest.java +++ b/core/src/test/java/org/apache/calcite/test/SqlToRelConverterTest.java @@ -2326,9 +2326,11 @@ private void checkCallTypesConsistent(String sql) { } @Test void testUnnestSingleFieldRowWithOrdinality() { - final String sql = "select d, d.a\n" + // Alias equals ORDINALITY: unqualified "ordinality" must project + // the ordinality column, not the data column named by the alias. + final String sql = "select ordinality\n" + "from unnest(cast(array[row(1)] as row(a integer) array))\n" - + " with ordinality as d"; + + " with ordinality as ordinality"; sql(sql).ok(); } diff --git a/core/src/test/java/org/apache/calcite/test/SqlValidatorTest.java b/core/src/test/java/org/apache/calcite/test/SqlValidatorTest.java index 9a9e0ec7bb9c..646179712faa 100644 --- a/core/src/test/java/org/apache/calcite/test/SqlValidatorTest.java +++ b/core/src/test/java/org/apache/calcite/test/SqlValidatorTest.java @@ -10147,13 +10147,21 @@ void testGroupExpressionEquivalenceParams() { + " with ordinality as d") .type("RecordType(INTEGER NOT NULL D, INTEGER NOT NULL A," + " INTEGER NOT NULL ORDINALITY) NOT NULL"); + // Alias equals ORDINALITY: unqualified name resolves to the INTEGER + // ordinality column, not the VARCHAR data column. The VARCHAR data field + // makes the two columns distinguishable and pins the getField lookup order. + sql("select ordinality\n" + + "from unnest(cast(array[row('x')] as row(a varchar(1)) array))\n" + + " with ordinality as ordinality") + .type("RecordType(INTEGER NOT NULL ORDINALITY) NOT NULL"); // UNNEST MULTISET gets the same treatment. sql("select *\n" + "from unnest(cast(multiset[row(1)] as row(a integer) multiset)) as d") .type("RecordType(INTEGER NOT NULL A) NOT NULL"); - // NATURAL JOIN and USING match the field name "A", not the alias "D". + // NATURAL JOIN matches the field name "A", not the alias "D". USING accepts + // either name. // A column named after the alias does not count as a match. sql("select *\n" + "from unnest(cast(array[row(1)] as row(a integer) array)) as d\n" @@ -10167,7 +10175,7 @@ void testGroupExpressionEquivalenceParams() { + "from unnest(cast(array[row(1)] as row(a integer) array)) as d\n" + "join (values (1)) as t (a) using (a)") .type("RecordType(INTEGER NOT NULL A) NOT NULL"); - // USING also accepts the alias, which resolves through the field. + // USING (d) matches the alias, and the output column is named A. sql("select *\n" + "from unnest(cast(array[row(1)] as row(a integer) array)) as d\n" + "join (values (1)) as t (d) using (d)") diff --git a/core/src/test/resources/org/apache/calcite/test/SqlToRelConverterTest.xml b/core/src/test/resources/org/apache/calcite/test/SqlToRelConverterTest.xml index 666c3e966955..fd62bbdd5d18 100644 --- a/core/src/test/resources/org/apache/calcite/test/SqlToRelConverterTest.xml +++ b/core/src/test/resources/org/apache/calcite/test/SqlToRelConverterTest.xml @@ -10334,13 +10334,13 @@ LogicalProject(D=[$0], A=[$0]) - + with ordinality as ordinality]]> Date: Sun, 4 Oct 2026 18:06:39 -0700 Subject: [PATCH 6/9] Remove check warning --- .../calcite/rel/type/SingleColumnAliasRelDataType.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/core/src/main/java/org/apache/calcite/rel/type/SingleColumnAliasRelDataType.java b/core/src/main/java/org/apache/calcite/rel/type/SingleColumnAliasRelDataType.java index 67516ba44af2..65ff853c9822 100644 --- a/core/src/main/java/org/apache/calcite/rel/type/SingleColumnAliasRelDataType.java +++ b/core/src/main/java/org/apache/calcite/rel/type/SingleColumnAliasRelDataType.java @@ -26,6 +26,8 @@ import java.nio.charset.Charset; import java.util.List; +import static com.google.common.base.Preconditions.checkArgument; + /** * Specific type of RelDataType where the first column can also be * referenced by an alias. @@ -46,8 +48,8 @@ public class SingleColumnAliasRelDataType implements RelDataType { private final RelDataType alias; 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); this.original = original; this.alias = alias; } From 07ea9f1e04b83f84c1e1a7f001d1694b7007b981 Mon Sep 17 00:00:00 2001 From: Sean Broeder Date: Fri, 23 Oct 2026 07:15:00 -0700 Subject: [PATCH 7/9] Adressing review comments - Reuse dataColumnAlias in AliasNamespace.java - testUnnestSingleFieldRowWithOrdinality renamed to testUnnestAliasOrdinalityResolvesToOrdinalityColumn - Added Javadoc to testUnnestAliasOrdinalityResolvesToOrdinalityColumn and testUnnestSingleFieldRowWithOrdinalityAllColumns --- .../calcite/sql/validate/AliasNamespace.java | 9 +++--- .../calcite/test/SqlToRelConverterTest.java | 12 +++++++- .../calcite/test/SqlToRelConverterTest.xml | 30 +++++++++---------- 3 files changed, 30 insertions(+), 21 deletions(-) diff --git a/core/src/main/java/org/apache/calcite/sql/validate/AliasNamespace.java b/core/src/main/java/org/apache/calcite/sql/validate/AliasNamespace.java index d8f86d98ae5a..c74d9383ee8c 100644 --- a/core/src/main/java/org/apache/calcite/sql/validate/AliasNamespace.java +++ b/core/src/main/java/org/apache/calcite/sql/validate/AliasNamespace.java @@ -127,8 +127,7 @@ protected AliasNamespace( ? new SingleColumnAliasRelDataType(rowType, dataColumnAlias) : validator.getTypeFactory().builder() .kind(rowType.getStructKind()) - .add(((SqlIdentifier) operands.get(1)).getSimple(), - rowType.getFieldList().get(0).getType()) + .addAll(dataColumnAlias.getFieldList()) .add(rowType.getFieldList().get(1)) .build(); } else { @@ -171,9 +170,9 @@ protected AliasNamespace( } /** - * Returns whether the data column of an aliased UNNEST is a field of - * the collection's ROW element, which keeps its own name, rather than - * a scalar column, which the alias renames. + * Returns whether UNNEST expands the collection's ROW element into one + * column per field. Such a column keeps its field name, and the alias + * names it as well; any other data column takes the alias as its name. */ private boolean keepsElementFieldName(SqlCall unnestCall) { final RelDataType operandType = diff --git a/core/src/test/java/org/apache/calcite/test/SqlToRelConverterTest.java b/core/src/test/java/org/apache/calcite/test/SqlToRelConverterTest.java index 0c3c6f3beb56..f7f444ac7f56 100644 --- a/core/src/test/java/org/apache/calcite/test/SqlToRelConverterTest.java +++ b/core/src/test/java/org/apache/calcite/test/SqlToRelConverterTest.java @@ -2325,7 +2325,12 @@ private void checkCallTypesConsistent(String sql) { sql(sql).ok(); } - @Test void testUnnestSingleFieldRowWithOrdinality() { + /** + * Test case for + * [CALCITE-7791] + * UNNEST of a single-field ROW array loses the field name when aliased. + */ + @Test void testUnnestAliasOrdinalityResolvesToOrdinalityColumn() { // Alias equals ORDINALITY: unqualified "ordinality" must project // the ordinality column, not the data column named by the alias. final String sql = "select ordinality\n" @@ -2334,6 +2339,11 @@ private void checkCallTypesConsistent(String sql) { sql(sql).ok(); } + /** + * Test case for + * [CALCITE-7791] + * UNNEST of a single-field ROW array loses the field name when aliased. + */ @Test void testUnnestSingleFieldRowWithOrdinalityAllColumns() { final String sql = "select d, d.a, d.ordinality\n" + "from unnest(cast(array[row(1)] as row(a integer) array))\n" diff --git a/core/src/test/resources/org/apache/calcite/test/SqlToRelConverterTest.xml b/core/src/test/resources/org/apache/calcite/test/SqlToRelConverterTest.xml index fd62bbdd5d18..ddfdf799770c 100644 --- a/core/src/test/resources/org/apache/calcite/test/SqlToRelConverterTest.xml +++ b/core/src/test/resources/org/apache/calcite/test/SqlToRelConverterTest.xml @@ -10179,6 +10179,21 @@ LogicalProject(EXPR$0=[$0]) + + + + + + + + @@ -10329,21 +10344,6 @@ LogicalProject(D=[$0], A=[$0]) Uncollect LogicalProject(EXPR$0=[CAST(ARRAY(ROW(1))):RecordType(INTEGER NOT NULL A) NOT NULL ARRAY NOT NULL]) LogicalValues(tuples=[[{ 0 }]]) -]]> - - - - - - - - From 1e5e6f9c47f4b6c2fc8c57a8bd47653514aa6f9b Mon Sep 17 00:00:00 2001 From: Sean Broeder Date: Sun, 15 Nov 2026 06:52:30 -0800 Subject: [PATCH 8/9] Update core/src/test/java/org/apache/calcite/test/SqlValidatorTest.java Co-authored-by: Vladimir Sitnikov --- .../test/java/org/apache/calcite/test/SqlValidatorTest.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/core/src/test/java/org/apache/calcite/test/SqlValidatorTest.java b/core/src/test/java/org/apache/calcite/test/SqlValidatorTest.java index 646179712faa..5576629a80b0 100644 --- a/core/src/test/java/org/apache/calcite/test/SqlValidatorTest.java +++ b/core/src/test/java/org/apache/calcite/test/SqlValidatorTest.java @@ -10106,6 +10106,9 @@ void testGroupExpressionEquivalenceParams() { // the field name when aliased. The field name "A" survives // star-expansion. The alias "D" still names the column and // qualifies the field. + sql("select *\n" + + "from unnest(cast(array[row(1)] as row(a integer) array)) as d") + .type("RecordType(INTEGER NOT NULL A) NOT NULL"); sql("select d, d.a\n" + "from unnest(cast(array[row(1)] as row(a integer) array)) as d") .type("RecordType(INTEGER NOT NULL D, INTEGER NOT NULL A) NOT NULL"); From c0aac8317767b5b85706228ff72c55dc5a492e4f Mon Sep 17 00:00:00 2001 From: Sean Broeder Date: Sun, 15 Nov 2026 08:52:56 -0800 Subject: [PATCH 9/9] Addressing review comments - 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. --- .../rel/type/RelDataTypeFactoryImpl.java | 8 +- .../type/SingleColumnAliasRelDataType.java | 27 ++- .../calcite/sql/validate/AliasNamespace.java | 37 +++- .../calcite/test/SqlToRelConverterTest.java | 169 ++++++++++++++ .../apache/calcite/test/SqlValidatorTest.java | 52 +++++ .../calcite/test/SqlToRelConverterTest.xml | 207 ++++++++++++++++++ site/_docs/history.md | 12 + 7 files changed, 497 insertions(+), 15 deletions(-) diff --git a/core/src/main/java/org/apache/calcite/rel/type/RelDataTypeFactoryImpl.java b/core/src/main/java/org/apache/calcite/rel/type/RelDataTypeFactoryImpl.java index c0d90578fa7a..653010102b2c 100644 --- a/core/src/main/java/org/apache/calcite/rel/type/RelDataTypeFactoryImpl.java +++ b/core/src/main/java/org/apache/calcite/rel/type/RelDataTypeFactoryImpl.java @@ -390,7 +390,13 @@ private RelDataType copyRecordType( final boolean nullable) { requireNonNull(type, "type"); RelDataType newType; - if (type.isNullable() == nullable) { + if (type instanceof SingleColumnAliasRelDataType) { + // Preserve the alias wrapper, applying nullability to both wrapped types. + final SingleColumnAliasRelDataType aliasType = (SingleColumnAliasRelDataType) type; + return new SingleColumnAliasRelDataType( + createTypeWithNullability(aliasType.getOriginal(), nullable), + createTypeWithNullability(aliasType.getAlias(), nullable)); + } else if (type.isNullable() == nullable) { newType = type; } else if (type instanceof RelRecordType) { // REVIEW: angel 18-Aug-2005 dtbug 336 workaround diff --git a/core/src/main/java/org/apache/calcite/rel/type/SingleColumnAliasRelDataType.java b/core/src/main/java/org/apache/calcite/rel/type/SingleColumnAliasRelDataType.java index 65ff853c9822..813e0bd4525e 100644 --- a/core/src/main/java/org/apache/calcite/rel/type/SingleColumnAliasRelDataType.java +++ b/core/src/main/java/org/apache/calcite/rel/type/SingleColumnAliasRelDataType.java @@ -47,13 +47,36 @@ public class SingleColumnAliasRelDataType implements RelDataType { private final RelDataType original; private final RelDataType alias; + /** + * Creates a SingleColumnAliasRelDataType. + * + * @param original Row type whose fields are exposed; a struct with at + * least one field + * @param alias Struct with exactly one field, named after the alias, whose + * type is that of the first field of {@code original} + * + * @throws IllegalArgumentException if either type does not have the + * required shape + */ public SingleColumnAliasRelDataType(RelDataType original, RelDataType alias) { - checkArgument(original.isStruct() && original.getFieldCount() >= 1); - checkArgument(alias.isStruct() && alias.getFieldCount() == 1); + checkArgument(original.isStruct() && original.getFieldCount() >= 1, + "original must be a struct with at least one field: %s", original); + checkArgument(alias.isStruct() && alias.getFieldCount() == 1, + "alias must be a struct with exactly one field: %s", alias); this.original = original; this.alias = alias; } + /** Returns the wrapped type whose fields are exposed. */ + public RelDataType getOriginal() { + return original; + } + + /** Returns the single-field type that supplies the extra alias name. */ + public RelDataType getAlias() { + return alias; + } + @Override public boolean isStruct() { return true; } diff --git a/core/src/main/java/org/apache/calcite/sql/validate/AliasNamespace.java b/core/src/main/java/org/apache/calcite/sql/validate/AliasNamespace.java index c74d9383ee8c..0ca5afd71f31 100644 --- a/core/src/main/java/org/apache/calcite/sql/validate/AliasNamespace.java +++ b/core/src/main/java/org/apache/calcite/sql/validate/AliasNamespace.java @@ -28,6 +28,7 @@ import org.apache.calcite.sql.SqlNode; import org.apache.calcite.sql.SqlNodeList; import org.apache.calcite.sql.SqlUnnestOperator; +import org.apache.calcite.sql.SqlUtil; import org.apache.calcite.sql.fun.SqlStdOperatorTable; import org.apache.calcite.sql.parser.SqlParserPos; import org.apache.calcite.util.Pair; @@ -107,22 +108,16 @@ protected AliasNamespace( final boolean keepsElementFieldName = node.getKind() == SqlKind.UNNEST && keepsElementFieldName((SqlCall) node); 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(); + final RelDataType dataColumnAlias = + aliasDataColumn(rowType, (SqlIdentifier) operands.get(1)); aliasedType = node.getKind() == SqlKind.COLLECTION_TABLE || keepsElementFieldName - ? new SingleColumnAliasRelDataType(rowType, singleColumnAlias) : singleColumnAlias; + ? new SingleColumnAliasRelDataType(rowType, dataColumnAlias) : dataColumnAlias; } else if (node.getKind() == SqlKind.UNNEST && rowType.getFieldCount() == 2 && ((SqlUnnestOperator) ((SqlBasicCall) node).getOperator()).withOrdinality) { // 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()) - .build(); + final RelDataType dataColumnAlias = + aliasDataColumn(rowType, (SqlIdentifier) operands.get(1)); aliasedType = keepsElementFieldName ? new SingleColumnAliasRelDataType(rowType, dataColumnAlias) : validator.getTypeFactory().builder() @@ -169,6 +164,15 @@ protected AliasNamespace( } } + /** Returns a single-field struct holding the first column of + * {@code rowType}, named after the alias. */ + private RelDataType aliasDataColumn(RelDataType rowType, SqlIdentifier alias) { + return validator.getTypeFactory().builder() + .kind(rowType.getStructKind()) + .add(alias.getSimple(), rowType.getFieldList().get(0).getType()) + .build(); + } + /** * Returns whether UNNEST expands the collection's ROW element into one * column per field. Such a column keeps its field name, and the alias @@ -181,7 +185,16 @@ private boolean keepsElementFieldName(SqlCall unnestCall) { final RelDataType componentType = operandType.getComponentType(); return componentType != null && SqlUnnestOperator.expandsStructIntoColumns(componentType, - validator.config().conformance().allowAliasUnnestItems()); + validator.config().conformance().allowAliasUnnestItems()) + && !hasGeneratedFirstFieldName(componentType); + } + + /** Returns whether the first field of a ROW element has a generated name, + * such as {@code EXPR$0} for {@code ROW(1)}. The alias then names the + * column, because a generated name is not worth keeping. */ + private static boolean hasGeneratedFirstFieldName(RelDataType componentType) { + final List fields = componentType.getFieldList(); + return !fields.isEmpty() && SqlUtil.isGeneratedAlias(fields.get(0).getName()); } private static String getString(RelDataType rowType) { diff --git a/core/src/test/java/org/apache/calcite/test/SqlToRelConverterTest.java b/core/src/test/java/org/apache/calcite/test/SqlToRelConverterTest.java index f7f444ac7f56..2f7d023eee81 100644 --- a/core/src/test/java/org/apache/calcite/test/SqlToRelConverterTest.java +++ b/core/src/test/java/org/apache/calcite/test/SqlToRelConverterTest.java @@ -2351,6 +2351,175 @@ private void checkCallTypesConsistent(String sql) { sql(sql).ok(); } + /** + * Test case for + * [CALCITE-7791] + * UNNEST of a single-field ROW array loses the field name when aliased. + * + *

The aliased UNNEST is on the null-generating side of an outer join, + * so its columns must become nullable. */ + @Test void testUnnestSingleFieldRowLeftJoinAlias() { + final String sql = "select d\n" + + "from dept\n" + + "left join unnest(cast(array[row(1)] as row(a integer) array)) as d on true"; + sql(sql).ok(); + } + + /** + * Test case for + * [CALCITE-7791] + * UNNEST of a single-field ROW array loses the field name when aliased. + * + *

The aliased UNNEST is on the null-generating side of an outer join, + * so its columns must become nullable. */ + @Test void testUnnestSingleFieldRowLeftJoinField() { + final String sql = "select d.a\n" + + "from dept\n" + + "left join unnest(cast(array[row(1)] as row(a integer) array)) as d on true"; + sql(sql).ok(); + } + + /** + * Test case for + * [CALCITE-7791] + * UNNEST of a single-field ROW array loses the field name when aliased. + * + *

The aliased UNNEST is on the null-generating side of an outer join, + * so its columns must become nullable. */ + @Test void testUnnestSingleFieldRowLeftJoinOrdinalityAlias() { + final String sql = "select d\n" + + "from dept\n" + + "left join unnest(cast(array[row(1)] as row(a integer) array)) with ordinality as d on true"; + sql(sql).ok(); + } + + /** + * Test case for + * [CALCITE-7791] + * UNNEST of a single-field ROW array loses the field name when aliased. + * + *

The aliased UNNEST is on the null-generating side of an outer join, + * so its columns must become nullable. */ + @Test void testUnnestSingleFieldRowLeftJoinOrdinalityField() { + final String sql = "select d.a\n" + + "from dept\n" + + "left join unnest(cast(array[row(1)] as row(a integer) array)) with ordinality as d on true"; + sql(sql).ok(); + } + + /** + * Test case for + * [CALCITE-7791] + * UNNEST of a single-field ROW array loses the field name when aliased. + * + *

The aliased UNNEST is on the null-generating side of an outer join, + * so its columns must become nullable. */ + @Test void testUnnestSingleFieldRowRightJoinAlias() { + final String sql = "select d\n" + + "from unnest(cast(array[row(1)] as row(a integer) array)) as d\n" + + "right join dept on true"; + sql(sql).ok(); + } + + /** + * Test case for + * [CALCITE-7791] + * UNNEST of a single-field ROW array loses the field name when aliased. + * + *

The aliased UNNEST is on the null-generating side of an outer join, + * so its columns must become nullable. */ + @Test void testUnnestSingleFieldRowRightJoinField() { + final String sql = "select d.a\n" + + "from unnest(cast(array[row(1)] as row(a integer) array)) as d\n" + + "right join dept on true"; + sql(sql).ok(); + } + + /** + * Test case for + * [CALCITE-7791] + * UNNEST of a single-field ROW array loses the field name when aliased. + * + *

The aliased UNNEST is on the null-generating side of an outer join, + * so its columns must become nullable. */ + @Test void testUnnestSingleFieldRowRightJoinOrdinalityAlias() { + final String sql = "select d\n" + + "from unnest(cast(array[row(1)] as row(a integer) array)) with ordinality as d\n" + + "right join dept on true"; + sql(sql).ok(); + } + + /** + * Test case for + * [CALCITE-7791] + * UNNEST of a single-field ROW array loses the field name when aliased. + * + *

The aliased UNNEST is on the null-generating side of an outer join, + * so its columns must become nullable. */ + @Test void testUnnestSingleFieldRowRightJoinOrdinalityField() { + final String sql = "select d.a\n" + + "from unnest(cast(array[row(1)] as row(a integer) array)) with ordinality as d\n" + + "right join dept on true"; + sql(sql).ok(); + } + + /** + * Test case for + * [CALCITE-7791] + * UNNEST of a single-field ROW array loses the field name when aliased. + * + *

A {@code TABLE(...) AS alias} on the null-generating side of an outer + * join becomes nullable. */ + @Test void testTableFunctionAliasLeftJoin() { + final String sql = "select rmp, rmp.i\n" + + "from dept\n" + + "left join table(ramp(3)) as rmp on true"; + sql(sql).ok(); + } + + /** + * Test case for + * [CALCITE-7791] + * UNNEST of a single-field ROW array loses the field name when aliased. + * + *

As {@link #testTableFunctionAliasLeftJoin()} but a RIGHT JOIN. */ + @Test void testTableFunctionAliasRightJoin() { + final String sql = "select rmp, rmp.i\n" + + "from table(ramp(3)) as rmp\n" + + "right join dept on true"; + sql(sql).ok(); + } + + /** + * Test case for + * [CALCITE-7791] + * UNNEST of a single-field ROW array loses the field name when aliased. + * + *

The element's field name is generated, so NATURAL JOIN of two aliased + * UNNESTs has no common column and is a cross join. */ + @Test void testUnnestAnonymousRowNaturalJoin() { + final String sql = "select * from unnest(array[row(1)]) as a\n" + + "natural join unnest(array[row(2)]) as b"; + sql(sql).ok(); + } + + /** + * Test case for + * [CALCITE-7791] + * UNNEST of a single-field ROW array loses the field name when aliased. + * + *

The correlation field of a table to the right of an aliased ROW-element + * UNNEST WITH ORDINALITY is offset by the UNNEST's field count, so this pins + * {@code SingleColumnAliasRelDataType.getFieldCount()}. */ + @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)"; + sql(sql).withDecorrelate(false).withExpand(false).ok(); + } + @Test void testUnnestSubQuery() { final String sql = "select*from unnest(multiset(select*from dept))"; sql(sql).ok(); diff --git a/core/src/test/java/org/apache/calcite/test/SqlValidatorTest.java b/core/src/test/java/org/apache/calcite/test/SqlValidatorTest.java index 5576629a80b0..50f5552e64c3 100644 --- a/core/src/test/java/org/apache/calcite/test/SqlValidatorTest.java +++ b/core/src/test/java/org/apache/calcite/test/SqlValidatorTest.java @@ -10158,6 +10158,58 @@ void testGroupExpressionEquivalenceParams() { + " with ordinality as ordinality") .type("RecordType(INTEGER NOT NULL ORDINALITY) NOT NULL"); + // On the null-generating side of an outer join, the alias and the field + // are nullable. + sql("select d, d.a\n" + + "from dept\n" + + "left join unnest(cast(array[row(1)] as row(a integer) array)) as d on true") + .type("RecordType(INTEGER D, INTEGER A) NOT NULL"); + sql("select d, d.a\n" + + "from unnest(cast(array[row(1)] as row(a integer) array)) as d\n" + + "right join dept on true") + .type("RecordType(INTEGER D, INTEGER A) NOT NULL"); + sql("select d, d.a\n" + + "from dept\n" + + "left join unnest(cast(array[row(1)] as row(a integer) array)) with ordinality as d on true") + .type("RecordType(INTEGER D, INTEGER A) NOT NULL"); + sql("select d, d.a\n" + + "from unnest(cast(array[row(1)] as row(a integer) array)) with ordinality as d\n" + + "right join dept on true") + .type("RecordType(INTEGER D, INTEGER A) NOT NULL"); + + // The element's field name is generated (EXPR$0), not declared, so the + // alias names the column, as it does for any other single-column UNNEST. + sql("select * from unnest(array[row(1)]) as d") + .type("RecordType(INTEGER NOT NULL D) NOT NULL"); + sql("select * from unnest(array[row(1)]) with ordinality as d") + .type("RecordType(INTEGER NOT NULL D, INTEGER NOT NULL ORDINALITY) NOT NULL"); + sql("select *\n" + + "from unnest(\n" + + " (select array[row(1)] from (values (1)))) as d") + .type("RecordType(INTEGER NOT NULL D) NOT NULL"); + // Two such UNNESTs keep distinct column names, so NATURAL JOIN has no + // common column and is a cross join. + sql("select * from unnest(array[row(1)]) as a\n" + + "natural join unnest(array[row(2)]) as b") + .type("RecordType(INTEGER NOT NULL A, INTEGER NOT NULL B) NOT NULL"); + + // Edge case: generated names are recognized by their "EXPR$" prefix, so a + // declared field whose name starts with "EXPR$" is treated as generated + // and the alias names the column. + sql("select *\n" + + "from unnest(cast(array[row(1)] as row(\"EXPR$x\" integer) array)) as d") + .type("RecordType(INTEGER NOT NULL D) NOT NULL"); + + // Workaround: a column list renames the column, so 'AS d (d)' makes the + // alias the column name again. + sql("select *\n" + + "from unnest(cast(array[row(1)] as row(a integer) array)) as d (d)") + .type("RecordType(INTEGER NOT NULL D) NOT NULL"); + sql("select *\n" + + "from unnest(cast(array[row(1)] as row(a integer) array))\n" + + " with ordinality as d (d, o)") + .type("RecordType(INTEGER NOT NULL D, INTEGER NOT NULL O) NOT NULL"); + // UNNEST MULTISET gets the same treatment. sql("select *\n" + "from unnest(cast(multiset[row(1)] as row(a integer) multiset)) as d") diff --git a/core/src/test/resources/org/apache/calcite/test/SqlToRelConverterTest.xml b/core/src/test/resources/org/apache/calcite/test/SqlToRelConverterTest.xml index ddfdf799770c..f968652a6854 100644 --- a/core/src/test/resources/org/apache/calcite/test/SqlToRelConverterTest.xml +++ b/core/src/test/resources/org/apache/calcite/test/SqlToRelConverterTest.xml @@ -9198,6 +9198,36 @@ LogicalProject(EXPR$0=[+($0, $2)]) + + + + + + + + + + + + + + + + @@ -10191,6 +10221,24 @@ LogicalProject(ORDINALITY=[$1]) Uncollect(withOrdinality=[true]) LogicalProject(EXPR$0=[CAST(ARRAY(ROW(1))):RecordType(INTEGER NOT NULL A) NOT NULL ARRAY NOT NULL]) LogicalValues(tuples=[[{ 0 }]]) +]]> + + + + + + + + @@ -10344,6 +10392,165 @@ LogicalProject(D=[$0], A=[$0]) Uncollect LogicalProject(EXPR$0=[CAST(ARRAY(ROW(1))):RecordType(INTEGER NOT NULL A) NOT NULL ARRAY NOT NULL]) LogicalValues(tuples=[[{ 0 }]]) +]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/site/_docs/history.md b/site/_docs/history.md index cc4e1e9ebbbd..004802505bf7 100644 --- a/site/_docs/history.md +++ b/site/_docs/history.md @@ -125,6 +125,18 @@ and `GeodeSimpleSchemaFactory`) now requires the operator-level opt-in system pr `-Dcalcite.geode.pdxSerializablePackagePath.allowed=true`. A model that sets the operand without the opt-in will fail. Java callers of `GeodeUtils.createClientCache` are unaffected. +* [CALCITE-7791] +Under the default conformance, `select *` over an aliased UNNEST of single-field +ROW values (plain, `WITH ORDINALITY`, sub-query operand, or MULTISET) now returns +the declared field name instead of the alias: `select * from unnest(cast(array[row(1)] +as row(a integer) array)) as d` returns column `A`, not `D`. `NATURAL JOIN` matches +the field name, and `USING` accepts either the field name or the alias; the alias +still qualifies the field (`d.a`). When the field name is generated (for example +`ROW(1)`), the alias still names the column, as before. Conformances where +`allowAliasUnnestItems` is true, such as `PRESTO` and `BIG_QUERY`, are unaffected. +To keep the alias as the output column name, write `AS d (d)`; a `USING (d)` +join can still refer to the column by the alias, but its output keeps the field name. + #### New features {: #new-features-1-43-0}