Fix foreign key constraint errors during import#23
Open
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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 towp_cartflows_ca_email_templates) fails because_email_historyis 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 equivalentPRAGMA foreign_keys = OFF. BothWP_SQLite_DriverandWP_SQLite_TranslatorenablePRAGMA foreign_keys = ONat initialization, so FK constraints remain enforced throughout the import regardless of the MySQL-level setting.Changes
Use
execute_sqlite_query()to explicitly setPRAGMA foreign_keys = OFFbefore the import and re-enable it afterward. After re-enabling,PRAGMA foreign_key_checkvalidates 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.tar.gz
wp sqlite import <fk-test-backup>