SqlAlchemy: How to implement DROP TABLE … CASCADE?

前端 未结 2 2029
长情又很酷
长情又很酷 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条回答
  • 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 = <the relid for foo>;
    

    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.

    0 讨论(0)
  • 2020-12-31 06:53

    You can customize the compilation of constructs like this:

    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"
    

    This appends CASCADE to the DROP TABLE statement issued for the postgresql dialect while keeping all other dialects the same.

    0 讨论(0)
提交回复
热议问题