defer_foreign_keys doesn't stop DROP TABLE from cascading in D1
- Field note
Deferring postpones the check for violations, and it doesn't turn off foreign key actions. The SQLite documentation says DROP TABLE runs an implicit DELETE FROM when foreign keys are enabled, and that this "does cause any configured foreign key actions to take place". So ON DELETE CASCADE fires during the drop, and at commit there are no violations left to report.
Reproduced on SQLite with one parent row and one child row:
| Setting | Child rows after DROP TABLE |
|---|---|
foreign_keys=ON |
0 |
foreign_keys=ON, defer_foreign_keys=ON |
0 |
foreign_keys=OFF |
1 |
The migration that works on D1:
PRAGMA defer_foreign_keys = true;
CREATE TABLE revisions_keep AS SELECT * FROM revisions;
-- create posts_new, copy rows, DROP TABLE posts, rename posts_new to posts
DELETE FROM revisions;
INSERT INTO revisions SELECT * FROM revisions_keep;
DROP TABLE revisions_keep;Test this against a database that has child rows. On an empty one, the migration passes and tells you nothing.