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 19e4324fc18f..daadb0c195a3 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 @@ -414,7 +414,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 8839ce1ab4f3..afb6f6387061 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,26 +26,57 @@ import java.nio.charset.Charset; import java.util.List; +import static com.google.common.base.Preconditions.checkArgument; + /** - * 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;
* + *

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 */ 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) { - assert original.isStruct() && original.getFieldCount() == 1; - assert 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; } @@ -59,13 +90,18 @@ public SingleColumnAliasRelDataType(RelDataType original, RelDataType alias) { } @Override public int getFieldCount() { - return 1; + return original.getFieldCount(); } @Override public StructKind getStructKind() { 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/SqlUnnestOperator.java b/core/src/main/java/org/apache/calcite/sql/SqlUnnestOperator.java index 487563125919..126803280d0b 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; /** @@ -77,9 +80,7 @@ public SqlUnnestOperator(boolean withOrdinality) { return builder.build(); } - if (type.isStruct()) { - type = type.getFieldList().get(0).getType(); - } + type = unwrapOperandType(type); assert type instanceof ArraySqlType || type instanceof MultisetSqlType || type instanceof MapSqlType; @@ -100,10 +101,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) { @@ -131,6 +129,32 @@ public SqlUnnestOperator(boolean withOrdinality) { return builder.build(); } + /** + * 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; + } + 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 f3c04dbca0ae..6de274f1e7ca 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; @@ -103,29 +104,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' 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) { - 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 - ? 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. + final RelDataType dataColumnAlias = + aliasDataColumn(rowType, (SqlIdentifier) operands.get(1)); + aliasedType = node.getKind() == SqlKind.COLLECTION_TABLE || keepsElementFieldName + ? new SingleColumnAliasRelDataType(rowType, dataColumnAlias) : dataColumnAlias; } 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(); + // WITH ORDINALITY: data column, ordinality column. The data + // column is named after the alias, same as the single-column case. + final RelDataType dataColumnAlias = + aliasDataColumn(rowType, (SqlIdentifier) operands.get(1)); + aliasedType = keepsElementFieldName + ? new SingleColumnAliasRelDataType(rowType, dataColumnAlias) + : validator.getTypeFactory().builder() + .kind(rowType.getStructKind()) + .addAll(dataColumnAlias.getFieldList()) + .add(rowType.getFieldList().get(1)) + .build(); } else { aliasedType = rowType; } @@ -165,6 +167,39 @@ 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 + * names it as well; any other data column takes the alias as its 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()) + && !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) { StringBuilder buf = new StringBuilder(); buf.append("("); 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 628474979972..191b8104afd7 100644 --- a/core/src/test/java/org/apache/calcite/test/SqlToRelConverterTest.java +++ b/core/src/test/java/org/apache/calcite/test/SqlToRelConverterTest.java @@ -2438,6 +2438,212 @@ 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 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" + + "from unnest(cast(array[row(1)] as row(a integer) array))\n" + + " with ordinality as ordinality"; + 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" + + " with ordinality as d"; + 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 cc444c7f7c4d..20e08658db96 100644 --- a/core/src/test/java/org/apache/calcite/test/SqlValidatorTest.java +++ b/core/src/test/java/org/apache/calcite/test/SqlValidatorTest.java @@ -10475,6 +10475,155 @@ void testOrderByAliasPreservesValidatedExpressions(String query) { 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 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"); + + // 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 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") + .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"); + // 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"); + // 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"); + + // 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") + .type("RecordType(INTEGER NOT NULL A) NOT NULL"); + + // 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" + + "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"); + // 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)") + .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 + * {@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") + .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 3fd82ebfef35..933954c1ac00 100644 --- a/core/src/test/resources/org/apache/calcite/test/SqlToRelConverterTest.xml +++ b/core/src/test/resources/org/apache/calcite/test/SqlToRelConverterTest.xml @@ -9871,6 +9871,36 @@ LogicalProject(EXPR$0=[+($0, $2)]) + + + + + + + + + + + + + + + + @@ -10852,6 +10882,39 @@ LogicalProject(EXPR$0=[$0]) + + + + + + + + + + + + + + + + @@ -11007,6 +11070,194 @@ LogicalProject(EXPR$0=[$0]) Collect(field=[EXPR$0]) LogicalProject(EXPR$0=[$cor0.DEPTNO]) LogicalValues(tuples=[[{ 0 }]]) +]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/site/_docs/history.md b/site/_docs/history.md index 100869a0a585..5a28f6391123 100644 --- a/site/_docs/history.md +++ b/site/_docs/history.md @@ -150,6 +150,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. + * [CALCITE-7906] `LikePattern`, which handles the patterns passed to JDBC `DatabaseMetaData` methods such as `getTables` and `getColumns` and to `Lookup.getNames`, now supports the `_` wildcard (any single