Как удалить все таблицы, включая зависимый объект - PullRequest
0 голосов
/ 13 февраля 2020

Когда я пытаюсь удалить все таблицы с помощью:

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.

Существует ли элегантное однострочное решение для этого?

1 Ответ

0 голосов
/ 14 февраля 2020
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
...