Skip to content

Commit 2e415ce

Browse files
committed
Set default SQL modes and other options for database import
1 parent 90ddb8d commit 2e415ce

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

features/sqlite-import.feature

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -171,3 +171,23 @@ Feature: WP-CLI SQLite Import Command
171171

172172
And the SQLite database should contain a table named "test_table"
173173
And the "test_table" should contain a row with name "Test Name"
174+
175+
@require-sqlite
176+
Scenario: Import data that expect non-strict SQL mode to be set
177+
Given a SQL dump file named "test_import.sql" with content:
178+
"""
179+
CREATE TABLE test_table (
180+
id INTEGER,
181+
name TEXT NOT NULL,
182+
created_at DATETIME DEFAULT '0000-00-00 00:00:00'
183+
);
184+
INSERT INTO test_table (id) VALUES (1);
185+
"""
186+
When I run `wp sqlite --enable-ast-driver import test_import.sql`
187+
Then STDOUT should contain:
188+
"""
189+
Success: Imported from 'test_import.sql'.
190+
"""
191+
192+
And the SQLite database should contain a table named "test_table"
193+
And the "test_table" should contain a row with name ""

src/Import.php

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,8 +35,26 @@ public function run( $sql_file_path, $args ) {
3535
$is_stdin = '-' === $sql_file_path;
3636
$import_file = $is_stdin ? 'php://stdin' : $sql_file_path;
3737

38+
/*
39+
* Set default SQL mode and other options as per the "mysqldump" command.
40+
*
41+
* This ensures that backups that don't specify SQL modes or other options
42+
* will be imported successfully. Backups that explicitly set any of these
43+
* options will override the default values.
44+
*
45+
* See also WP-CLI's "db import" command SQL mode handling:
46+
* https://github.com/wp-cli/db-command/blob/abeefa5a6c472f12716c5fa5c5a7394d3d0b1ef2/src/DB_Command.php#L823
47+
*/
48+
$this->driver->query( "SET @BACKUP_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO'" );
49+
$this->driver->query( 'SET @BACKUP_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0' );
50+
$this->driver->query( 'SET @BACKUP_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0' );
51+
3852
$this->execute_statements( $import_file );
3953

54+
$this->driver->query( 'SET SQL_MODE=@BACKUP_SQL_MODE' );
55+
$this->driver->query( 'SET UNIQUE_CHECKS=@BACKUP_UNIQUE_CHECKS' );
56+
$this->driver->query( 'SET FOREIGN_KEY_CHECKS=@BACKUP_FOREIGN_KEY_CHECKS' );
57+
4058
$imported_from = $is_stdin ? 'STDIN' : $sql_file_path;
4159
WP_CLI::success( sprintf( "Imported from '%s'.", $imported_from ) );
4260
}

0 commit comments

Comments
 (0)