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


##########
core/src/main/java/org/apache/calcite/sql/validate/SqlValidatorImpl.java:
##########
@@ -8553,7 +8564,48 @@ private SqlNode nthSelectItem(int ordinal, final 
SqlParserPos pos) {
 
       // Create a copy of the expression with the position of the order
       // item.
-      return expr.clone(pos);
+      return reposition(expr, pos);
+    }
+
+    private SqlNode reposition(SqlNode node, SqlParserPos pos) {
+      SqlNode res = node.accept(new SqlShuttle() {
+        @Override public @Nullable SqlNode visit(SqlIdentifier id) {
+          return id.clone(pos);
+        }
+
+        @Override public @Nullable SqlNode visit(SqlLiteral literal) {
+          return literal.clone(pos);
+        }
+
+        @Override public @Nullable SqlNode visit(SqlDataTypeSpec type) {
+          return type.clone(pos);
+        }
+
+        @Override public @Nullable SqlNode visit(SqlDynamicParam param) {
+          return param.clone(pos);
+        }
+
+        @Override public @Nullable SqlNode visit(SqlIntervalQualifier 
intervalQualifier) {
+          return intervalQualifier.clone(pos);
+        }
+
+        @Override public @Nullable SqlNode visit(SqlNodeList nodeList) {
+          SqlNodeList list = (SqlNodeList) super.visit(nodeList);
+          return list == null ? null : list.clone(pos);
+        }
+
+        @Override public @Nullable SqlNode visit(SqlCall call) {
+          if (call.isA(SqlKind.QUERY)

Review Comment:
   `call.clone(pos)` does not preserve a sub-query: for a `SqlSelect` it goes 
through `SqlSelectOperator.createCall` and returns a new `SqlSelect`, which has 
no entry in the identity-keyed `namespaces` map. The `SCALAR_QUERY` case works 
only because `SqlBasicCall.clone` keeps the original operand. The operand of 
IN, EXISTS and `> ALL` is a bare `SqlSelect`, which the shuttle reaches through 
the parent call and replaces.
   
   `select deptno in (select deptno from dept) as b from emp order by b` then 
fails in `OrderByScope.validateExpr` → `expandOrderExpr` → `deriveType` with 
`UnsupportedOperationException: class org.apache.calcite.sql.SqlNodeList`. That 
path is not the new check, so a bare `order by b` breaks too.
   
   The copy `reposition` makes also gives `?` a fresh, untyped 
`SqlDynamicParam`: `select sal + ? as x from emp order by x + 1` fails with 
`Cannot apply '+' to arguments of type '<INTEGER> + <UNKNOWN>'`. With 
`reposition` replaced by the old `expr.clone(pos)`, both queries pass again.
   
   With the new message from the review body, the error no longer depends on 
where the copied nodes point, so `reposition` is not needed: report the error 
at the ORDER BY item and keep the shallow `expr.clone(pos)`. If `reposition` 
stays, commit 15732c801f needs a test that fails without it, and the method 
needs a comment saying which nodes must keep their identity and why.



##########
core/src/main/java/org/apache/calcite/sql/validate/SqlValidatorImpl.java:
##########
@@ -5470,6 +5470,17 @@ private void validateOrderItem(SqlSelect select, SqlNode 
orderItem) {
 
     final SqlValidatorScope orderScope = getOrderScope(select);
     validateExpr(orderItem, orderScope);
+
+    final RelDataType type = deriveType(orderScope, orderItem);
+    if (!type.isMeasure()) {
+      final SqlNode expanded = expandOrderExpr(select, orderItem);
+      // Validate in the SELECT scope rather than ORDER BY scope so that
+      // expressions expanded from SELECT-list aliases (e.g. an aggregate 
referencing
+      // an alias that shadows a column) are checked for validity (such as 
disallowing
+      // nested aggregates). Measures are skipped because measure expressions 
are validated
+      // in MeasureScope and can reference other select items not present in 
table scopes.
+      expanded.validate(this, getSelectScope(select));

Review Comment:
   Validating the expansion in the SELECT scope rejects two valid queries for 
reasons unrelated to `reposition`; both also fail with the shallow 
`expr.clone(pos)`:
   
   - `select current_date as d, empno from emp order by d` fails with `No match 
found for function signature CURRENT_DATE()`. The select item is the 
`ExpandedBasicCall` that `makeNullaryCall` creates. Its copy is a plain 
`SqlBasicCall` with `isExpanded() == false`, and `validateCall` rejects a 
zero-operand function call that is not expanded.
   - `select deptno + 1 as d1, d1 + 2 as measure d3 from emp order by d3 + 1` 
fails with `Column 'D1' not found in any table`. `type.isMeasure()` looks at 
the type of the whole ORDER BY item, so the measure guard works for `order by 
d3` and not when the measure is inside an expression.
   
   The check only needs to find a nested aggregate, and an aggregate inside 
FILTER. Looking for those in the expansion, instead of validating it again in 
the SELECT scope, avoids both failures. `OrderByScope.validateExpr`, the other 
place my previous review suggested, already expands the item and passes it to 
the parent scope, so the check fits there and the second `expandOrderExpr` call 
here goes away.



##########
core/src/test/java/org/apache/calcite/test/JdbcTest.java:
##########
@@ -3391,6 +3391,16 @@ void testJoinWithTrimmingConfigs(boolean 
enableTrimmingByConfig,
             + "store_id=0; grocery_sqft=null\n");
   }
 
+  /** Test case for <a 
href="https://issues.apache.org/jira/browse/CALCITE-7744";>[CALCITE-7744]</a>
+   * ORDER BY agg(col) on a query where an alias shadows col fails with nested 
aggregate error. */

Review Comment:
   Calcite's `Test case for [CALCITE-NNNN]` Javadoc quotes the JIRA summary. 
This one replaces "produces an invalid plan containing an aggregate call in a 
Project" with "fails with nested aggregate error", and the one on 
`SqlValidatorTest#testOrderByAggregateAliasShadowing` cuts the summary after 
"produces an invalid plan". Please use the full summary in both.



-- 
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