Skip to content

Instantly share code, notes, and snippets.

@bdraco
Forked from SalemHarrache/remove_foreign_keys.py
Created November 26, 2020 20:21
Show Gist options
  • Save bdraco/85972289381736d89bec025c57f67b42 to your computer and use it in GitHub Desktop.
Save bdraco/85972289381736d89bec025c57f67b42 to your computer and use it in GitHub Desktop.
SQLAlchemy : remove all foreign keys constraints
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