Skip to content

Commit a85a986

Browse files
committed
Fix: only drop LIMIT 0 in VarcharSizeWorkaroundMixin table creation
1 parent 29b2263 commit a85a986

2 files changed

Lines changed: 19 additions & 2 deletions

File tree

sqlmesh/core/engine_adapter/mixins.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -297,11 +297,15 @@ def _build_create_table_exp(
297297
and statement.expression.args["limit"].expression.this == "0"
298298
):
299299
assert not isinstance(table_name_or_schema, exp.Schema)
300+
300301
# redshift and mssql have a bug where CTAS statements have non determistic types. if a limit
301302
# is applied to a ctas statement, VARCHAR types default to 1 in some instances.
302303
select_statement = statement.expression.copy()
303304
for select_or_union in select_statement.find_all(exp.Select, exp.SetOperation):
304-
select_or_union.set("limit", None)
305+
limit = select_or_union.args.get("limit")
306+
if limit is not None and limit.expression.this == "0":
307+
limit.pop()
308+
305309
select_or_union.set("where", None)
306310

307311
temp_view_name = self._get_temp_table("ctas")

tests/core/engine_adapter/test_mssql.py

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -730,11 +730,24 @@ def test_create_table_from_query(make_mocked_engine_adapter: t.Callable, mocker:
730730
),
731731
exists=False,
732732
)
733-
734733
assert to_sql_calls(adapter) == [
735734
"CREATE VIEW [__temp_ctas_test_random_id] AS SELECT [a], [b], [x] + 1 AS [c], [d] AS [d], [e] FROM (SELECT * FROM [table]);",
736735
"DROP VIEW IF EXISTS [__temp_ctas_test_random_id];",
737736
"CREATE TABLE [test_schema].[test_table] ([a] VARCHAR(MAX), [b] VARCHAR(60), [c] VARCHAR(MAX), [d] VARCHAR(MAX), [e] DATETIME2);",
738737
]
739738

740739
columns_mock.assert_called_once_with(exp.table_("__temp_ctas_test_random_id", quoted=True))
740+
741+
# We don't want to drop anything other than LIMIT 0
742+
# See https://github.com/TobikoData/sqlmesh/issues/4048
743+
adapter.ctas(
744+
table_name="test_schema.test_table",
745+
query_or_df=parse_one(
746+
"SELECT * FROM (SELECT * FROM t WHERE FALSE LIMIT 1) WHERE FALSE LIMIT 0"
747+
),
748+
exists=False,
749+
)
750+
assert (
751+
"CREATE VIEW [__temp_ctas_test_random_id] AS SELECT * FROM (SELECT TOP 1 * FROM [t]);"
752+
in to_sql_calls(adapter)
753+
)

0 commit comments

Comments
 (0)