I need to drop tables in a PostgreSQL database that have foreign key constraints and require DROP TABLE ... CASCADE
.
I could execute raw SQL: engine.execute("DROP TABLE %s CASCADE;" % table.name)
.
However, I would like to implement this behaviour such that I can do table.drop(engine)
for the postgresql
dialect.
How would one approach this?
You can customize the compilation of constructs like this:
from sqlalchemy.schema import DropTable
from sqlalchemy.ext.compiler import compiles
@compiles(DropTable, "postgresql")
def _compile_drop_table(element, compiler, **kwargs):
return compiler.visit_drop_table(element) + " CASCADE"
This appends CASCADE
to the DROP TABLE
statement issued for the postgresql dialect while keeping all other dialects the same.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With