Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions doc/build/changelog/unreleased_20/8141.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
.. change::
:tags: usecase, schema
:tickets: 8141

Added parameter :paramref:`_ddl.DropConstraint.if_exists` to the
:class:`_ddl.DropConstraint` construct which result in "IF EXISTS" DDL
being added to the DROP statement.
This phrase is not accepted by all databases and the operation will fail
on a database that does not support it as there is no similarly compatible
fallback within the scope of a single DDL statement.
Pull request courtesy Mike Fiedler.
5 changes: 3 additions & 2 deletions lib/sqlalchemy/sql/compiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -5210,10 +5210,11 @@ def visit_drop_constraint(self, drop, **kw):
"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),
"IF EXISTS " if drop.if_exists else "",
formatted_name,
drop.cascade and " CASCADE" or "",
" CASCADE" if drop.cascade else "",
)

def get_column_specification(self, column, **kwargs):
Expand Down
10 changes: 10 additions & 0 deletions test/sql/test_constraints.py
Original file line number Diff line number Diff line change
Expand Up @@ -1261,6 +1261,16 @@ def test_render_drop_constraint_cascade(self):
"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()

Expand Down