File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -191,3 +191,24 @@ Feature: WP-CLI SQLite Import Command
191191
192192 And the SQLite database should contain a table named "test_table"
193193 And the "test_table" should contain a row with name ""
194+
195+ @require-sqlite
196+ Scenario : Import tables with foreign key constraints when child table is imported before parent
197+ Given a SQL dump file named "test_import.sql" with content:
198+ """
199+ CREATE TABLE wp_aa_child (
200+ id INTEGER PRIMARY KEY,
201+ parent_id INTEGER NOT NULL,
202+ CONSTRAINT fk_parent FOREIGN KEY (parent_id) REFERENCES wp_zz_parent(id)
203+ );
204+ INSERT INTO wp_aa_child (id, parent_id) VALUES (1, 1);
205+ CREATE TABLE wp_zz_parent (id INTEGER PRIMARY KEY, name TEXT NOT NULL);
206+ INSERT INTO wp_zz_parent (id, name) VALUES (1, 'Parent Row');
207+ """
208+ When I run `wp sqlite --enable-ast-driver import test_import.sql`
209+ Then STDOUT should contain:
210+ """
211+ Success: Imported from 'test_import.sql'.
212+ """
213+ And the SQLite database should contain a table named "wp_zz_parent"
214+ And the SQLite database should contain a table named "wp_aa_child"
Original file line number Diff line number Diff line change @@ -49,8 +49,27 @@ public function run( $sql_file_path, $args ) {
4949 $ this ->driver ->query ( 'SET @BACKUP_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 ' );
5050 $ this ->driver ->query ( 'SET @BACKUP_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 ' );
5151
52+ /*
53+ * Disable foreign key constraints at the SQLite level during import.
54+ *
55+ * The MySQL SET FOREIGN_KEY_CHECKS=0 above is stored as a session
56+ * variable by the driver but does not translate to SQLite's PRAGMA.
57+ * We need to explicitly disable foreign keys so that tables with
58+ * cross-references can be imported in any order (e.g., alphabetical).
59+ */
60+ $ this ->driver ->execute_sqlite_query ( 'PRAGMA foreign_keys = OFF ' );
61+
5262 $ this ->execute_statements ( $ import_file );
5363
64+ /*
65+ * Re-enable foreign key constraints and verify integrity.
66+ *
67+ * PRAGMA foreign_key_check validates all FK references after the
68+ * full import, catching any actual data integrity issues.
69+ */
70+ $ this ->driver ->execute_sqlite_query ( 'PRAGMA foreign_key_check ' );
71+ $ this ->driver ->execute_sqlite_query ( 'PRAGMA foreign_keys = ON ' );
72+
5473 $ this ->driver ->query ( 'SET SQL_MODE=@BACKUP_SQL_MODE ' );
5574 $ this ->driver ->query ( 'SET UNIQUE_CHECKS=@BACKUP_UNIQUE_CHECKS ' );
5675 $ this ->driver ->query ( 'SET FOREIGN_KEY_CHECKS=@BACKUP_FOREIGN_KEY_CHECKS ' );
You can’t perform that action at this time.
0 commit comments