jinxing64 commented on a change in pull request #1715: [CALCITE-3662] Generate
wrong SQL when plan contains Project(Sort(Aggregate)) and aggregate field has
no alias
URL: https://github.com/apache/calcite/pull/1715#discussion_r362756121
##########
File path: piglet/src/test/java/org/apache/calcite/test/PigRelOpTest.java
##########
@@ -468,14 +468,14 @@ private Fluent pig(String script) {
+ "HIREDATE, SAL, COMM, DEPTNO)) AS A\n"
+ " FROM scott.EMP\n"
+ " GROUP BY DEPTNO) AS $cor4,\n"
- + " LATERAL (SELECT COLLECT(ROW(ENAME, JOB, DEPTNO, SAL)) AS
X\n"
- + " FROM (SELECT ENAME, JOB, DEPTNO, SAL\n"
+ + " LATERAL (SELECT X\n"
+ + " FROM (SELECT 'all' AS $f0, COLLECT(ROW(ENAME, JOB,
DEPTNO, SAL)) AS X\n"
+ " FROM UNNEST (SELECT $cor4.A AS $f0\n"
+ " FROM (VALUES (0)) AS t (ZERO)) "
+ "AS t2 (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO)\n"
+ " WHERE JOB <> 'CLERK'\n"
- + " ORDER BY SAL) AS t5\n"
- + " GROUP BY 'all') AS t8) AS $cor5,\n"
+ + " GROUP BY 'all'\n"
+ + " ORDER BY SAL) AS t7) AS t8) AS $cor5,\n"
+ " LATERAL UNNEST (SELECT $cor5.X AS $f0\n"
Review comment:
Thanks for explanation @helloppx
Yes, thee reference is indeed a fix for this case. But I still think a
thorough fix is to set the correct alias. I take below case as an example:
If I have sql and corresponding plan as below:
```
select "product_class_id" + 1, *
from
(
select * from
(select "product_class_id", sum("product_id") from "product" group by
"product_class_id" limit 10) A
union all
select * from
(select "product_class_id", sum("product_id") from "product" group by
"product_class_id" limit 10) B
) C
LogicalProject(EXPR$0=[+($0, 1)], product_class_id=[$0], EXPR$1=[$1])
LogicalUnion(all=[true])
LogicalProject(product_class_id=[$0], EXPR$1=[$1])
LogicalSort(fetch=[10])
LogicalAggregate(group=[{0}], EXPR$1=[SUM($1)])
LogicalProject(product_class_id=[$0], product_id=[$1])
JdbcTableScan(table=[[foodmart, product]])
LogicalProject(product_class_id=[$0], EXPR$1=[$1])
LogicalSort(fetch=[10])
LogicalAggregate(group=[{0}], EXPR$1=[SUM($1)])
LogicalProject(product_class_id=[$0], product_id=[$1])
JdbcTableScan(table=[[foodmart, product]])
```
RelToSqlConverter will convert the plan to below sql (with the fix bring by
this PR):
```
SELECT "product_class_id" + 1, "product_class_id", SUM("product_id")
FROM (SELECT "product_class_id", SUM("product_id")
FROM "foodmart"."product"
GROUP BY "product_class_id"
FETCH NEXT 10 ROWS ONLY
UNION ALL
SELECT "product_class_id", SUM("product_id")
FROM "foodmart"."product"
GROUP BY "product_class_id"
FETCH NEXT 10 ROWS ONLY) AS "t5"
```
Obviously it's not correct (the outmost `SUM("product_id")` is wrong).
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
[email protected]
With regards,
Apache Git Services