Skip to content

Commit 8b15530

Browse files
committed
Drop the SQL mode probe; run wp db query under server modes
`wp db query`, `wp db import` and the internal `run_query()` adapted the session SQL mode to match WordPress. Building that adaptation opened a second MySQL connection to read `@@SESSION.sql_mode`, and that probe was built without the caller's connection options (`--host`, `--defaults`, SSL/TLS, sockets), so it connected to the wrong server and aborted the command before the real query ran. This is the root cause of #311, and of #237, #278, #288 and #218. - `wp db query` no longer adapts the SQL mode. It runs under the server's own modes, like the `mysql` client, so connection options are honored. This is a behavior change and targets the next major version. - `wp db import` and `run_query()` keep WordPress compatibility, but apply it via the client's `--init-command` on the same connection rather than a probe. This also covers dumps streamed from STDIN (#171). - Add a `--skip-sql-mode-compat` flag to `wp db import` to opt out. The incompatible modes are stripped from `@@SESSION.sql_mode` in a single statement, with each mode comma-wrapped so a substring like `ANSI` cannot corrupt `ANSI_QUOTES`.
1 parent 24ed6d8 commit 8b15530

3 files changed

Lines changed: 160 additions & 115 deletions

File tree

‎features/db-import.feature‎

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -247,3 +247,95 @@ Feature: Import a WordPress database
247247
"""
248248
🍣
249249
"""
250+
251+
# SQLite does not use the MySQL client and has no concept of SQL modes.
252+
@require-mysql-or-mariadb
253+
Scenario: `wp db import` adapts the SQL mode in-band by default
254+
Given a WP install
255+
256+
When I run `wp db export wp_cli_test.sql`
257+
Then the wp_cli_test.sql file should exist
258+
259+
# The WordPress-compatibility mode adaptation is applied via the MySQL client's
260+
# --init-command on the same connection, so it is visible in the debug output
261+
# and no separate mode probe runs (which is what used to break with custom
262+
# connection options).
263+
When I try `wp db import wp_cli_test.sql --debug`
264+
Then the return code should be 0
265+
And STDERR should contain:
266+
"""
267+
SET SESSION sql_mode
268+
"""
269+
And STDERR should not contain:
270+
"""
271+
Failed to get current SQL modes
272+
"""
273+
274+
@require-mysql-or-mariadb
275+
Scenario: `wp db import --skip-sql-mode-compat` imports under the server's own SQL modes
276+
Given a WP install
277+
278+
When I run `wp db export wp_cli_test.sql`
279+
Then the wp_cli_test.sql file should exist
280+
281+
When I try `wp db import wp_cli_test.sql --skip-sql-mode-compat --debug`
282+
Then the return code should be 0
283+
And STDERR should not contain:
284+
"""
285+
SET SESSION sql_mode
286+
"""
287+
288+
# Regression test for the WordPress-compatibility behavior. WordPress schema
289+
# declares datetime columns as `DEFAULT '0000-00-00 00:00:00'`, so real dumps
290+
# carry zero-date values. On servers whose default SQL mode includes
291+
# NO_ZERO_DATE/STRICT_TRANS_TABLES (MySQL 5.7+/8.0), a raw dump without its own
292+
# SQL_MODE header would fail to import with "Invalid default value". `wp db
293+
# import` must strip those modes for the session so the import succeeds.
294+
@require-mysql-or-mariadb
295+
Scenario: `wp db import` loads a dump containing legacy zero-date values
296+
Given a WP install
297+
And a zerodate.sql file:
298+
"""
299+
CREATE TABLE `wp_cli_zerodate` (
300+
`id` int NOT NULL,
301+
`d` datetime NOT NULL DEFAULT '0000-00-00 00:00:00'
302+
);
303+
INSERT INTO `wp_cli_zerodate` (`id`, `d`) VALUES (1, '0000-00-00 00:00:00');
304+
"""
305+
306+
When I run `wp db import zerodate.sql`
307+
Then STDOUT should contain:
308+
"""
309+
Success: Imported from 'zerodate.sql'.
310+
"""
311+
312+
When I run `wp db query 'SELECT COUNT(*) FROM wp_cli_zerodate;' --skip-column-names`
313+
Then STDOUT should contain:
314+
"""
315+
1
316+
"""
317+
318+
# Regression test for https://github.com/wp-cli/db-command/issues/171
319+
# A dump streamed from STDIN must get the same WordPress SQL-mode compatibility
320+
# as a file import. This is now handled via --init-command, which applies on the
321+
# STDIN connection too (the previous prepend only covered file imports).
322+
@require-mysql-or-mariadb
323+
Scenario: `wp db import -` from STDIN loads a dump containing legacy zero-date values
324+
Given a WP install
325+
And a zerodate_stdin.sql file:
326+
"""
327+
CREATE TABLE wp_cli_zerodate_stdin (id int NOT NULL, d datetime NOT NULL DEFAULT '0000-00-00 00:00:00');
328+
INSERT INTO wp_cli_zerodate_stdin (id, d) VALUES (1, '0000-00-00 00:00:00');
329+
"""
330+
331+
When I run `wp db import - < zerodate_stdin.sql`
332+
Then STDOUT should contain:
333+
"""
334+
Success: Imported from 'STDIN'.
335+
"""
336+
337+
When I run `wp db query 'SELECT COUNT(*) FROM wp_cli_zerodate_stdin;' --skip-column-names`
338+
Then STDOUT should contain:
339+
"""
340+
1
341+
"""

