Skip to content

Commit 91ea5eb

Browse files
Vamsi-kluclaude
andcommitted
fix(redshift): address review feedback on late-binding CTAS fallback
- Raise SQLMeshError in VarcharSizeWorkaroundMixin when the temp view's column types are unavailable, instead of creating the table from the LIMIT 0 CTAS with non-deterministic VARCHAR widths (Redshift and MSSQL). - Order BasePostgresEngineAdapter.columns() by attnum so the pg_catalog fallback preserves the view's SELECT order. - Document why Redshift's exists=True path does not forward target types and pin view-derived VARCHAR widths with a test. - Schema-qualify late-binding view sources in the test fixtures. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Signed-off-by: Vamsi-klu <nrvamsi13@gmail.com>
1 parent 0d8f7b0 commit 91ea5eb

6 files changed

Lines changed: 111 additions & 56 deletions

File tree

‎sqlmesh/core/engine_adapter/base_postgres.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@ def columns(
5555
)
5656
if table.args.get("db"):
5757
sql = sql.where(exp.column("nspname").eq(table.args["db"].name))
58+
sql = sql.order_by("attnum")
5859

5960
self.execute(sql)
6061
resp = self.cursor.fetchall()

‎sqlmesh/core/engine_adapter/mixins.py‎

Lines changed: 23 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -282,22 +282,32 @@ def _build_create_table_exp(
282282
self.columns(temp_view_name)
283283
)
284284

