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): propagate recursive CTE source to children scopes early #3294

Merged
merged 1 commit into from
Apr 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
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
12 changes: 3 additions & 9 deletions sqlglot/optimizer/scope.py
Original file line number Diff line number Diff line change
Expand Up @@ -600,7 +600,7 @@ def _traverse_ctes(scope):
sources = {}

for cte in scope.ctes:
recursive_scope = None
cte_name = cte.alias

# if the scope is a recursive cte, it must be in the form of base_case UNION recursive.
# thus the recursive scope is the first section of the union.
Expand All @@ -609,7 +609,7 @@ def _traverse_ctes(scope):
union = cte.this

if isinstance(union, exp.Union):
recursive_scope = scope.branch(union.this, scope_type=ScopeType.CTE)
sources[cte_name] = scope.branch(union.this, scope_type=ScopeType.CTE)

child_scope = None

Expand All @@ -623,15 +623,9 @@ def _traverse_ctes(scope):
):
yield child_scope

alias = cte.alias
sources[alias] = child_scope

if recursive_scope:
child_scope.add_source(alias, recursive_scope)
child_scope.cte_sources[alias] = recursive_scope

# append the final child_scope yielded
if child_scope:
sources[cte_name] = child_scope
scope.cte_scopes.append(child_scope)

scope.sources.update(sources)
Expand Down
11 changes: 11 additions & 0 deletions tests/test_optimizer.py
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,17 @@ def test_normalize(self):

@patch("sqlglot.generator.logger")
def test_qualify_columns(self, logger):
self.assertEqual(
optimizer.qualify_columns.qualify_columns(
parse_one(
"WITH RECURSIVE t AS (SELECT 1 AS x UNION ALL SELECT x + 1 FROM t AS child WHERE x < 10) SELECT * FROM t"
),
schema={},
infer_schema=False,
).sql(),
"WITH RECURSIVE t AS (SELECT 1 AS x UNION ALL SELECT child.x + 1 AS _col_0 FROM t AS child WHERE child.x < 10) SELECT t.x AS x FROM t",
)

self.assertEqual(
optimizer.qualify_columns.qualify_columns(
parse_one("WITH x AS (SELECT a FROM db.y) SELECT * FROM db.x"),
Expand Down
Loading