Skip to content

Commit

Permalink
Fix(optimizer): don't merge CTEs with EXPLODE projections into outer …
Browse files Browse the repository at this point in the history
…scopes (#2366)
  • Loading branch information
georgesittas authored Oct 3, 2023
1 parent a270c15 commit 0e93890
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
2 changes: 1 addition & 1 deletion sqlglot/optimizer/merge_subqueries.py
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ def _outer_select_joins_on_inner_select_join():
and not any(inner_select.args.get(arg) for arg in UNMERGABLE_ARGS)
and inner_select.args.get("from")
and not outer_scope.pivots
and not any(e.find(exp.AggFunc, exp.Select) for e in inner_select.expressions)
and not any(e.find(exp.AggFunc, exp.Select, exp.Explode) for e in inner_select.expressions)
and not (leave_tables_isolated and len(outer_scope.selected_sources) > 1)
and not (
isinstance(from_or_join, exp.Join)
Expand Down
22 changes: 22 additions & 0 deletions tests/fixtures/optimizer/optimizer.sql
Original file line number Diff line number Diff line change
Expand Up @@ -1023,3 +1023,25 @@ SELECT
FROM "table1" AS "table1"
LEFT JOIN "alias3"
ON "table1"."cid" = "alias3"."cid";

# title: CTE with EXPLODE cannot be merged
# dialect: spark
# execute: false
SELECT Name,
FruitStruct.`$id`,
FruitStruct.value
FROM
(SELECT Name,
explode(Fruits) as FruitStruct
FROM fruits_table);
WITH `_q_0` AS (
SELECT
`fruits_table`.`name` AS `name`,
EXPLODE(`fruits_table`.`fruits`) AS `fruitstruct`
FROM `fruits_table` AS `fruits_table`
)
SELECT
`_q_0`.`name` AS `name`,
`_q_0`.`fruitstruct`.`$id` AS `$id`,
`_q_0`.`fruitstruct`.`value` AS `value`
FROM `_q_0` AS `_q_0`;

0 comments on commit 0e93890

Please sign in to comment.