Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(optimizer): Fix merge_subqueries.py::rename_inner_sources() #4266

Merged
merged 2 commits into from
Oct 18, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions sqlglot/optimizer/merge_subqueries.py
Original file line number Diff line number Diff line change
Expand Up @@ -227,10 +227,13 @@ def _rename_inner_sources(outer_scope, inner_scope, alias):
inner_scope (sqlglot.optimizer.scope.Scope)
alias (str)
"""
taken = set(outer_scope.selected_sources)
conflicts = taken.intersection(set(inner_scope.selected_sources))
inner_selected_sources_set = set(inner_scope.selected_sources)
outer_selected_sources_set = set(outer_scope.selected_sources)
conflicts = outer_selected_sources_set.intersection(inner_selected_sources_set)
VaggelisD marked this conversation as resolved.
Show resolved Hide resolved
conflicts -= {alias}

taken = outer_selected_sources_set.union(inner_selected_sources_set)

for conflict in conflicts:
new_name = find_new_name(taken, conflict)

Expand Down
18 changes: 18 additions & 0 deletions tests/fixtures/optimizer/merge_subqueries.sql
Original file line number Diff line number Diff line change
Expand Up @@ -446,3 +446,21 @@ SELECT
1 AS a;
WITH q AS (SELECT x.a AS a FROM x AS x ORDER BY x.a) SELECT q.a AS a FROM q AS q UNION ALL SELECT 1 AS a;

# title: Consecutive inner - outer conflicting names
WITH tbl AS (select 1 as id)
SELECT
id
FROM (
SELECT OTBL.id
FROM (
SELECT OTBL.id
FROM (
SELECT OTBL.id
FROM tbl AS OTBL
LEFT OUTER JOIN tbl AS ITBL ON OTBL.id = ITBL.id
) AS OTBL
LEFT OUTER JOIN tbl AS ITBL ON OTBL.id = ITBL.id
) AS OTBL
LEFT OUTER JOIN tbl AS ITBL ON OTBL.id = ITBL.id
) AS ITBL;
WITH tbl AS (SELECT 1 AS id) SELECT OTBL.id AS id FROM tbl AS OTBL LEFT OUTER JOIN tbl AS ITBL_2 ON OTBL.id = ITBL_2.id LEFT OUTER JOIN tbl AS ITBL_3 ON OTBL.id = ITBL_3.id LEFT OUTER JOIN tbl AS ITBL ON OTBL.id = ITBL.id;
Loading