Skip to content Skip to sidebar Skip to footer

Sqlalchemy: How To Implement Drop Table ... Cascade?

I need to drop tables in a PostgreSQL database that have foreign key constraints and require DROP TABLE ... CASCADE. I could execute raw SQL: engine.execute('DROP TABLE %s CASCADE;

Solution 1:

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.

Solution 2:

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.

Post a Comment for "Sqlalchemy: How To Implement Drop Table ... Cascade?"