-
-
Save bdraco/85972289381736d89bec025c57f67b42 to your computer and use it in GitHub Desktop.
SQLAlchemy : remove all foreign keys constraints
This file contains 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
def remove_foreign_keys(db): | |
log("Dropping all foreign key constraints from archive database") | |
inspector = reflection.Inspector.from_engine(db.engine) | |
fake_metadata = MetaData() | |
fake_tables = [] | |
all_fks = [] | |
for table_name in db.metadata.tables: | |
fks = [] | |
for fk in inspector.get_foreign_keys(table_name): | |
if fk['name']: | |
fks.append(ForeignKeyConstraint((),(),name=fk['name'])) | |
t = Table(table_name, fake_metadata, *fks) | |
fake_tables.append(t) | |
all_fks.extend(fks) | |
connection = db.engine.connect() | |
transaction = connection.begin() | |
for fkc in all_fks: | |
connection.execute(DropConstraint(fkc)) | |
transaction.commit() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment