Skip to content

Commit 215ceae

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

2 files changed

Lines changed: 41 additions & 2 deletions

File tree

sqlmesh/core/engine_adapter/mssql.py

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -172,15 +172,24 @@ 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_name = ".".join(
177+
[
178+
exp.to_identifier(obj.schema_name).sql(self.dialect),
179+
exp.to_identifier(obj.name).sql(self.dialect),
180+
]
181+
)
182+
object_table = exp.to_table(object_name, dialect=self.dialect)
183+
175184
# _get_data_objects is catalog-specific, so these can't accidentally drop view/tables in another catalog
176185
if obj.type == DataObjectType.VIEW:
177186
self.drop_view(
178-
".".join([obj.schema_name, obj.name]),
187+
object_table,
179188
ignore_if_not_exists=ignore_if_not_exists,
180189
)
181190
else:
182191
self.drop_table(
183-
".".join([obj.schema_name, obj.name]),
192+
object_table,
184193
exists=ignore_if_not_exists,
185194
)
186195
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)