Skip to content

Commit 0d8f7b0

Browse files
committed
fix(redshift): prevent empty-schema CREATE TABLE when late-binding CTAS view metadata is unavailable
Unannotated SCD_TYPE_2_BY_TIME and SCD_TYPE_2_BY_COLUMN models on Redshift create their snapshot table via empty CTAS (WHERE FALSE LIMIT 0) through VarcharSizeWorkaroundMixin. When svv_columns returned 0 rows for the temporary late-binding view (e.g. over Redshift Datashares, cross-database relations, or restricted search_path schemas), RedshiftEngineAdapter.columns() returned {}, causing VarcharSizeWorkaroundMixin to emit a truncated column-less CREATE TABLE statement (SQLSTATE 42601: syntax error at end of input). - Fall back in RedshiftEngineAdapter.columns() from svv_columns to pg_get_late_binding_view_cols() and pg_catalog.pg_attribute without aborting active transactions, and respect explicit no_schema_binding in create_view(). - Guard VarcharSizeWorkaroundMixin._build_create_table_exp() so empty or unknown view column metadata falls back to the CTAS query instead of building an empty schema. - Return False from columns_to_types_all_known({}) so create_table() raises SQLMeshError rather than emitting column-less DDL. - Quote unmanaged column identifiers in EngineAdapter._scd_type_2() so reserved keywords and special-character column names render safely. Fixes #5787 Signed-off-by: Vamsi-klu <nrvamsi13@gmail.com>
1 parent be795ff commit 0d8f7b0

7 files changed

Lines changed: 725 additions & 26 deletions

File tree