‎features/db-query.feature‎

Lines changed: 26 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -91,31 +91,39 @@ Feature: Query the database with WordPress' MySQL config
9191
When I try `wp db query --no-defaults --debug`
9292
Then STDERR should match #Debug \(db\): Running shell command: /([^/]+/)+(mysql|mariadb) --no-defaults --no-auto-rehash#
9393

94-
Scenario: SQL modes do not include any of the modes incompatible with WordPress
94+
Scenario: `wp db query` runs under the server's own SQL modes without a separate mode probe
9595
Given a WP install
9696

97-
When I try `wp db query 'SELECT @@SESSION.sql_mode;' --debug`
98-
Then STDOUT should not contain:
97+
# The previous implementation always opened a second `SELECT @@SESSION.sql_mode`
98+
# connection to decide whether to rewrite the query, then prepended a
99+
# `SET SESSION sql_mode=...` statement. Both are gone: `wp db query` now behaves
100+
# like the `mysql` client and runs under the server's own SQL modes.
101+
When I try `wp db query 'SELECT 1;' --debug`
102+
Then the return code should be 0
103+
And STDERR should not contain:
99104
"""
100-
NO_ZERO_DATE
105+
@@SESSION.sql_mode
101106
"""
102-
And STDOUT should not contain:
107+
And STDERR should not contain:
103108
"""
104-
ONLY_FULL_GROUP_BY
109+
SET SESSION sql_mode
105110
"""
106-
And STDOUT should not contain:
107-
"""
108-
STRICT_TRANS_TABLES
109-
"""
110-
And STDOUT should not contain:
111-
"""
112-
STRICT_ALL_TABLES
113-
"""
114-
And STDOUT should not contain:
111+
112+
# Regression test for https://github.com/wp-cli/db-command/issues/311
113+
# Passing connection options alongside an inline query used to fail, because the
114+
# SQL-mode probe opened a *second* connection that ignored those very options
115+
# (custom --host, --defaults, SSL/TLS, sockets, ...) and then aborted the whole
116+
# command with "Failed to get current SQL modes". With the probe removed, the
117+
# inline query runs directly under the given options.
118+
Scenario: `wp db query` with an inline query and connection options does not trigger a failing mode probe
119+
Given a WP install
120+
121+
When I try `wp db query 'SELECT 1;' --defaults --debug`
122+
Then STDERR should not contain:
115123
"""
116-
TRADITIONAL
124+
Failed to get current SQL modes
117125
"""
118-
And STDOUT should not contain:
126+
And STDERR should not contain:
119127
"""
120-
ANSI
128+
@@SESSION.sql_mode
121129
"""

‎src/DB_Command.php‎

Lines changed: 42 additions & 97 deletions
Original file line numberDiff line numberDiff line change
@@ -606,11 +606,8 @@ public function query( $args, $assoc_args ) {
606606
$assoc_args['execute'] = $args[0];
607607
}
608608

609-
if ( isset( $assoc_args['execute'] ) ) {
610-
// Ensure that the SQL mode is compatible with WPDB.
611-
$assoc_args['execute'] = $this->get_sql_mode_query( $assoc_args ) . $assoc_args['execute'];
612-
}
613-
609+
// Note: `wp db query` intentionally runs under the server's own SQL modes,
610+
// like the `mysql` client itself. No SQL-mode adaptation is applied here.
614611
$is_row_modifying_query = isset( $assoc_args['execute'] ) && preg_match( '/\b(UPDATE|DELETE|INSERT|REPLACE(?!\s*\()|LOAD DATA)\b/i', $assoc_args['execute'] );
615612

