Skip to content

Commit 9687d62

Browse files
authored
fix: skip limit on recursive ctes (#2278)
1 parent 895c832 commit 9687d62

File tree

2 files changed

+26
-3
lines changed

2 files changed

+26
-3
lines changed

sqlmesh/core/model/definition.py

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -425,12 +425,17 @@ def ctas_query(self, **render_kwarg: t.Any) -> exp.Query:
425425
query = self.render_query_or_raise(**render_kwarg).copy()
426426

427427
for select_or_union in query.find_all(exp.Select, exp.Union):
428+
cte = select_or_union.find_ancestor(exp.With, exp.Select, exp.Subquery)
429+
skip_limit = isinstance(cte, exp.With) and cte.recursive
430+
428431
if isinstance(select_or_union, exp.Select) and select_or_union.args.get("from"):
429432
select_or_union.where(exp.false(), copy=False)
430-
if not isinstance(select_or_union.parent, exp.Union):
433+
if not skip_limit and not isinstance(select_or_union.parent, exp.Union):
431434
select_or_union.limit(0, copy=False)
432-
elif isinstance(select_or_union, exp.Union) and not isinstance(
433-
select_or_union.parent, exp.Union
435+
elif (
436+
not skip_limit
437+
and isinstance(select_or_union, exp.Union)
438+
and not isinstance(select_or_union.parent, exp.Union)
434439
):
435440
select_or_union.set("limit", exp.Limit(expression=exp.Literal.number(0)))
436441

tests/core/test_model.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1811,6 +1811,24 @@ def test_model_ctas_query():
18111811
== 'SELECT 1 AS "a" FROM "t" AS "t" WHERE FALSE UNION ALL SELECT 2 AS "a" FROM "t" AS "t" WHERE FALSE ORDER BY 1 LIMIT 0'
18121812
)
18131813

1814+
expressions = d.parse(
1815+
"""
1816+
MODEL (name `a-b-c.table`, kind FULL, dialect bigquery);
1817+
WITH RECURSIVE a AS (
1818+
SELECT * FROM x
1819+
), b AS (
1820+
SELECT * FROM a UNION ALL SELECT * FROM a
1821+
)
1822+
SELECT * FROM b
1823+
1824+
"""
1825+
)
1826+
1827+
assert (
1828+
load_sql_based_model(expressions, dialect="bigquery").ctas_query().sql()
1829+
== 'WITH RECURSIVE "a" AS (SELECT * FROM "x" AS "x" WHERE FALSE), "b" AS (SELECT * FROM "a" AS "a" WHERE FALSE UNION ALL SELECT * FROM "a" AS "a" WHERE FALSE) SELECT * FROM "b" AS "b" WHERE FALSE LIMIT 0'
1830+
)
1831+
18141832

18151833
def test_is_breaking_change():
18161834
model = create_external_model("a", columns={"a": "int", "limit": "int"})

0 commit comments

Comments
 (0)