python - SqlAlchemy:如何实现 DROP TABLE ... CASCADE?

标签 python postgresql sqlalchemy

我需要删除具有外键约束的 PostgreSQL 数据库中的表,并且需要 DROP TABLE ... CASCADE

我可以执行原始 SQL:engine.execute("DROP TABLE %s CASCADE;"% table.name)。 但是,我想实现此行为,以便我可以为 postgresql 方言执行 table.drop(engine)

如何解决这个问题?

最佳答案

您可以 customize the compilation of constructs像这样:

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 语句,同时保持所有其他方言相同。

关于python - SqlAlchemy:如何实现 DROP TABLE ... CASCADE?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38678336/

相关文章:

jquery - 带有多个选择的 web.py Json

mysql - postgres - 修改 xml(MySql UpdateXml 替代)

python - 加入条件以急切地加载 sqlalchemy orm

python - 使用 SQLAlchemy 获取表中的行数

python - Flask-SQLAlchemy query.get() 在查询不存在的键时抛出异常

python - 我如何在 gdb 中使用 python 访问寄存器

python - 将 RDD 划分为长度为 n 的元组

python - Fabric - 有什么方法可以捕获运行标准输出?

sql - sequelize 原始查询列不存在

postgresql - 如何将 Google App Engine (Flex) Go 应用程序连接到 Google Cloud Postgres 实例