Skip to content

Instantly share code, notes, and snippets.

@nZac
Last active November 26, 2020 20:21
Show Gist options
  • Save nZac/da15574c5c564c0b8895 to your computer and use it in GitHub Desktop.
Save nZac/da15574c5c564c0b8895 to your computer and use it in GitHub Desktop.
Temporarily Drop a Foreign Key Constraint, Python, SQLAlchemy
class TempDropConstraint(object):
def __init__(self, table, column):
self.table = table
self.table_name = table.__tablename__
self.column = column
self.constraint = list(self.table.__table__.columns[column.name].foreign_keys)[0]
self.constraint_name = self.constraint.name
self.referred_table = self.constraint.column.table.name
self.referred_columns = self.constraint.column.name
def __enter__(self):
sql = """
ALTER TABLE {table}
DROP CONSTRAINT {constraint}
""".format(
table=self.table_name,
constraint=self.constraint_name
)
db.session.execute(sql)
log.info('Dropped constraint')
def __exit__(self, exc_type, exc_val, exc_tb):
sql = """
ALTER TABLE {table_name}
ADD CONSTRAINT {constraint_name}
FOREIGN KEY ({column})
REFERENCES {referred_table} ({referred_columns})
""".format(
table_name=self.table_name,
constraint_name=self.constraint_name,
column=self.column.name,
referred_table=self.referred_table,
referred_columns=self.referred_columns
)
db.session.execute(sql)
log.info('Added constraint')
with TempDropConstraint(Entity, Entity.column):
# Thing which doesn't need FK constraint
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment