Skip to content

Commit 85075a0

Browse files
committed
Changes to how FKs are handled during migrations
At the start of all migrations FK checks are disabled. After migration, they are verified and then re-enabled.
1 parent 35795a4 commit 85075a0

File tree

1 file changed

+20
-1
lines changed

1 file changed

+20
-1
lines changed

breadbox/alembic/env.py

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,11 @@ def run_migrations_online():
7171
)
7272

7373
with connectable.connect() as connection:
74-
connection.execute("PRAGMA foreign_keys = ON")
74+
# because alembic batch operations drop and recreate tables, this causes
75+
# problems with foreign key constraints. To work around this, we'll explicitly
76+
# disable foreign key constraints at the before running migrations and the
77+
# explicitly check the constraints after applying the migrations
78+
connection.execute("PRAGMA foreign_keys = OFF")
7579

7680
context.configure(
7781
connection=connection,
@@ -83,6 +87,21 @@ def run_migrations_online():
8387
with context.begin_transaction():
8488
context.run_migrations()
8589

90+
# verify there are no broken foreign key constraints
91+
print("Checking fk constraints...")
92+
# if there are violated constraint, the pragma returns a row for each
93+
rows = connection.execute("pragma foreign_key_check").fetchall()
94+
if len(rows) > 0:
95+
for row in rows:
96+
print("FK violated:", row)
97+
98+
raise Exception("FK constraints violated at the end of running migrations!")
99+
print("Done. fk constraints are ok")
100+
101+
# shouldn't matter, but since I explictly disabled the constraints at the start
102+
# I'd like to turn it back on at the end.
103+
connection.execute("PRAGMA foreign_keys = ON")
104+
86105

87106
if context.is_offline_mode():
88107
run_migrations_offline()

0 commit comments

Comments
 (0)