@@ -71,7 +71,11 @@ def run_migrations_online():
71
71
)
72
72
73
73
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" )
75
79
76
80
context .configure (
77
81
connection = connection ,
@@ -83,6 +87,21 @@ def run_migrations_online():
83
87
with context .begin_transaction ():
84
88
context .run_migrations ()
85
89
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
+
86
105
87
106
if context .is_offline_mode ():
88
107
run_migrations_offline ()
0 commit comments