Fix CTE insertion position when the model uses WITH RECURSIVE (#7350) (#7414)

This commit is contained in:
Will Bryant
2023-06-29 03:41:31 +12:00
committed by GitHub
parent e01d4c0a6e
commit 0f52505dbe
5 changed files with 37 additions and 0 deletions

View File

@@ -0,0 +1,6 @@
kind: Fixes
body: Fix CTE insertion position when the model uses WITH RECURSIVE
time: 2023-04-20T12:32:21.432848+12:00
custom:
Author: willbryant
Issue: "7350"

View File

@@ -340,6 +340,10 @@ class Compiler:
for token in parsed.tokens:
if token.is_keyword and token.normalized == "WITH":
with_stmt = token
elif token.is_keyword and token.normalized == "RECURSIVE" and with_stmt is not None:
with_stmt = token
break
elif not token.is_whitespace and with_stmt is not None:
break
if with_stmt is None:

View File

@@ -32,6 +32,16 @@ select {{
}} as fun
"""
with_recursive_model_sql = """
{{ config(materialized = 'ephemeral') }}
with recursive t(n) as (
select * from {{ ref('first_ephemeral_model') }}
union all
select n+1 from t where n < 100
)
select sum(n) from t;
"""
schema_yml = """
version: 2

View File

@@ -11,6 +11,7 @@ from tests.functional.compile.fixtures import (
first_ephemeral_model_sql,
second_ephemeral_model_sql,
third_ephemeral_model_sql,
with_recursive_model_sql,
schema_yml,
model_multiline_jinja,
)
@@ -56,6 +57,7 @@ class TestEphemeralModels:
"first_ephemeral_model.sql": first_ephemeral_model_sql,
"second_ephemeral_model.sql": second_ephemeral_model_sql,
"third_ephemeral_model.sql": third_ephemeral_model_sql,
"with_recursive_model.sql": with_recursive_model_sql,
}
def test_first_selector(self, project):
@@ -104,6 +106,20 @@ class TestEphemeralModels:
"select 2 as fun",
]
def test_with_recursive_cte(self, project):
run_dbt(["compile"])
assert get_lines("with_recursive_model") == [
"with recursive __dbt__cte__first_ephemeral_model as (",
"select 1 as fun",
"),t(n) as (",
" select * from __dbt__cte__first_ephemeral_model",
" union all",
" select n+1 from t where n < 100",
")",
"select sum(n) from t;",
]
class TestCompile:
@pytest.fixture(scope="class")

View File

@@ -3,6 +3,7 @@ from typing import Tuple, Iterable
class Token:
def __init__(self, ttype, value): ...
is_keyword: bool
is_whitespace: bool
normalized: str
class TokenList(Token):