285-
if columns_to_types_from_view and columns_to_types_all_known(
285+
if not (
286286
columns_to_types_from_view
287+
and columns_to_types_all_known(columns_to_types_from_view)
287288
):
288-
schema = self._build_schema_exp(
289-
exp.to_table(table_name_or_schema),
290-
columns_to_types_from_view,
291-
)
292-
statement = super()._build_create_table_exp(
293-
schema,
294-
None,
295-
exists=exists,
296-
replace=replace,
297-
target_columns_to_types=columns_to_types_from_view,
298-
table_description=table_description,
299-
**kwargs,
289+
# View metadata is unavailable (e.g. a late-binding view the catalog doesn't expose).
290+
# Never fall back to the LIMIT 0 CTAS since its column types (e.g. VARCHAR widths)
291+
# are non-deterministic and the table could silently truncate data.
292+
raise SQLMeshError(
293+
f"Could not determine column types for table "
294+
f"'{exp.to_table(table_name_or_schema).sql(dialect=self.dialect)}' from "
295+
"its query. Specify the column types explicitly, e.g. by annotating the model."
300296
)
297+
298+
schema = self._build_schema_exp(
299+
exp.to_table(table_name_or_schema),
300+
columns_to_types_from_view,
301+
)
302+
statement = super()._build_create_table_exp(
303+
schema,
304+
None,
305+
exists=exists,
306+
replace=replace,
307+
target_columns_to_types=columns_to_types_from_view,
308+
table_description=table_description,
309+
**kwargs,
310+
)
301311
finally:
302312
self.drop_view(temp_view_name)
303313

‎sqlmesh/core/engine_adapter/redshift.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -253,6 +253,9 @@ def _create_table_from_source_queries(
253253
)
254254
if self.table_exists(table_name):
255255
return
256+
# target_columns_to_types is deliberately not forwarded: inferred types can lack VARCHAR widths, and
257+
# casting to them would truncate data. Keeping the LIMIT 0 CTAS lets VarcharSizeWorkaroundMixin derive
258+
# the exact widths from a temp view instead.
256259
super()._create_table_from_source_queries(
257260
table_name,
258261
source_queries,

‎tests/core/engine_adapter/test_base_postgres.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ def test_columns(make_mocked_engine_adapter: t.Callable):
2323
'JOIN "pg_catalog"."pg_class" ON "pg_class"."oid" = "attrelid" '
2424
'JOIN "pg_catalog"."pg_namespace" ON "pg_namespace"."oid" = "relnamespace" '
2525
"""WHERE ("attnum" > 0 AND NOT "attisdropped" AND "relname" = 'table') AND "nspname" = 'db'"""
26+
' ORDER BY "attnum"'
2627
)
2728
assert resp == {"col": exp.DataType.build("INT")}
2829

‎tests/core/engine_adapter/test_mssql.py‎

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
from sqlmesh.core import dialect as d
1919
from sqlmesh.core.engine_adapter.shared import DataObject, DataObjectType, SourceQuery
2020
from sqlmesh.utils.date import to_ds
21+
from sqlmesh.utils.errors import SQLMeshError
2122
from tests.core.engine_adapter import to_sql_calls
2223

2324
pytestmark = [pytest.mark.engine, pytest.mark.mssql]
@@ -1081,14 +1082,14 @@ def test_ctas_varchar_workaround_empty_columns_fallback(
10811082
)
10821083
mocker.patch("sqlmesh.core.engine_adapter.mssql.MSSQLEngineAdapter.columns", return_value={})
10831084

1084-
adapter.ctas(
1085-
table_name="test_schema.test_table",
1086-
query_or_df=parse_one("SELECT a, b FROM tbl WHERE FALSE LIMIT 0"),
1087-
exists=False,
1088-
)
1085+
with pytest.raises(SQLMeshError, match="Could not determine column types"):
1086+
adapter.ctas(
1087+
table_name="test_schema.test_table",
1088+
query_or_df=parse_one("SELECT a, b FROM tbl WHERE FALSE LIMIT 0"),
1089+
exists=False,
1090+
)
10891091

10901092
assert to_sql_calls(adapter) == [
10911093
"CREATE VIEW [__temp_ctas_test_random_id] AS SELECT [a], [b] FROM [tbl];",
10921094
"DROP VIEW IF EXISTS [__temp_ctas_test_random_id];",
1093-
"SELECT * INTO [test_schema].[test_table] FROM (SELECT TOP 0 [a] AS [a], [b] AS [b] FROM [tbl] WHERE (1 = 0)) AS temp;",
10941095
]

‎tests/core/engine_adapter/test_redshift.py‎

Lines changed: 76 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -990,21 +990,63 @@ def test_ctas_varchar_workaround_empty_or_unknown_columns_fallback(
990990
return_value=mocked_columns,
991991
)
992992

993+
with pytest.raises(SQLMeshError, match="Could not determine column types"):
994+
adapter.ctas(
995+
table_name="sqlmesh_xxx.my_example",
996+
query_or_df=parse_one(
997+
"SELECT id, updated_at, trashed_at, CAST(NULL AS TIMESTAMP) AS valid_from, CAST(NULL AS TIMESTAMP) AS valid_to FROM sqlmesh_xxx.my_table WHERE FALSE LIMIT 0"
998+
),
999+
exists=False,
1000+
)
1001+
1002+
# The table must never be created from the LIMIT 0 CTAS (VARCHAR widths are non-deterministic)
1003+
# and the temp view must still be cleaned up.
1004+
assert to_sql_calls(adapter) == [
1005+
'CREATE VIEW "__temp_ctas_test_random_id" AS SELECT "id", "updated_at", "trashed_at", CAST(NULL AS TIMESTAMP) AS "valid_from", CAST(NULL AS TIMESTAMP) AS "valid_to" FROM "sqlmesh_xxx"."my_table" WITH NO SCHEMA BINDING',
1006+
'DROP VIEW IF EXISTS "__temp_ctas_test_random_id" CASCADE',
1007+
]
1008+
for sql in to_sql_calls(adapter):
1009+
parse_one(sql, read="redshift")
1010+
1011+
1012+
def test_ctas_exists_true_derives_varchar_widths_from_view_not_target_types(
1013+
make_mocked_engine_adapter: t.Callable,
1014+
mocker: MockerFixture,
1015+
) -> None:
1016+
adapter = make_mocked_engine_adapter(RedshiftEngineAdapter)
1017+
mocker.patch(
1018+
"sqlmesh.core.engine_adapter.base.random_id",
1019+
return_value="test_random_id",
1020+
)
1021+
mocker.patch(
1022+
"sqlmesh.core.engine_adapter.redshift.RedshiftEngineAdapter.table_exists",
1023+
return_value=False,
1024+
)
1025+
columns_mock = mocker.patch(
1026+
"sqlmesh.core.engine_adapter.redshift.RedshiftEngineAdapter.columns",
1027+
return_value={
1028+
"id": exp.DataType.build("INT"),
1029+
"name": exp.DataType.build("VARCHAR(2000)", dialect="redshift"),
1030+
},
1031+
)
1032+
1033+
# Inferred target types can be a plain VARCHAR with no length. They must not be forwarded (default
1034+
# exists=True path), otherwise a CAST to VARCHAR would truncate; widths come from the temp view.
9931035
adapter.ctas(
9941036
table_name="sqlmesh_xxx.my_example",
995-
query_or_df=parse_one(
996-
"SELECT id, updated_at, trashed_at, CAST(NULL AS TIMESTAMP) AS valid_from, CAST(NULL AS TIMESTAMP) AS valid_to FROM my_table WHERE FALSE LIMIT 0"
997-
),
998-
exists=False,
1037+
query_or_df=parse_one("SELECT id, name FROM sqlmesh_xxx.my_table WHERE FALSE LIMIT 0"),
1038+
target_columns_to_types={
1039+
"id": exp.DataType.build("INT"),
1040+
"name": exp.DataType.build("VARCHAR"),
1041+
},
9991042
)
10001043

10011044
sql_calls = to_sql_calls(adapter)
1002-
assert 'CREATE TABLE "sqlmesh_xxx"."my_example"' not in sql_calls
1003-
assert all("UNKNOWN" not in sql for sql in sql_calls)
1045+
columns_mock.assert_called_once()
10041046
assert sql_calls == [
1005-
'CREATE VIEW "__temp_ctas_test_random_id" AS SELECT "id", "updated_at", "trashed_at", CAST(NULL AS TIMESTAMP) AS "valid_from", CAST(NULL AS TIMESTAMP) AS "valid_to" FROM "my_table" WITH NO SCHEMA BINDING',
1047+
'CREATE VIEW "__temp_ctas_test_random_id" AS SELECT "id", "name" FROM "sqlmesh_xxx"."my_table" WITH NO SCHEMA BINDING',
10061048
'DROP VIEW IF EXISTS "__temp_ctas_test_random_id" CASCADE',
1007-
'CREATE TABLE "sqlmesh_xxx"."my_example" AS SELECT "id", "updated_at", "trashed_at", CAST(NULL AS TIMESTAMP) AS "valid_from", CAST(NULL AS TIMESTAMP) AS "valid_to" FROM "my_table" WHERE FALSE LIMIT 0',
1049+
'CREATE TABLE "sqlmesh_xxx"."my_example" ("id" INTEGER, "name" VARCHAR(2000))',
10081050
]
10091051
for sql in sql_calls:
10101052
parse_one(sql, read="redshift")
@@ -1068,6 +1110,7 @@ def test_columns_late_binding_view_and_pg_catalog_fallback(
10681110
sql_calls_pg = to_sql_calls(adapter)
10691111
assert len(sql_calls_pg) == 3
10701112
assert '"pg_catalog"."pg_attribute"' in sql_calls_pg[2]
1113+
assert 'ORDER BY "attnum"' in sql_calls_pg[2]
10711114
assert resp_pg == {
10721115
"id": exp.DataType.build("INT", dialect="redshift"),
10731116
"ts": exp.DataType.build("TIMESTAMP", dialect="redshift"),
@@ -1135,7 +1178,7 @@ def test_scd_type_2_by_time_unannotated_lifecycle_issue_5787(
11351178
id,
11361179
updated_at,
11371180
trashed_at
1138-
FROM my_table
1181+
FROM sqlmesh_xxx.my_table
11391182
"""
11401183
),
11411184
dialect="redshift",
@@ -1181,22 +1224,21 @@ def test_scd_type_2_by_time_unannotated_lifecycle_issue_5787(
11811224
for sql in create_calls_lbv:
11821225
parse_one(sql, read="redshift")
11831226

1184-
# Step 1b: strategy.create when columns("__temp_ctas_*") returns {} completely (all catalog queries empty)
1227+
# Step 1b: columns("__temp_ctas_*") returns {} (all catalog queries empty) -> fail loudly instead of
1228+
# creating the table from the LIMIT 0 CTAS, which can truncate VARCHARs or lose the schema
11851229
adapter.cursor.execute.reset_mock()
11861230
adapter.cursor.fetchall.side_effect = [[], [], []]
1187-
strategy.create(
1188-
table_name=target_table,
1189-
model=model,
1190-
is_table_deployable=True,
1191-
render_kwargs={},
1192-
skip_grants=True,
1193-
)
1231+
with pytest.raises(SQLMeshError, match="Could not determine column types"):
1232+
strategy.create(
1233+
table_name=target_table,
1234+
model=model,
1235+
is_table_deployable=True,
1236+
render_kwargs={},
1237+
skip_grants=True,
1238+
)
11941239
create_calls_fallback = to_sql_calls(adapter)
1195-
assert truncated_ddl not in create_calls_fallback
1196-
assert (
1197-
'CREATE TABLE "sqlmesh__sqlmesh_xxx"."sqlmesh_xxx__my_example__1234567890" AS SELECT "id" AS "id", "updated_at" AS "updated_at", "trashed_at" AS "trashed_at", CAST(NULL AS TIMESTAMP) AS "valid_from", CAST(NULL AS TIMESTAMP) AS "valid_to" FROM "my_table" AS "my_table" WHERE FALSE LIMIT 0'
1198-
in create_calls_fallback
1199-
)
1240+
assert not any(sql.startswith("CREATE TABLE") for sql in create_calls_fallback)
1241+
assert create_calls_fallback[-1] == 'DROP VIEW IF EXISTS "__temp_ctas_test_random_id" CASCADE'
12001242
for sql in create_calls_fallback:
12011243
parse_one(sql, read="redshift")
12021244

@@ -1484,7 +1526,7 @@ def test_scd_type_2_redshift_edge_cases(
14841526
execution_time_as_valid_from true
14851527
)
14861528
);
1487-
SELECT id, val FROM src
1529+
SELECT id, val FROM s.src
14881530
"""
14891531
),
14901532
dialect="redshift",
@@ -1494,19 +1536,16 @@ def test_scd_type_2_redshift_edge_cases(
14941536

14951537
mocker.patch.object(adapter, "table_exists", return_value=False)
14961538
mocker.patch.object(adapter, "columns", return_value={})
1497-
strategy.create(
1498-
table_name="s.t",
1499-
model=model_star,
1500-
is_table_deployable=True,
1501-
render_kwargs={},
1502-
skip_grants=True,
1503-
)
1504-
create_calls = to_sql_calls(adapter)
1505-
assert 'CREATE TABLE "s"."t"' not in create_calls
1506-
assert (
1507-
'CREATE TABLE "s"."t" AS SELECT "id" AS "id", "val" AS "val", CAST(NULL AS TIMESTAMP) AS "valid_from", CAST(NULL AS TIMESTAMP) AS "valid_to" FROM "src" AS "src" WHERE FALSE LIMIT 0'
1508-
in create_calls
1509-
)
1539+
with pytest.raises(SQLMeshError, match="Could not determine column types"):
1540+
strategy.create(
1541+
table_name="s.t",
1542+
model=model_star,
1543+
is_table_deployable=True,
1544+
render_kwargs={},
1545+
skip_grants=True,
1546+
)
1547+
assert not any(sql.startswith("CREATE TABLE") for sql in to_sql_calls(adapter))
1548+
adapter.cursor.execute.reset_mock()
15101549

15111550
mocker.patch.object(
15121551
adapter,
@@ -1548,7 +1587,7 @@ def test_scd_type_2_redshift_edge_cases(
15481587
assert "1970-01-01" not in sub_insert
15491588
else:
15501589
assert "CAST('1970-01-01 00:00:00' AS TIMESTAMP)" in sub_insert
1551-
sql_calls = create_calls
1590+
sql_calls = sub_calls
15521591

15531592
for sql in sql_calls:
15541593
parse_one(sql, read="redshift")

0 commit comments

Comments
 (0)