Last active
December 20, 2015 17:09
-
-
Save inklesspen/6166852 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 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