Skip to content

Commit c3a4362

Browse files
Fix(mssql): Properly quote table and views when dropping in mssql (#4773)
1 parent 347aa7c commit c3a4362

2 files changed

Lines changed: 35 additions & 2 deletions

File tree

sqlmesh/core/engine_adapter/mssql.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -172,15 +172,18 @@ def drop_schema(
172172
if cascade:
173173
objects = self._get_data_objects(schema_name)
174174
for obj in objects:
175+
# Build properly quoted table for MSSQL using square brackets when needed
176+
object_table = exp.table_(obj.name, obj.schema_name)
177+
175178
# _get_data_objects is catalog-specific, so these can't accidentally drop view/tables in another catalog
176179
if obj.type == DataObjectType.VIEW:
177180
self.drop_view(
178-
".".join([obj.schema_name, obj.name]),
181+
object_table,
179182
ignore_if_not_exists=ignore_if_not_exists,
180183
)
181184
else:
182185
self.drop_table(
183-
".".join([obj.schema_name, obj.name]),
186+
object_table,
184187
exists=ignore_if_not_exists,
185188
)
186189
super().drop_schema(schema_name, ignore_if_not_exists=ignore_if_not_exists, cascade=False)

tests/core/engine_adapter/test_mssql.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -655,6 +655,36 @@ def test_drop_schema(make_mocked_engine_adapter: t.Callable):
655655
]
656656

657657

658+
def test_drop_schema_with_special_identifiers(make_mocked_engine_adapter: t.Callable):
659+
adapter = make_mocked_engine_adapter(MSSQLEngineAdapter)
660+
661+
adapter._get_data_objects = mock.Mock()
662+
adapter._get_data_objects.return_value = [
663+
DataObject(
664+
catalog="test_catalog",
665+
schema="test schema", # Schema with space
666+
name="test view", # Object with space
667+
type=DataObjectType.from_str("VIEW"),
668+
),
669+
DataObject(
670+
catalog="test_catalog",
671+
schema="test schema",
672+
name="test table", # Table with space
673+
type=DataObjectType.from_str("TABLE"),
674+
),
675+
]
676+
677+
schema_name = exp.to_table("[test schema]", dialect="tsql")
678+
adapter.drop_schema(schema_name, cascade=True)
679+
680+
# Validate that names with spaces/special chars are properly quoted with square brackets
681+
assert to_sql_calls(adapter) == [
682+
"""DROP VIEW IF EXISTS [test schema].[test view];""",
683+
"""DROP TABLE IF EXISTS [test schema].[test table];""",
684+
"""DROP SCHEMA IF EXISTS [test schema];""",
685+
]
686+
687+
658688
def test_df_dates(make_mocked_engine_adapter: t.Callable):
659689
adapter = make_mocked_engine_adapter(MSSQLEngineAdapter)
660690

0 commit comments

Comments
 (0)