]> git.ipfire.org Git - thirdparty/sqlalchemy/sqlalchemy.git/commitdiff
feat: add `drop constraint if exists`
authorMike Fiedler <miketheman@gmail.com>
Sat, 25 Jun 2022 00:33:37 +0000 (00:33 +0000)
committerMike Fiedler <miketheman@gmail.com>
Sat, 25 Jun 2022 00:35:06 +0000 (00:35 +0000)
Add `DROP CONSTRAINT ... IF EXISTS` behavior to the compiler.

Fixes #8141

Signed-off-by: Mike Fiedler <miketheman@gmail.com>
lib/sqlalchemy/sql/compiler.py
test/sql/test_constraints.py

index 8ce0c65e42ce865ad72ad06c9ac1367c2be9ea42..9cc928a810899e464e3e55d601746aaca26d4ce2 100644 (file)
@@ -5210,8 +5210,9 @@ class DDLCompiler(Compiled):
                 "Can't emit DROP CONSTRAINT for constraint %r; "
                 "it has no name" % drop.element
             )
-        return "ALTER TABLE %s DROP CONSTRAINT %s%s" % (
+        return "ALTER TABLE %s DROP CONSTRAINT %s%s%s" % (
             self.preparer.format_table(drop.element.table),
+            drop.if_exists and "IF EXISTS " or "",
             formatted_name,
             drop.cascade and " CASCADE" or "",
         )
index c417255af612612343015164308ec47e3de0230d..462667bedcedb875894b6ff929d3a78218697424 100644 (file)
@@ -1261,6 +1261,16 @@ class ConstraintCompilationTest(fixtures.TestBase, AssertsCompiledSQL):
             "ALTER TABLE tbl DROP CONSTRAINT my_test_constraint CASCADE",
         )
 
+    def test_render_drop_constraint_if_exists(self):
+        t, t2 = self._constraint_create_fixture()
+
+        constraint = CheckConstraint("a = 1", name="a1", table=t)
+
+        self.assert_compile(
+            schema.DropConstraint(constraint, if_exists=True),
+            "ALTER TABLE tbl DROP CONSTRAINT IF EXISTS a1",
+        )
+
     def test_render_add_fk_constraint_stringcol(self):
         t, t2 = self._constraint_create_fixture()