Python SqlAlchemy:如何实现DROP表。。。大量
我需要删除具有外键约束的PostgreSQL数据库中的表,并且需要Python SqlAlchemy:如何实现DROP表。。。大量,python,postgresql,sqlalchemy,Python,Postgresql,Sqlalchemy,我需要删除具有外键约束的PostgreSQL数据库中的表,并且需要删除表。。。级联 我可以执行原始SQL:engine.execute(“删除表%s CASCADE;%TABLE.name)。 但是,我希望实现这种行为,这样我就可以对postgresql方言执行table.drop(engine) 如何实现这一点?您需要pg_constraint中的数据,即处理所有约束的数据,包括检查约束和外键。幸运的是,您想要的是相当简单的 要获取引用tablefoo的所有表的列表,可以执行以下操作: SEL
删除表。。。级联
我可以执行原始SQL:engine.execute(“删除表%s CASCADE;%TABLE.name)
。
但是,我希望实现这种行为,这样我就可以对postgresql
方言执行table.drop(engine)
如何实现这一点?您需要
pg_constraint
中的数据,即处理所有约束的数据,包括检查约束和外键。幸运的是,您想要的是相当简单的
要获取引用tablefoo
的所有表的列表,可以执行以下操作:
SELECT conrelid
FROM pg_constraint
WHERE confrelid = <the relid for foo>;
它返回一个列表,然后您可以循环遍历该列表,并发出单个的DROP TABLE
语句。您可以这样:
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
语句,同时保持所有其他方言相同
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"