Skip to content

Instantly share code, notes, and snippets.

@SalemHarrache
Created January 22, 2015 14:44
Show Gist options
  • Save SalemHarrache/9f1756b2f56bae634ba9 to your computer and use it in GitHub Desktop.
Save SalemHarrache/9f1756b2f56bae634ba9 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()
@makmanalp
Copy link

DropConstraint just saved my life! And the opposite is AddConstraint which emits an ALTER TABLE CREATE CONSTRAINT ...

@fn-hide
Copy link

fn-hide commented Aug 28, 2023

@mikeghen Thank you, just saved my life too! But, I use sqlalchemy 1.4.39 and I edit the code as follow

From:

inspector = reflection.Inspector.from_engine(db.engine)

To:

from sqlalchemy import inspect
inspector = inspect(engine)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment