Skip to content

Instantly share code, notes, and snippets.

@stephenemslie
Created November 13, 2014 15:26
Show Gist options
  • Save stephenemslie/cf97c378b62c9000ad23 to your computer and use it in GitHub Desktop.
Save stephenemslie/cf97c378b62c9000ad23 to your computer and use it in GitHub Desktop.
e.g. DBURI=postgres://user:pass@host:port/name python alembic_fk_deferrable.py
import os
import sqlalchemy as sa
engine = sa.create_engine(os.environ['DBURI'])
meta = sa.MetaData(bind=engine, reflect=True)
tmpl = """
op.drop_constraint('{name}', '{source}')
op.create_foreign_key('{name}', '{source}', '{referent}', ['{local_cols}'], ['{remote_cols}'], deferrable=True)
"""
for name, table in meta.tables.items():
for fk in table.foreign_keys:
c = fk.constraint
print tmpl.format(name=c.name,
source=c.table.name,
referent=fk.column.table.name,
local_cols=c.columns[0],
remote_cols=fk.column.name).strip()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment