SqlAlchemy: How to implement DROP TABLE … CASCADE?

前端 未结 2 2028
长情又很酷
长情又很酷 2020-12-31 05:58

I need to drop tables in a PostgreSQL database that have foreign key constraints and require DROP TABLE ... CASCADE.

I could execute raw SQL: engi

2条回答
  •  -上瘾入骨i
    2020-12-31 06:43

    You need the data in pg_constraint, which is a rather complicated table, that handles all constraints, including check constraints and foreign keys. Fortunately, what you want is fairly straightforward.

    In order to get the list of all of the tables referencing table foo, you can do something like:

    SELECT conrelid
      FROM pg_constraint
      WHERE confrelid = ;
    

    That gets you a list of table relids. But you probably don't want to deal with relids, so let's make it a bit more complicated:

    SELECT r.schemaname || '.' || r.relname
      FROM pg_stat_user_tables r, pg_constraint c, pg_stat_user_tables s
      WHERE
        s.relid = c.confrelid AND
        c.conrelid = r.relid AND
        s.relname = 'foo';
    

    That returns a list which you can then loop through and issue individual DROP TABLE statements.

提交回复
热议问题