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

Conversation

georgesittas
Copy link
Collaborator

Before:

>>> from sqlglot import parse_one
>>> from sqlglot.optimizer.qualify import qualify
>>>
>>> sql = """
... with recursive t as (
...   select 1 as x
...   union all
...   select x + 1 from t as child where x < 10
... )
... select * from t
... """
>>>
>>> expr = parse_one(sql)
>>> print(qualify(expr, infer_schema=False).sql(pretty=True))
sqlglot.errors.OptimizeError: Column '"x"' could not be resolved

After:

>>> from sqlglot import parse_one
>>> from sqlglot.optimizer.qualify import qualify
>>>
>>> sql = """
... with recursive t as (
...   select 1 as x
...   union all
...   select x + 1 from t as child where x < 10
... )
... select * from t
... """
>>>
>>> expr = parse_one(sql)
>>> print(qualify(expr, infer_schema=False).sql(pretty=True))
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" AS "t"

@georgesittas georgesittas merged commit 94c188d into main Apr 9, 2024
5 checks passed
@georgesittas georgesittas deleted the jo/fix_cte_scope_traversal branch April 9, 2024 20:41
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

4 participants