Created
January 22, 2015 14:44
-
-
Save SalemHarrache/9f1756b2f56bae634ba9 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() |
mikeghen
commented
Jun 23, 2018
•
DropConstraint
just saved my life! And the opposite is AddConstraint
which emits an ALTER TABLE CREATE CONSTRAINT ...
@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