‎sqlmesh/core/engine_adapter/base.py‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1943,8 +1943,10 @@ def remove_managed_columns(
19431943
f"Column {updated_at_name} not found in {target_table}. Table must contain an `updated_at` timestamp for SCD Type 2"
19441944
)
19451945
time_data_type = target_columns_to_types[valid_from_name]
1946-
select_source_columns: t.List[t.Union[str, exp.Alias]] = [
1947-
col for col in unmanaged_columns_to_types if col != updated_at_name
1946+
select_source_columns: t.List[exp.Expr] = [
1947+
exp.column(col, quoted=True)
1948+
for col in unmanaged_columns_to_types
1949+
if col != updated_at_name
19481950
]
19491951
table_columns = [exp.column(c, quoted=True) for c in target_columns_to_types]
19501952
if updated_at_name:
@@ -2245,7 +2247,7 @@ def remove_managed_columns(
22452247
.with_(
22462248
"inserted_rows",
22472249
exp.select(
2248-
*unmanaged_columns_to_types,
2250+
*(exp.column(col, quoted=True) for col in unmanaged_columns_to_types),
22492251
insert_valid_from_start.as_(valid_from_col.this), # type: ignore
22502252
to_time_column(exp.null(), time_data_type, self.dialect, nullable=True).as_(
22512253
valid_to_col.this

‎sqlmesh/core/engine_adapter/mixins.py‎

Lines changed: 17 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
from sqlmesh.core.node import IntervalUnit
1515
from sqlmesh.core.dialect import schema_
1616
from sqlmesh.core.schema_diff import TableAlterOperation
17+
from sqlmesh.utils import columns_to_types_all_known
1718
from sqlmesh.utils.errors import SQLMeshError
1819

1920
if t.TYPE_CHECKING:
@@ -281,19 +282,22 @@ def _build_create_table_exp(
281282
self.columns(temp_view_name)
282283
)
283284

284-
schema = self._build_schema_exp(
285-
exp.to_table(table_name_or_schema),
286-
columns_to_types_from_view,
287-
)
288-
statement = super()._build_create_table_exp(
289-
schema,
290-
None,
291-
exists=exists,
292-
replace=replace,
293-
target_columns_to_types=columns_to_types_from_view,
294-
table_description=table_description,
295-
**kwargs,
296-
)
285+
if columns_to_types_from_view and columns_to_types_all_known(
286+
columns_to_types_from_view
287+
):
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,
300+
)
297301
finally:
298302
self.drop_view(temp_view_name)
299303

‎sqlmesh/core/engine_adapter/redshift.py‎

Lines changed: 62 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,59 @@ def columns(
103103
sql = sql.where(exp.column("table_schema").eq(table.args["db"].name))
104104

105105
columns_raw = self.fetchall(sql, quote_identifiers=True)
106+
if not columns_raw:
107+
# svv_columns can return 0 rows for late-binding views referencing cross-database /
108+
# datashare objects or schemas without USAGE metadata visibility. Fall back to
109+
# pg_get_late_binding_view_cols() and then pg_catalog.pg_attribute.
110+
late_binding_sql = (
111+
exp.select("col_name", "col_type")
112+
.from_(
113+
exp.Table(
114+
this=exp.func("pg_get_late_binding_view_cols"),
115+
alias=exp.TableAlias(
116+
this=exp.to_identifier("cols"),
117+
columns=[
118+
exp.ColumnDef(
119+
this=exp.to_identifier("view_schema"),
120+
kind=exp.DataType.build("NAME", dialect=self.dialect),
121+
),
122+
exp.ColumnDef(
123+
this=exp.to_identifier("view_name"),
124+
kind=exp.DataType.build("NAME", dialect=self.dialect),
125+
),
126+
exp.ColumnDef(
127+
this=exp.to_identifier("col_name"),
128+
kind=exp.DataType.build("NAME", dialect=self.dialect),
129+
),
130+
exp.ColumnDef(
131+
this=exp.to_identifier("col_type"),
132+
kind=exp.DataType.build("VARCHAR", dialect=self.dialect),
133+
),
134+
exp.ColumnDef(
135+
this=exp.to_identifier("col_num"),
136+
kind=exp.DataType.build("INT", dialect=self.dialect),
137+
),
138+
],
139+
),
140+
)
141+
)
142+
.where(exp.column("view_name").eq(table.alias_or_name))
143+
.order_by("col_num", dialect=self.dialect)
144+
)
145+
if table.args.get("db"):
146+
late_binding_sql = late_binding_sql.where(
147+
exp.column("view_schema").eq(table.args["db"].name)
148+
)
149+
late_binding_cols = self.fetchall(late_binding_sql, quote_identifiers=True)
150+
if late_binding_cols:
151+
return {
152+
col_name: exp.DataType.build(col_type, dialect=self.dialect, udt=True)
153+
for col_name, col_type in late_binding_cols
154+
}
155+
try:
156+
return super().columns(table_name, include_pseudo_columns=include_pseudo_columns)
157+
except SQLMeshError:
158+
return {}
106159

107160
def build_var_length_col(
108161
column_name: str,
@@ -228,13 +281,15 @@ def create_view(
228281
underlying table without dropping the view first. This is a problem for us since we want to be able to
229282
swap tables out from under views. Therefore, we create the view as non-binding.
230283
"""
231-
no_schema_binding = True
232-
if isinstance(query_or_df, exp.Expr):
233-
# We can't include NO SCHEMA BINDING if the query has a recursive CTE
234-
has_recursive_cte = any(
235-
w.args.get("recursive", False) for w in query_or_df.find_all(exp.With)
236-
)
237-
no_schema_binding = not has_recursive_cte
284+
no_schema_binding: t.Optional[bool] = create_kwargs.pop("no_schema_binding", None)
285+
if no_schema_binding is None:
286+
no_schema_binding = True
287+
if isinstance(query_or_df, exp.Expr):
288+
# We can't include NO SCHEMA BINDING if the query has a recursive CTE
289+
has_recursive_cte = any(
290+
w.args.get("recursive", False) for w in query_or_df.find_all(exp.With)
291+
)
292+
no_schema_binding = not has_recursive_cte
238293

239294
return super().create_view(
240295
view_name,

‎sqlmesh/utils/__init__.py‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -342,8 +342,10 @@ def type_is_known(d_type: t.Union[exp.DataType, exp.ColumnDef]) -> bool:
342342

343343

344344
def columns_to_types_all_known(columns_to_types: t.Dict[str, exp.DataType]) -> bool:
345-
"""Checks that all column types are known and not NULL."""
346-
return all(type_is_known(expression) for expression in columns_to_types.values())
345+
"""Checks that all column types are non-empty, known, and not NULL."""
346+
return bool(columns_to_types) and all(
347+
type_is_known(expression) for expression in columns_to_types.values()
348+
)
347349

348350

349351
class Verbosity(IntEnum):

‎tests/core/engine_adapter/test_mssql.py‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1069,3 +1069,26 @@ def test_concat_columns_uses_varchar_max(adapter: MSSQLEngineAdapter):
10691069
adapter.concat_columns(columns_to_types).sql(dialect=adapter.dialect)
10701070
== "COALESCE(CAST(id AS VARCHAR(MAX)), '') + ',' + COALESCE(CAST(name AS VARCHAR(MAX)), '')"
10711071
)
1072+
1073+
1074+
def test_ctas_varchar_workaround_empty_columns_fallback(
1075+
make_mocked_engine_adapter: t.Callable, mocker: MockerFixture
1076+
):
1077+
adapter = make_mocked_engine_adapter(MSSQLEngineAdapter)
1078+
mocker.patch("sqlmesh.core.engine_adapter.base.random_id", return_value="test_random_id")
1079+
mocker.patch(
1080+
"sqlmesh.core.engine_adapter.mssql.MSSQLEngineAdapter.table_exists", return_value=False
1081+
)
1082+
mocker.patch("sqlmesh.core.engine_adapter.mssql.MSSQLEngineAdapter.columns", return_value={})
1083+
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+
)
1089+
1090+
assert to_sql_calls(adapter) == [
1091+
"CREATE VIEW [__temp_ctas_test_random_id] AS SELECT [a], [b] FROM [tbl];",
1092+
"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;",
1094+
]

0 commit comments

Comments
 (0)