SqlAlchemy:如何实现 DROP TABLE ... CASCADE? [英] SqlAlchemy: How to implement DROP TABLE ... CASCADE?
问题描述
我需要删除具有外键约束并需要 DROP TABLE ... CASCADE
的 PostgreSQL 数据库中的表.
I need to drop tables in a PostgreSQL database that have foreign key constraints and require DROP TABLE ... CASCADE
.
我可以执行原始 SQL:engine.execute("DROP TABLE %s CASCADE;" % table.name)
.但是,我想实现这种行为,以便我可以为 postgresql
方言执行 table.drop(engine)
.
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?
推荐答案
您可以自定义构造的编译,如下所示:
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"
这将 CASCADE
附加到为 postgresql 方言发出的 DROP TABLE
语句,同时保持所有其他方言相同.
This appends CASCADE
to the DROP TABLE
statement issued for the postgresql dialect while keeping all other dialects the same.
这篇关于SqlAlchemy:如何实现 DROP TABLE ... CASCADE?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!