From 120171a7902c80dd7f6dc93f1abadb1bf23ee194 Mon Sep 17 00:00:00 2001 From: Mike Fiedler Date: Sat, 25 Jun 2022 00:33:37 +0000 Subject: [PATCH] feat: add `drop constraint if exists` Add `DROP CONSTRAINT ... IF EXISTS` behavior to the compiler. Fixes #8141 Signed-off-by: Mike Fiedler --- lib/sqlalchemy/sql/compiler.py | 3 ++- test/sql/test_constraints.py | 10 ++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/lib/sqlalchemy/sql/compiler.py b/lib/sqlalchemy/sql/compiler.py index 8ce0c65e42..9cc928a810 100644 --- a/lib/sqlalchemy/sql/compiler.py +++ b/lib/sqlalchemy/sql/compiler.py @@ -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 "", ) diff --git a/test/sql/test_constraints.py b/test/sql/test_constraints.py index c417255af6..462667bedc 100644 --- a/test/sql/test_constraints.py +++ b/test/sql/test_constraints.py @@ -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() -- 2.47.3