From 2e415ce21ee3f600d1799b2f074ba45564cea7ce Mon Sep 17 00:00:00 2001 From: Jan Jakes Date: Fri, 31 Oct 2025 10:37:36 +0100 Subject: [PATCH] Set default SQL modes and other options for database import --- features/sqlite-import.feature | 20 ++++++++++++++++++++ src/Import.php | 18 ++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/features/sqlite-import.feature b/features/sqlite-import.feature index 75a4365..060b5b6 100644 --- a/features/sqlite-import.feature +++ b/features/sqlite-import.feature @@ -171,3 +171,23 @@ Feature: WP-CLI SQLite Import Command And the SQLite database should contain a table named "test_table" And the "test_table" should contain a row with name "Test Name" + + @require-sqlite + Scenario: Import data that expect non-strict SQL mode to be set + Given a SQL dump file named "test_import.sql" with content: + """ + CREATE TABLE test_table ( + id INTEGER, + name TEXT NOT NULL, + created_at DATETIME DEFAULT '0000-00-00 00:00:00' + ); + INSERT INTO test_table (id) VALUES (1); + """ + When I run `wp sqlite --enable-ast-driver import test_import.sql` + Then STDOUT should contain: + """ + Success: Imported from 'test_import.sql'. + """ + + And the SQLite database should contain a table named "test_table" + And the "test_table" should contain a row with name "" diff --git a/src/Import.php b/src/Import.php index e2e8249..892d892 100644 --- a/src/Import.php +++ b/src/Import.php @@ -35,8 +35,26 @@ public function run( $sql_file_path, $args ) { $is_stdin = '-' === $sql_file_path; $import_file = $is_stdin ? 'php://stdin' : $sql_file_path; + /* + * Set default SQL mode and other options as per the "mysqldump" command. + * + * This ensures that backups that don't specify SQL modes or other options + * will be imported successfully. Backups that explicitly set any of these + * options will override the default values. + * + * See also WP-CLI's "db import" command SQL mode handling: + * https://github.com/wp-cli/db-command/blob/abeefa5a6c472f12716c5fa5c5a7394d3d0b1ef2/src/DB_Command.php#L823 + */ + $this->driver->query( "SET @BACKUP_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO'" ); + $this->driver->query( 'SET @BACKUP_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0' ); + $this->driver->query( 'SET @BACKUP_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0' ); + $this->execute_statements( $import_file ); + $this->driver->query( 'SET SQL_MODE=@BACKUP_SQL_MODE' ); + $this->driver->query( 'SET UNIQUE_CHECKS=@BACKUP_UNIQUE_CHECKS' ); + $this->driver->query( 'SET FOREIGN_KEY_CHECKS=@BACKUP_FOREIGN_KEY_CHECKS' ); + $imported_from = $is_stdin ? 'STDIN' : $sql_file_path; WP_CLI::success( sprintf( "Imported from '%s'.", $imported_from ) ); }