Skip to content

Fix foreign key constraint errors during import#23

Open
gcsecsey wants to merge 2 commits intomainfrom
fix/fk-import-error
Open

Fix foreign key constraint errors during import#23
gcsecsey wants to merge 2 commits intomainfrom
fix/fk-import-error

Conversation

@gcsecsey
Copy link

Summary

When importing SQL dumps where tables are processed in alphabetical order (as Studio does with Jetpack backups), any table containing a FOREIGN KEY constraint referencing another table that comes later alphabetically causes the import to fail with a SQLite constraint error.

For example, a backup containing wp_cartflows_ca_email_history (which has an FK to wp_cartflows_ca_email_templates) fails because _email_history is imported before _email_templates.

This affects any WordPress plugin that uses foreign key constraints between tables.

Context

The import command already sets SET FOREIGN_KEY_CHECKS=0. However, the SQLite driver stores this as a PHP session variable, it does not translate it to SQLite’s equivalent PRAGMA foreign_keys = OFF. Both WP_SQLite_Driver and WP_SQLite_Translator enable PRAGMA foreign_keys = ON at initialization, so FK constraints remain enforced throughout the import regardless of the MySQL-level setting.

Changes

Use execute_sqlite_query() to explicitly set PRAGMA foreign_keys = OFF before the import and re-enable it afterward. After re-enabling, PRAGMA foreign_key_check validates all FK references, catching any actual data integrity issues.

Testing

I prepared this test SQL dump where a child table with an FK constraint appears before its referenced parent table:

fk-test-backup
└── sql
    ├── wp_aa_child.sql
    └── wp_zz_parent.sql

fk-test-backup.tar.gz

  • Run wp sqlite import <fk-test-backup>
  • Before fix: import fails with constraint error on the INSERT into the child table
  • After fix: import succeeds, both tables are created with correct data

@gcsecsey gcsecsey requested a review from a team March 17, 2026 17:10
@gcsecsey gcsecsey marked this pull request as ready for review March 17, 2026 17:11
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant