Skip to content

Commit 895c832

Browse files
authored
Fix: Place LIMIT before ORDER BY for UNION queries when generating a CTAS query (#2277)
1 parent 1b42d7a commit 895c832

File tree

2 files changed

+21
-7
lines changed

2 files changed

+21
-7
lines changed

sqlmesh/core/model/definition.py

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -424,13 +424,15 @@ def ctas_query(self, **render_kwarg: t.Any) -> exp.Query:
424424
"""
425425
query = self.render_query_or_raise(**render_kwarg).copy()
426426

427-
for select in query.find_all(exp.Select):
428-
if select.args.get("from"):
429-
select.where(exp.false(), copy=False)
430-
if not isinstance(select.parent, exp.Union) or (
431-
select.parent.parent is None and select.arg_key == "expression"
432-
):
433-
select.limit(0, copy=False)
427+
for select_or_union in query.find_all(exp.Select, exp.Union):
428+
if isinstance(select_or_union, exp.Select) and select_or_union.args.get("from"):
429+
select_or_union.where(exp.false(), copy=False)
430+
if not isinstance(select_or_union.parent, exp.Union):
431+
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
434+
):
435+
select_or_union.set("limit", exp.Limit(expression=exp.Literal.number(0)))
434436

435437
if self.managed_columns:
436438
query.select(

tests/core/test_model.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1799,6 +1799,18 @@ def test_model_ctas_query():
17991799
== 'SELECT 1 AS "a" FROM "t" AS "t" WHERE FALSE UNION ALL SELECT 2 AS "a" FROM "t" AS "t" WHERE FALSE LIMIT 0'
18001800
)
18011801

1802+
expressions = d.parse(
1803+
"""
1804+
MODEL (name `a-b-c.table`, kind FULL, dialect bigquery);
1805+
SELECT 1 AS a FROM t UNION ALL SELECT 2 AS a FROM t ORDER BY 1
1806+
"""
1807+
)
1808+
1809+
assert (
1810+
load_sql_based_model(expressions, dialect="bigquery").ctas_query().sql()
1811+
== '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'
1812+
)
1813+
18021814

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

0 commit comments

Comments
 (0)