vlsi commented on code in PR #5271:
URL: https://github.com/apache/calcite/pull/5271#discussion_r4575408175


##########
core/src/main/java/org/apache/calcite/sql/validate/AliasNamespace.java:
##########
@@ -162,6 +169,21 @@ protected AliasNamespace(
     }
   }
 
+  /**
+   * 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());
+  }

Review Comment:
   **F2 major** An aliased UNNEST of an anonymous single-field ROW array now 
exposes the generated field name EXPR$0 instead of the alias, so `select *` 
loses the alias and NATURAL JOIN of two such UNNESTs becomes an equi-join.
   
   Problem: keepsElementFieldName is true for every single-field ROW element, 
including `ROW(1)`, whose field name is generated. Two aliased UNNESTs in one 
FROM clause give `EXPR$0, EXPR$00` instead of `A, B`, and a NATURAL JOIN 
between them now filters rows where the base did a cross join, without an 
error. WITH ORDINALITY and a sub-query operand behave the same. The thread that 
settled the field name as canonical ("the field name is what star-expansion and 
NATURAL JOIN use") considered a declared name such as `A`, not a generated one.
   
   ```sql
   select * from unnest(array[row(1)]) as d;
   -- head: RecordType(INTEGER NOT NULL EXPR$0)   base: RecordType(INTEGER NOT 
NULL D)
   
   select * from unnest(array[row(1)]) as a natural join unnest(array[row(2)]) 
as b;
   -- head: (EXPR$0), LogicalJoin(condition=[=($0, $1)]), no rows
   -- base: (A, B), LogicalJoin(condition=[true])
   
   select * from unnest(array[row(1)]) with ordinality as d;
   -- head: (EXPR$0, ORDINALITY)   base: (D, ORDINALITY)
   ```
   
   Proposed solution: Keep the base behavior, the alias as the column name, 
when the element's single field name is generated, for example by also 
requiring `!SqlUtil.isGeneratedAlias(...)` of that name in 
keepsElementFieldName, and add a testUnnestAlias case for 
`unnest(array[row(1)]) as d`. If the generated name is meant to win, state it 
in the PR description and the JIRA release note and pin it with a test.



##########
core/src/main/java/org/apache/calcite/sql/validate/AliasNamespace.java:
##########
@@ -100,29 +100,36 @@ 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
+        aliasedType = node.getKind() == SqlKind.COLLECTION_TABLE || 
keepsElementFieldName
             ? new SingleColumnAliasRelDataType(rowType, singleColumnAlias) : 
singleColumnAlias;
-        // If the sub-query is UNNEST with ordinality
-        // and the sub-query has two columns: data column, ordinality column
-        // then the namespace's sole column is named after the alias.
       } else if (node.getKind() == SqlKind.UNNEST && rowType.getFieldCount() 
== 2
           && ((SqlUnnestOperator) ((SqlBasicCall) 
node).getOperator()).withOrdinality) {
-        aliasedType = validator.getTypeFactory().builder()
+        // WITH ORDINALITY: data column, ordinality column. The data
+        // column is named after the alias, same as the single-column case.
+        final RelDataType dataColumnAlias = 
validator.getTypeFactory().builder()
             .kind(rowType.getStructKind())
             .add(((SqlIdentifier) operands.get(1)).getSimple(),
                 rowType.getFieldList().get(0).getType())
-            .add(rowType.getFieldList().get(1))
             .build();
+        aliasedType = keepsElementFieldName
+            ? new SingleColumnAliasRelDataType(rowType, dataColumnAlias)

Review Comment:
   **F1 major** An aliased UNNEST of a single-field ROW array on the 
null-generating side of a LEFT or RIGHT JOIN now validates its column as NOT 
NULL, and SqlToRelConverter rejects the query, which converted on the base.
   
   Problem: The validator's outer-join nullability does not reach a 
SingleColumnAliasRelDataType, so a column reference through it (`d`, `d.a`, `d 
+ 1`, `d.ordinality`) keeps NOT NULL while the converted plan makes it 
nullable, and conversion throws `AssertionError: Conversion to relational 
algebra failed to preserve datatypes`. The throw is unconditional, so it does 
not depend on `-ea`. Plain UNNEST and WITH ORDINALITY fail alike; only `select 
*` converts. TABLE(...) AS alias, which the base already wraps, fails the same 
way at the base, so a fix inside the UNNEST branch alone leaves it.
   
   <details><summary>Reproducer</summary>
   
   ```java
   // SqlToRelConverterTest
   @Test void testUnnestSingleFieldRowAliasOnNullableSide() {
     sql("select d, d.a from (values 1) as t (x)\n"
         + "left join unnest(cast(array[row(1)] as row(a integer) array)) as d 
on true").ok();
     sql("select d, d.ordinality from (values 1) as t (x)\n"
         + "left join unnest(cast(array[row(1)] as row(a integer) array))\n"
         + "  with ordinality as d on true").ok();
     sql("select d from unnest(cast(array[row(1)] as row(a integer) array)) as 
d\n"
         + "right join (values 1) as t (x) on true").ok();
     // head: AssertionError: Conversion to relational algebra failed to 
preserve datatypes
     //   validated type: RecordType(INTEGER NOT NULL D) NOT NULL
     //   converted type: RecordType(INTEGER D) NOT NULL
     // expected (base 9634752f for `d`): validated RecordType(INTEGER D) NOT 
NULL, plan converts
   }
   ```
   
   </details>
   
   Proposed solution: Make the nullable copy of a SingleColumnAliasRelDataType 
a SingleColumnAliasRelDataType over nullable copies of both wrapped types, for 
example in RelDataTypeFactoryImpl.createTypeWithNullability, which fixes 
TABLE(...) AS alias with it. Add SqlToRelConverterTest cases, with their 
validator types in testUnnestAlias, for the aliased UNNEST on the 
null-generating side of a LEFT and a RIGHT JOIN, plain and WITH ORDINALITY, 
selecting the alias and the field name.



##########
core/src/test/java/org/apache/calcite/test/SqlValidatorTest.java:
##########
@@ -10101,6 +10101,100 @@ 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 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");

Review Comment:
   **F4 minor** The test comment says the field name "A" survives 
star-expansion, but the query under it is `select d, d.a`, and no case runs a 
plain `select *` over the aliased ROW array.
   
   Problem: A reader takes the comment as the description of the query below it 
and concludes that the headline case of CALCITE-7791 is pinned directly; the 
plain array appears with `select *` only under NATURAL JOIN or USING.
   
   ```suggestion
       // 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");
   ```



##########
core/src/main/java/org/apache/calcite/sql/validate/AliasNamespace.java:
##########
@@ -100,29 +100,36 @@ 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
+        aliasedType = node.getKind() == SqlKind.COLLECTION_TABLE || 
keepsElementFieldName
             ? new SingleColumnAliasRelDataType(rowType, singleColumnAlias) : 
singleColumnAlias;
-        // If the sub-query is UNNEST with ordinality
-        // and the sub-query has two columns: data column, ordinality column
-        // then the namespace's sole column is named after the alias.
       } else if (node.getKind() == SqlKind.UNNEST && rowType.getFieldCount() 
== 2
           && ((SqlUnnestOperator) ((SqlBasicCall) 
node).getOperator()).withOrdinality) {
-        aliasedType = validator.getTypeFactory().builder()
+        // WITH ORDINALITY: data column, ordinality column. The data
+        // column is named after the alias, same as the single-column case.
+        final RelDataType dataColumnAlias = 
validator.getTypeFactory().builder()
             .kind(rowType.getStructKind())
             .add(((SqlIdentifier) operands.get(1)).getSimple(),
                 rowType.getFieldList().get(0).getType())
-            .add(rowType.getFieldList().get(1))
             .build();

Review Comment:
   **F6 nit** The single-column branch and the WITH ORDINALITY branch build the 
same aliased data-column type with identical five-line builders.
   
   Problem: `singleColumnAlias` and `dataColumnAlias` are the same expression 
and both feed `new SingleColumnAliasRelDataType(rowType, ...)`, so a later 
change to how the data column is aliased has to be made twice; T27 merged the 
copies inside the ORDINALITY branch but left this pair.
   
   Proposed solution: Build the aliased data-column type in one place, for 
example a private helper that both branches call, or a builder computed once 
under a condition that covers both branches.



##########
core/src/main/java/org/apache/calcite/rel/type/SingleColumnAliasRelDataType.java:
##########
@@ -26,22 +26,30 @@
 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.
  *
  * <p>For instance:
  * <blockquote><pre>select rmp, rmp.i from table(ramp(3)) as 
rmp;</pre></blockquote>
  *
+ * <p>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;
 
   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);

Review Comment:
   **F7 nit** The public constructor of SingleColumnAliasRelDataType now throws 
IllegalArgumentException on preconditions that nothing documents, including 
that the alias's single field stands for the first field of `original`.
   
   Problem: A caller cannot tell from the class comment what to pass as 
`alias`: a one-field struct named after the alias whose field has the type of 
`original`'s first field. The checks throw without a message.
   
   Proposed solution: Give the constructor a doc comment: `@param original` the 
row type, a struct with at least one field; `@param alias` a struct with one 
field, named after the alias, whose type is that of the first field of 
`original`; `@throws IllegalArgumentException` when either shape does not hold.



##########
core/src/main/java/org/apache/calcite/rel/type/SingleColumnAliasRelDataType.java:
##########
@@ -59,13 +67,18 @@ public SingleColumnAliasRelDataType(RelDataType original, 
RelDataType alias) {
   }
 
   @Override public int getFieldCount() {
-    return 1;
+    return original.getFieldCount();

Review Comment:
   **F5 minor** No test observes SingleColumnAliasRelDataType.getFieldCount(): 
the mutant that returns 0 survives, though a wrong count binds a correlated 
reference to the wrong column.
   
   Problem: The change makes getFieldCount() report the wrapped type's count so 
that WITH ORDINALITY works through the wrapper. SqlToRelConverter adds each 
namespace's field count to the offset of the correlation fields after it, so a 
FROM item to the right of an aliased ROW-element UNNEST WITH ORDINALITY that a 
correlated sub-query references is where the count shows.
   
   ```java
   @Test void testUnnestSingleFieldRowAliasWithOrdinalityCorrelatedOffset() {
     final String sql = "select t.name\n"
         + "from unnest(cast(array[row(1)] as row(a integer) array))\n"
         + "  with ordinality as d, dept as t\n"
         + "where exists (select 1 from emp e\n"
         + "  where e.deptno = t.deptno and e.empno = d.ordinality)";
     // head: LogicalFilter(condition=[AND(=($7, $cor0.DEPTNO), =($0, 
$cor0.ORDINALITY))])
     // getFieldCount() mutated to `return 0;`: =($7, $cor0.A)
     sql(sql).withDecorrelate(false).withExpand(false).ok();
   }
   ```
   
   Proposed solution: Add a SqlToRelConverterTest case with an aliased 
ROW-element UNNEST WITH ORDINALITY followed by another table in the same FROM, 
and a correlated sub-query that references that table, so the plan pins the 
correlation field.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to