python - 如何删除所有表,包括依赖对象
问题描述
当我尝试删除所有表时:
base.metadata.drop_all(engine)
我收到以下错误:
ERROR:libdl.database_operations:Cannot drop table: (psycopg2.errors.DependentObjectsStillExist) cannot drop sequence <schema>.<sequence> because other objects depend on it
DETAIL: default for table <schema>.<table> column id depends on sequence <schema>.<sequence>
HINT: Use DROP ... CASCADE to drop the dependent objects too.
有没有一种优雅的单线解决方案?
解决方案
import psycopg2
from psycopg2 import sql
cnn = psycopg2.connect('...')
cur = cnn.cursor()
cur.execute("""
select s.nspname as s, t.relname as t
from pg_class t join pg_namespace s on s.oid = t.relnamespace
where t.relkind = 'r'
and s.nspname !~ '^pg_' and s.nspname != 'information_schema'
order by 1,2
""")
tables = cur.fetchall() # make sure they are the right ones
for t in tables:
cur.execute(
sql.SQL("drop table if exists {}.{} cascade")
.format(sql.Identifier(t[0]), sql.Identifier(t[1])))
cnn.commit() # goodbye
推荐阅读
- r - R Parallel EasyABC 或 smfsb:ABC-SMC
- json - json文件未在本机反应中更新
- visual-studio - Visual Studio 2019 退出并显示“Docker 命令失败,退出代码 -1073741515”
- memurai - Memurai Developer Sentinel 作为服务不会注册
- javascript - 如何计算一个数组相对于另一个数组
- python - 如果满足日期条件,则从数据框中提取特定值
- r-markdown - 使用 Rmd 块代码样式编织 Markdown 代码块
- python - 树人 js 的 Python 递归函数
- tfs - 在进行反向集成时,我的合并变更集为什么会重新出现?
- javascript - Only the month of february is not rendering perfectly