]> git.ipfire.org Git - thirdparty/sqlalchemy/sqlalchemy.git/commitdiff
Support for `IF EXISTS` in SQL Server 2016 (13.x) and later versions
authorEdgar Ramírez Mondragón <edgarrm358@gmail.com>
Thu, 18 Dec 2025 04:11:33 +0000 (22:11 -0600)
committerEdgar Ramírez Mondragón <edgarrm358@gmail.com>
Thu, 18 Dec 2025 04:20:26 +0000 (22:20 -0600)
Fixes: #13045
Signed-off-by: Edgar Ramírez Mondragón <edgarrm358@gmail.com>
lib/sqlalchemy/dialects/mssql/base.py
test/dialect/mssql/test_compiler.py

index 94f265ebed1d0f45d5161a9c7455da20e6742b4f..256f975fdefb770a0f9953f7c5d48bcfb839496f 100644 (file)
@@ -963,6 +963,7 @@ import codecs
 import datetime
 import operator
 import re
+from typing import Any
 from typing import Literal
 from typing import overload
 from typing import TYPE_CHECKING
@@ -1014,6 +1015,7 @@ from ...types import VARCHAR
 from ...util import update_wrapper
 
 if TYPE_CHECKING:
+    from ...sql.ddl import DropIndex
     from ...sql.dml import DMLState
     from ...sql.selectable import TableClause
 
@@ -2688,11 +2690,21 @@ class MSDDLCompiler(compiler.DDLCompiler):
 
         return text
 
-    def visit_drop_index(self, drop, **kw):
-        return "\nDROP INDEX %s ON %s" % (
-            self._prepared_index_name(drop.element, include_schema=False),
-            self.preparer.format_table(drop.element.table),
-        )
+    def visit_drop_index(self, drop: DropIndex, **kw: Any) -> str:
+        index = drop.element
+
+        text = "\nDROP INDEX "
+
+        if (
+            # only supported in 2016+
+            self.dialect.server_version_info < MS_2016_VERSION
+            and drop.if_exists
+        ):
+            text += "IF EXISTS "
+
+        text += self._prepared_index_name(index, include_schema=False)
+        text += " ON " + self.preparer.format_table(index.table)
+        return text
 
     def visit_create_table_as(self, element, **kw):
         prep = self.preparer
index f8d9d548862643907d3782c8a862632f4dbc9854..30e7f79a2933410d783b8e0fe9d2d4f56a6b36ff 100644 (file)
@@ -1534,6 +1534,14 @@ class CompileTest(fixtures.TestBase, AssertsCompiledSQL):
             "DROP INDEX idx_foo ON bar.foo",
         )
 
+    def test_drop_index_if_exists(self):
+        m = MetaData()
+        t1 = Table("foo", m, Column("x", Integer), schema="bar")
+        self.assert_compile(
+            schema.DropIndex(Index("idx_foo", t1.c.x), if_exists=True),
+            "DROP INDEX IF EXISTS idx_foo ON bar.foo",
+        )
+
     def test_index_extra_include_1(self):
         metadata = MetaData()
         tbl = Table(