Skip to content

Instantly share code, notes, and snippets.

@inklesspen
Last active December 20, 2015 17:09
Show Gist options
  • Select an option

  • Save inklesspen/6166852 to your computer and use it in GitHub Desktop.

Select an option

Save inklesspen/6166852 to your computer and use it in GitHub Desktop.
# Given a SQLAlchemy engine, this will drop all the tables reachable from that engine
# I've used this in PostgreSQL, but it should work with other dialects as well.
from sqlalchemy.engine import reflection
from sqlalchemy.schema import (
MetaData,
Table,
DropTable,
ForeignKeyConstraint,
DropConstraint,
)
def drop_everything(engine):
conn = engine.connect()
trans = conn.begin()
inspector = reflection.Inspector.from_engine(engine)
metadata = MetaData()
tbs = []
all_fks = []
for table_name in inspector.get_table_names():
fks = []
for fk in inspector.get_foreign_keys(table_name):
if not fk['name']:
continue
fks.append(ForeignKeyConstraint((), (), name=fk['name']))
t = Table(table_name, metadata, *fks)
tbs.append(t)
all_fks.extend(fks)
for fkc in all_fks:
conn.execute(DropConstraint(fkc))
for table in tbs:
conn.execute(DropTable(table))
trans.commit()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment