### Description
Add `DROP CONSTRAINT ... IF EXISTS` behavior to the compiler.
Fixes https://github.com/sqlalchemy/sqlalchemy/issues/8141
### Checklist
<!-- go over following points. check them with an `x` if they do apply, (they turn into clickable checkboxes once the PR is submitted, so no need to do everything at once)
-->
This pull request is:
- [ ] A documentation / typographical error fix
- Good to go, no issue or tests are needed
- [ ] A short code fix
- please include the issue number, and create an issue if none exists, which
must include a complete example of the issue. one line code fixes without an
issue and demonstration will not be accepted.
- Please include: `Fixes: #<issue number>` in the commit message
- please include tests. one line code fixes without tests will not be accepted.
- [x] A new feature implementation
- please include the issue number, and create an issue if none exists, which must
include a complete example of how the feature would look.
- Please include: `Fixes: #<issue number>` in the commit message
- please include tests.
**Have a nice day!**
Closes: #8161
Pull-request: https://github.com/sqlalchemy/sqlalchemy/pull/8161
Pull-request-sha:
43276e29fa864fc66900c5a3fa0bf84df5f14271
Change-Id: I18bae3cf013159b6fffde4413fb59ce19ff83c16
--- /dev/null
+.. 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.
\ No newline at end of file
"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):
"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()