616613
if ( $is_row_modifying_query ) {
@@ -898,6 +895,9 @@ private function command_supports_option( $command, $option ) {
898895
* [--skip-optimization]
899896
* : When using an SQL file, do not include speed optimization such as disabling auto-commit and key checks.
900897
*
898+
* [--skip-sql-mode-compat]
899+
* : Do not adapt the session SQL mode for WordPress compatibility. By default, `wp db import` strips the SQL modes that WordPress Core disables (such as `STRICT_TRANS_TABLES` and `NO_ZERO_DATE`) so that dumps containing legacy values like `0000-00-00` import cleanly. Pass this flag to import under the server's own SQL modes instead.
900+
*
901901
* [--defaults]
902902
* : Loads the environment's MySQL option files. Default behavior is to skip loading them to avoid failures due to misconfiguration.
903903
*
@@ -928,6 +928,14 @@ public function import( $args, $assoc_args ) {
928928
self::get_mysql_args( $assoc_args )
929929
);
930930

931+
// Adapt the session SQL mode to be WordPress-compatible via --init-command,
932+
// so it runs on connect before any SQL is read. This covers both file and
933+
// STDIN imports, and needs no separate probe connection.
934+
$sql_mode_compat = $this->get_sql_mode_compat_statement( $assoc_args );
935+
if ( '' !== $sql_mode_compat && ! isset( $mysql_args['init-command'] ) ) {
936+
$mysql_args['init-command'] = $sql_mode_compat;
937+
}
938+
931939
if ( '-' !== $result_file ) {
932940
if ( ! is_readable( $result_file ) ) {
933941
WP_CLI::error( sprintf( 'Import file missing or not readable: %s', $result_file ) );
@@ -937,8 +945,6 @@ public function import( $args, $assoc_args ) {
937945
? 'SOURCE %s;'
938946
: 'SET autocommit = 0; SET unique_checks = 0; SET foreign_key_checks = 0; SOURCE %s; COMMIT;';
939947

940-
$query = $this->get_sql_mode_query( $assoc_args ) . $query;
941-
942948
$mysql_args['execute'] = sprintf( $query, $result_file );
943949
} else {
944950
$result_file = 'STDIN';
@@ -1926,16 +1932,20 @@ private static function get_create_query() {
19261932
* @param array $assoc_args Optional. Associative array of arguments.
19271933
*/
19281934
protected function run_query( $query, $assoc_args = [] ) {
1929-
// Ensure that the SQL mode is compatible with WPDB.
1930-
$query = $this->get_sql_mode_query( $assoc_args ) . $query;
1931-
19321935
WP_CLI::debug( "Query: {$query}", 'db' );
19331936

19341937
$mysql_args = array_merge(
19351938
self::get_dbuser_dbpass_args( $assoc_args ),
19361939
self::get_mysql_args( $assoc_args )
19371940
);
19381941

1942+
// Adapt the session SQL mode to be WordPress-compatible via --init-command
1943+
// (runs on connect, needs no separate probe connection).
1944+
$sql_mode_compat = $this->get_sql_mode_compat_statement( $assoc_args );
1945+
if ( '' !== $sql_mode_compat && ! isset( $mysql_args['init-command'] ) ) {
1946+
$mysql_args['init-command'] = $sql_mode_compat;
1947+
}
1948+
19391949
self::run(
19401950
sprintf(
19411951
'%s%s --no-auto-rehash',
@@ -2291,103 +2301,38 @@ protected function get_defaults_flag_string( &$assoc_args ) {
22912301
}
22922302

22932303
/**
2294-
* Get the query to change the current SQL mode, and ensure its WordPress compatibility.
2304+
* Get the statement that strips the SQL modes incompatible with WordPress
2305+
* from the current session.
22952306
*
2296-
* If no modes are passed, it will ensure the current MySQL server modes are
2297-
* compatible.
2307+
* This is handed to the MySQL client as `--init-command`, so it runs on the
2308+
* very same connection right after connecting and before any SQL is read.
2309+
* Imports therefore behave like WordPress Core (which disables these modes in
2310+
* `wpdb`), including when the dump is streamed from STDIN. Unlike the previous
2311+
* implementation, no separate connection is opened to first discover the
2312+
* current modes, so it works regardless of the connection options in play
2313+
* (custom `--host`, `--defaults`, SSL/TLS, sockets, ...).
22982314
*
2299-
* Copied and adapted from WordPress Core code.
2315+
* Returns an empty string when the `--skip-sql-mode-compat` flag is set.
23002316
*
2301-
* @see https://github.com/WordPress/wordpress-develop/blob/5.4.0/src/wp-includes/wp-db.php#L817-L880
2317+
* @see https://github.com/WordPress/wordpress-develop/blob/5.4.0/src/wp-includes/wp-db.php#L559-L572
23022318
*
23032319
* @param array $assoc_args The associative argument array passed to the command.
2304-
* @param array $modes Optional. A list of SQL modes to set.
2305-
* @return string Query string to use for setting the SQL modes to a
2306-
* compatible state.
2320+
* @return string SQL statement to run via `--init-command`, or an empty string.
23072321
*/
2308-
protected function get_sql_mode_query( $assoc_args, $modes = [] ) {
2309-
if ( empty( $modes ) ) {
2310-
$modes = $this->get_current_sql_modes( $assoc_args );
2311-
}
2312-
2313-
$modes = array_change_key_case( $modes, CASE_UPPER );
2314-
2315-
$is_mode_adaptation_needed = false;
2316-
foreach ( $modes as $i => $mode ) {
2317-
if ( in_array( $mode, $this->sql_incompatible_modes, true ) ) {
2318-
unset( $modes[ $i ] );
2319-
$is_mode_adaptation_needed = true;
2320-
}
2321-
}
2322-
2323-
if ( ! $is_mode_adaptation_needed ) {
2324-
WP_CLI::debug(
2325-
sprintf(
2326-
'SQL modes look fine: %s',
2327-
json_encode( $modes )
2328-
)
2329-
);
2322+
protected function get_sql_mode_compat_statement( $assoc_args = [] ) {
2323+
if ( Utils\get_flag_value( $assoc_args, 'skip-sql-mode-compat', false ) ) {
23302324
return '';
23312325
}
23322326

2333-
WP_CLI::debug(
2334-
sprintf(
2335-
'SQL mode adaptation is needed: %s => %s',
2336-
json_encode( $this->get_current_sql_modes( $assoc_args ) ),
2337-
json_encode( $modes )
2338-
)
2339-
);
2340-
2341-
$modes_str = implode( ',', $modes );
2342-
2343-
return "SET SESSION sql_mode='{$modes_str}';";
2344-
}
2345-
2346-
/**
2347-
* Get the list of current SQL modes.
2348-
*
2349-
* @param array $assoc_args The associative argument array passed to the command.
2350-
* @return string[] Array of SQL modes.
2351-
*/
2352-
protected function get_current_sql_modes( $assoc_args ) {
2353-
static $modes = null;
2354-
2355-
// Make sure the provided arguments don't interfere with the expected
2356-
// output here.
2357-
$args = [];
2358-
2359-
if ( null === $modes ) {
2360-
$modes = [];
2361-
2362-
list( $stdout, $stderr, $exit_code ) = self::run(
2363-
sprintf(
2364-
'%s%s --no-auto-rehash --batch --skip-column-names',
2365-
Utils\get_mysql_binary_path(),
2366-
$this->get_defaults_flag_string( $assoc_args )
2367-
),
2368-
array_merge( $args, [ 'execute' => 'SELECT @@SESSION.sql_mode' ] ),
2369-
false
2370-
);
2371-
2372-
if ( $exit_code ) {
2373-
WP_CLI::error(
2374-
'Failed to get current SQL modes.'
2375-
. ( ! empty( $stderr ) ? " Reason: {$stderr}" : '' ),
2376-
$exit_code
2377-
);
2378-
}
2379-
2380-
if ( ! empty( $stdout ) ) {
2381-
$lines = preg_split( "/\r\n|\n|\r|,/", $stdout );
2382-
$modes = array_filter(
2383-
array_map(
2384-
'trim',
2385-
$lines ? $lines : []
2386-
)
2387-
);
2388-
}
2327+
// Strip the incompatible modes from the session mode list. Each mode is
2328+
// wrapped in commas so that it only matches as a whole token and never as
2329+
// a substring -- stripping `ANSI` must not turn `ANSI_QUOTES` into
2330+
// `_QUOTES`, for example.
2331+
$expression = "CONCAT( ',', @@SESSION.sql_mode, ',' )";
2332+
foreach ( $this->sql_incompatible_modes as $mode ) {
2333+
$expression = sprintf( "REPLACE( %s, ',%s,', ',' )", $expression, $mode );
23892334
}
23902335

2391-
return $modes;
2336+
return sprintf( "SET SESSION sql_mode = TRIM( BOTH ',' FROM %s )", $expression );
23922337
}
23932338
}

0 commit comments

Comments
 (0)