From 2e544c44542d4c2c93d64d8492b9ab0426b6d3b2 Mon Sep 17 00:00:00 2001
From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com>
Date: Mon, 19 Jan 2026 10:26:33 +0000
Subject: [PATCH 01/15] Initial plan
From 347182e378704123c0ddc3feefb82deb9d4c1111 Mon Sep 17 00:00:00 2001
From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com>
Date: Mon, 19 Jan 2026 13:15:57 +0000
Subject: [PATCH 02/15] Add wp db users create command implementation
Co-authored-by: swissspidy <841956+swissspidy@users.noreply.github.com>
---
composer.json | 4 +-
db-command.php | 1 +
features/db-users.feature | 79 +++++++++++++
phpcs.xml.dist | 1 +
src/DB_Users_Command.php | 228 ++++++++++++++++++++++++++++++++++++++
5 files changed, 312 insertions(+), 1 deletion(-)
create mode 100644 features/db-users.feature
create mode 100644 src/DB_Users_Command.php
diff --git a/composer.json b/composer.json
index e575f01f5..8d78d8529 100644
--- a/composer.json
+++ b/composer.json
@@ -50,7 +50,9 @@
"db search",
"db tables",
"db size",
- "db columns"
+ "db columns",
+ "db users",
+ "db users create"
]
},
"autoload": {
diff --git a/db-command.php b/db-command.php
index d08f55bb9..3af9a7ec0 100644
--- a/db-command.php
+++ b/db-command.php
@@ -10,3 +10,4 @@
}
WP_CLI::add_command( 'db', 'DB_Command' );
+WP_CLI::add_command( 'db users', 'DB_Users_Command' );
diff --git a/features/db-users.feature b/features/db-users.feature
new file mode 100644
index 000000000..06e8d9170
--- /dev/null
+++ b/features/db-users.feature
@@ -0,0 +1,79 @@
+Feature: Manage database users
+
+ Scenario: Create database user without privileges
+ Given an empty directory
+ And WP files
+ And wp-config.php
+
+ When I run `wp db create`
+ Then STDOUT should be:
+ """
+ Success: Database created.
+ """
+
+ When I run `wp db users create testuser localhost --password=testpass123`
+ Then STDOUT should contain:
+ """
+ Success: Database user 'testuser'@'localhost' created.
+ """
+
+ When I run `wp db query "SELECT User, Host FROM mysql.user WHERE User='testuser'"`
+ Then STDOUT should contain:
+ """
+ testuser
+ """
+
+ Scenario: Create database user with privileges
+ Given an empty directory
+ And WP files
+ And wp-config.php
+
+ When I run `wp db create`
+ Then STDOUT should be:
+ """
+ Success: Database created.
+ """
+
+ When I run `wp db users create appuser localhost --password=secret123 --grant-privileges`
+ Then STDOUT should contain:
+ """
+ created with privileges on database
+ """
+ And STDOUT should contain:
+ """
+ appuser
+ """
+
+ Scenario: Create database user with custom host
+ Given an empty directory
+ And WP files
+ And wp-config.php
+
+ When I run `wp db create`
+ Then STDOUT should be:
+ """
+ Success: Database created.
+ """
+
+ When I run `wp db users create remoteuser '%' --password=remote123`
+ Then STDOUT should contain:
+ """
+ Success: Database user 'remoteuser'@'%' created.
+ """
+
+ Scenario: Create database user with no password
+ Given an empty directory
+ And WP files
+ And wp-config.php
+
+ When I run `wp db create`
+ Then STDOUT should be:
+ """
+ Success: Database created.
+ """
+
+ When I run `wp db users create nopassuser localhost`
+ Then STDOUT should contain:
+ """
+ Success: Database user 'nopassuser'@'localhost' created.
+ """
diff --git a/phpcs.xml.dist b/phpcs.xml.dist
index c39cec40f..6ab493d8a 100644
--- a/phpcs.xml.dist
+++ b/phpcs.xml.dist
@@ -54,6 +54,7 @@
*/src/DB_Command\.php$
+ */src/DB_Users_Command\.php$
/tests/phpstan/scan-files
diff --git a/src/DB_Users_Command.php b/src/DB_Users_Command.php
new file mode 100644
index 000000000..fb158223e
--- /dev/null
+++ b/src/DB_Users_Command.php
@@ -0,0 +1,228 @@
+
+ * : MySQL username for the new user account.
+ *
+ * []
+ * : MySQL host for the new user account.
+ * ---
+ * default: localhost
+ * ---
+ *
+ * [--password=]
+ * : Password for the new user account. If not provided, MySQL will use no password.
+ *
+ * [--grant-privileges]
+ * : Grant full privileges on the current database to the new user.
+ *
+ * [--dbuser=]
+ * : Username to connect as (privileged user). Defaults to DB_USER.
+ *
+ * [--dbpass=]
+ * : Password to connect with (privileged user). Defaults to DB_PASSWORD.
+ *
+ * [--defaults]
+ * : Loads the environment's MySQL option files. Default behavior is to skip loading them to avoid failures due to misconfiguration.
+ *
+ * ## EXAMPLES
+ *
+ * # Create a user without privileges.
+ * $ wp db users create myuser localhost --password=mypass
+ * Success: Database user 'myuser'@'localhost' created.
+ *
+ * # Create a user with full privileges on the current database.
+ * $ wp db users create appuser localhost --password=secret123 --grant-privileges
+ * Success: Database user 'appuser'@'localhost' created with privileges on database 'wp_database'.
+ */
+ public function create( $args, $assoc_args ) {
+ list( $username, $host ) = array_pad( $args, 2, 'localhost' );
+
+ $password = Utils\get_flag_value( $assoc_args, 'password', '' );
+ $grant_privileges = Utils\get_flag_value( $assoc_args, 'grant-privileges', false );
+
+ // Escape identifiers for SQL
+ $username_escaped = $this->esc_sql_ident( $username );
+ $host_escaped = $this->esc_sql_ident( $host );
+ $user_identifier = "{$username_escaped}@{$host_escaped}";
+
+ // Create user
+ $create_query = "CREATE USER {$user_identifier}";
+ if ( ! empty( $password ) ) {
+ $password_escaped = $this->esc_sql_string( $password );
+ $create_query .= " IDENTIFIED BY {$password_escaped}";
+ }
+ $create_query .= ';';
+
+ $this->run_query( $create_query, $assoc_args );
+
+ // Grant privileges if requested
+ if ( $grant_privileges ) {
+ $database = DB_NAME;
+ $database_escaped = $this->esc_sql_ident( $database );
+ $grant_query = "GRANT ALL PRIVILEGES ON {$database_escaped}.* TO {$user_identifier};";
+ $this->run_query( $grant_query, $assoc_args );
+
+ // Flush privileges
+ $this->run_query( 'FLUSH PRIVILEGES;', $assoc_args );
+
+ WP_CLI::success( "Database user '{$username}'@'{$host}' created with privileges on database '{$database}'." );
+ } else {
+ WP_CLI::success( "Database user '{$username}'@'{$host}' created." );
+ }
+ }
+
+ /**
+ * Run a single query via the 'mysql' binary.
+ *
+ * @param string $query Query to execute.
+ * @param array $assoc_args Optional. Associative array of arguments.
+ */
+ private function run_query( $query, $assoc_args = [] ) {
+ WP_CLI::debug( "Query: {$query}", 'db' );
+
+ $mysql_args = array_merge(
+ $this->get_dbuser_dbpass_args( $assoc_args ),
+ $this->get_mysql_args( $assoc_args )
+ );
+
+ $this->run(
+ sprintf(
+ 'mysql%s --no-auto-rehash',
+ $this->get_defaults_flag_string( $assoc_args )
+ ),
+ array_merge( [ 'execute' => $query ], $mysql_args )
+ );
+ }
+
+ /**
+ * Run a MySQL command.
+ *
+ * @param string $cmd Command to run.
+ * @param array $assoc_args Optional. Associative array of arguments to use.
+ *
+ * @return array {
+ * Associative array containing STDOUT and STDERR output.
+ *
+ * @type string $stdout Output that was sent to STDOUT.
+ * @type string $stderr Output that was sent to STDERR.
+ * @type int $exit_code Exit code of the process.
+ * }
+ */
+ private function run( $cmd, $assoc_args = [] ) {
+ $required = [
+ 'host' => DB_HOST,
+ 'user' => DB_USER,
+ 'pass' => DB_PASSWORD,
+ ];
+
+ if ( ! isset( $assoc_args['default-character-set'] )
+ && defined( 'DB_CHARSET' ) && constant( 'DB_CHARSET' ) ) {
+ $required['default-character-set'] = constant( 'DB_CHARSET' );
+ }
+
+ // Using 'dbuser' as option name to workaround clash with WP-CLI's global WP 'user' parameter.
+ if ( isset( $assoc_args['dbuser'] ) ) {
+ $required['user'] = $assoc_args['dbuser'];
+ unset( $assoc_args['dbuser'] );
+ }
+ if ( isset( $assoc_args['dbpass'] ) ) {
+ $required['pass'] = $assoc_args['dbpass'];
+ unset( $assoc_args['dbpass'], $assoc_args['password'] );
+ }
+
+ $final_args = array_merge( $required, $assoc_args );
+
+ return Utils\run_mysql_command( $cmd, $final_args, null, true, false );
+ }
+
+ /**
+ * Helper to pluck 'dbuser' and 'dbpass' from associative args array.
+ *
+ * @param array $assoc_args Associative args array.
+ * @return array Array with 'dbuser' and 'dbpass' set if in passed-in associative args array.
+ */
+ private function get_dbuser_dbpass_args( $assoc_args ) {
+ $mysql_args = [];
+ $dbuser = Utils\get_flag_value( $assoc_args, 'dbuser' );
+ if ( null !== $dbuser ) {
+ $mysql_args['dbuser'] = $dbuser;
+ }
+ $dbpass = Utils\get_flag_value( $assoc_args, 'dbpass' );
+ if ( null !== $dbpass ) {
+ $mysql_args['dbpass'] = $dbpass;
+ }
+ return $mysql_args;
+ }
+
+ /**
+ * Gets the MySQL args from the associative args array.
+ *
+ * @param array $assoc_args Associative args array.
+ * @return array MySQL args.
+ */
+ private function get_mysql_args( $assoc_args ) {
+ $mysql_args = [];
+
+ if ( isset( $assoc_args['host'] ) ) {
+ $mysql_args['host'] = $assoc_args['host'];
+ }
+
+ return $mysql_args;
+ }
+
+ /**
+ * Gets the defaults flag string.
+ *
+ * @param array $assoc_args Associative args array.
+ * @return string Defaults flag string.
+ */
+ private function get_defaults_flag_string( $assoc_args ) {
+ $defaults = Utils\get_flag_value( $assoc_args, 'defaults', false );
+ return $defaults ? '' : ' --no-defaults';
+ }
+
+ /**
+ * Escapes a string for use in a SQL query.
+ *
+ * @param string $value String to escape.
+ * @return string Escaped string.
+ */
+ private function esc_sql_string( $value ) {
+ // Use single quotes and escape single quotes by doubling them.
+ return "'" . str_replace( "'", "''", $value ) . "'";
+ }
+
+ /**
+ * Escapes (backticks) MySQL identifiers (aka schema object names).
+ *
+ * @param string $ident A single identifier.
+ * @return string An escaped string.
+ */
+ private function esc_sql_ident( $ident ) {
+ // Escape any backticks in the identifier by doubling.
+ return '`' . str_replace( '`', '``', $ident ) . '`';
+ }
+}
From 891f7139ece4eda192c03c08259945772465b9c2 Mon Sep 17 00:00:00 2001
From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com>
Date: Mon, 19 Jan 2026 13:36:22 +0000
Subject: [PATCH 03/15] Refactor DB_Users_Command to extend DB_Command and
improve security
Co-authored-by: swissspidy <841956+swissspidy@users.noreply.github.com>
---
src/DB_Users_Command.php | 121 +++++----------------------------------
test-output.txt | 45 +++++++++++++++
2 files changed, 58 insertions(+), 108 deletions(-)
create mode 100644 test-output.txt
diff --git a/src/DB_Users_Command.php b/src/DB_Users_Command.php
index fb158223e..2d979fb5c 100644
--- a/src/DB_Users_Command.php
+++ b/src/DB_Users_Command.php
@@ -13,7 +13,7 @@
*
* @when after_wp_config_load
*/
-class DB_Users_Command extends WP_CLI_Command {
+class DB_Users_Command extends DB_Command {
/**
* Creates a new database user with optional privileges.
@@ -76,17 +76,17 @@ public function create( $args, $assoc_args ) {
}
$create_query .= ';';
- $this->run_query( $create_query, $assoc_args );
+ $this->run_user_query( $create_query, $assoc_args );
// Grant privileges if requested
if ( $grant_privileges ) {
$database = DB_NAME;
$database_escaped = $this->esc_sql_ident( $database );
$grant_query = "GRANT ALL PRIVILEGES ON {$database_escaped}.* TO {$user_identifier};";
- $this->run_query( $grant_query, $assoc_args );
+ $this->run_user_query( $grant_query, $assoc_args );
// Flush privileges
- $this->run_query( 'FLUSH PRIVILEGES;', $assoc_args );
+ $this->run_user_query( 'FLUSH PRIVILEGES;', $assoc_args );
WP_CLI::success( "Database user '{$username}'@'{$host}' created with privileges on database '{$database}'." );
} else {
@@ -97,111 +97,14 @@ public function create( $args, $assoc_args ) {
/**
* Run a single query via the 'mysql' binary.
*
+ * This method adds SQL mode compatibility and delegates to the parent class.
+ *
* @param string $query Query to execute.
* @param array $assoc_args Optional. Associative array of arguments.
*/
- private function run_query( $query, $assoc_args = [] ) {
- WP_CLI::debug( "Query: {$query}", 'db' );
-
- $mysql_args = array_merge(
- $this->get_dbuser_dbpass_args( $assoc_args ),
- $this->get_mysql_args( $assoc_args )
- );
-
- $this->run(
- sprintf(
- 'mysql%s --no-auto-rehash',
- $this->get_defaults_flag_string( $assoc_args )
- ),
- array_merge( [ 'execute' => $query ], $mysql_args )
- );
- }
-
- /**
- * Run a MySQL command.
- *
- * @param string $cmd Command to run.
- * @param array $assoc_args Optional. Associative array of arguments to use.
- *
- * @return array {
- * Associative array containing STDOUT and STDERR output.
- *
- * @type string $stdout Output that was sent to STDOUT.
- * @type string $stderr Output that was sent to STDERR.
- * @type int $exit_code Exit code of the process.
- * }
- */
- private function run( $cmd, $assoc_args = [] ) {
- $required = [
- 'host' => DB_HOST,
- 'user' => DB_USER,
- 'pass' => DB_PASSWORD,
- ];
-
- if ( ! isset( $assoc_args['default-character-set'] )
- && defined( 'DB_CHARSET' ) && constant( 'DB_CHARSET' ) ) {
- $required['default-character-set'] = constant( 'DB_CHARSET' );
- }
-
- // Using 'dbuser' as option name to workaround clash with WP-CLI's global WP 'user' parameter.
- if ( isset( $assoc_args['dbuser'] ) ) {
- $required['user'] = $assoc_args['dbuser'];
- unset( $assoc_args['dbuser'] );
- }
- if ( isset( $assoc_args['dbpass'] ) ) {
- $required['pass'] = $assoc_args['dbpass'];
- unset( $assoc_args['dbpass'], $assoc_args['password'] );
- }
-
- $final_args = array_merge( $required, $assoc_args );
-
- return Utils\run_mysql_command( $cmd, $final_args, null, true, false );
- }
-
- /**
- * Helper to pluck 'dbuser' and 'dbpass' from associative args array.
- *
- * @param array $assoc_args Associative args array.
- * @return array Array with 'dbuser' and 'dbpass' set if in passed-in associative args array.
- */
- private function get_dbuser_dbpass_args( $assoc_args ) {
- $mysql_args = [];
- $dbuser = Utils\get_flag_value( $assoc_args, 'dbuser' );
- if ( null !== $dbuser ) {
- $mysql_args['dbuser'] = $dbuser;
- }
- $dbpass = Utils\get_flag_value( $assoc_args, 'dbpass' );
- if ( null !== $dbpass ) {
- $mysql_args['dbpass'] = $dbpass;
- }
- return $mysql_args;
- }
-
- /**
- * Gets the MySQL args from the associative args array.
- *
- * @param array $assoc_args Associative args array.
- * @return array MySQL args.
- */
- private function get_mysql_args( $assoc_args ) {
- $mysql_args = [];
-
- if ( isset( $assoc_args['host'] ) ) {
- $mysql_args['host'] = $assoc_args['host'];
- }
-
- return $mysql_args;
- }
-
- /**
- * Gets the defaults flag string.
- *
- * @param array $assoc_args Associative args array.
- * @return string Defaults flag string.
- */
- private function get_defaults_flag_string( $assoc_args ) {
- $defaults = Utils\get_flag_value( $assoc_args, 'defaults', false );
- return $defaults ? '' : ' --no-defaults';
+ private function run_user_query( $query, $assoc_args = [] ) {
+ // Use parent class's run_query method which handles SQL mode compatibility.
+ parent::run_query( $query, $assoc_args );
}
/**
@@ -211,8 +114,10 @@ private function get_defaults_flag_string( $assoc_args ) {
* @return string Escaped string.
*/
private function esc_sql_string( $value ) {
- // Use single quotes and escape single quotes by doubling them.
- return "'" . str_replace( "'", "''", $value ) . "'";
+ // Escape backslashes first, then single quotes.
+ $value = str_replace( '\\', '\\\\', $value );
+ $value = str_replace( "'", "''", $value );
+ return "'" . $value . "'";
}
/**
diff --git a/test-output.txt b/test-output.txt
new file mode 100644
index 000000000..cef192a40
--- /dev/null
+++ b/test-output.txt
@@ -0,0 +1,45 @@
+WP_CLI_TEST_DBTYPE is set to 'sqlite', skipping database check.
+.F-------.F------.F-----.F-----
+
+--- Failed steps:
+
+001 Scenario: Create database user without privileges # features/db-users.feature:3
+ And WP files # features/db-users.feature:5
+ $ curl -sSfL 'https://downloads.wordpress.org/plugin/sqlite-database-integration.zip' > '/tmp/wp-cli-test-sqlite-integration-cache/sqlite-database-integration.zip'
+
+ curl: (6) Could not resolve host: downloads.wordpress.org
+ cwd:
+ run time: 0.0067920684814453
+ exit status: 6 (RuntimeException)
+
+002 Scenario: Create database user with privileges # features/db-users.feature:26
+ And WP files # features/db-users.feature:28
+ $ cp -r '/tmp/wp-cli-test-core-download-cache'/* '/tmp/wp-cli-test-run--696e307f102bc5.10488262/'
+
+ cp: cannot stat '/tmp/wp-cli-test-core-download-cache/*': No such file or directory
+ cwd:
+ run time: 0.0016000270843506
+ exit status: 1 (RuntimeException)
+
+003 Scenario: Create database user with custom host # features/db-users.feature:47
+ And WP files # features/db-users.feature:49
+ $ cp -r '/tmp/wp-cli-test-core-download-cache'/* '/tmp/wp-cli-test-run--696e307f10e798.58842661/'
+
+ cp: cannot stat '/tmp/wp-cli-test-core-download-cache/*': No such file or directory
+ cwd:
+ run time: 0.001478910446167
+ exit status: 1 (RuntimeException)
+
+004 Scenario: Create database user with no password # features/db-users.feature:64
+ And WP files # features/db-users.feature:66
+ $ cp -r '/tmp/wp-cli-test-core-download-cache'/* '/tmp/wp-cli-test-run--696e307f118931.57377979/'
+
+ cp: cannot stat '/tmp/wp-cli-test-core-download-cache/*': No such file or directory
+ cwd:
+ run time: 0.0014328956604004
+ exit status: 1 (RuntimeException)
+
+4 scenarios (4 failed)
+31 steps (4 passed, 4 failed, 23 skipped)
+0m0.21s (12.58Mb)
+Script run-behat-tests handling the behat event returned with error code 1
From 7f2d7d9b210fbf6b127d74d7bf8ea6d46dac2605 Mon Sep 17 00:00:00 2001
From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com>
Date: Mon, 19 Jan 2026 13:43:43 +0000
Subject: [PATCH 04/15] Simplify code by calling parent::run_query directly and
remove test-output.txt
Co-authored-by: swissspidy <841956+swissspidy@users.noreply.github.com>
---
src/DB_Users_Command.php | 22 ++++++--------------
test-output.txt | 45 ----------------------------------------
2 files changed, 6 insertions(+), 61 deletions(-)
delete mode 100644 test-output.txt
diff --git a/src/DB_Users_Command.php b/src/DB_Users_Command.php
index 2d979fb5c..f6c6737cb 100644
--- a/src/DB_Users_Command.php
+++ b/src/DB_Users_Command.php
@@ -76,17 +76,17 @@ public function create( $args, $assoc_args ) {
}
$create_query .= ';';
- $this->run_user_query( $create_query, $assoc_args );
+ parent::run_query( $create_query, $assoc_args );
// Grant privileges if requested
if ( $grant_privileges ) {
$database = DB_NAME;
$database_escaped = $this->esc_sql_ident( $database );
$grant_query = "GRANT ALL PRIVILEGES ON {$database_escaped}.* TO {$user_identifier};";
- $this->run_user_query( $grant_query, $assoc_args );
+ parent::run_query( $grant_query, $assoc_args );
// Flush privileges
- $this->run_user_query( 'FLUSH PRIVILEGES;', $assoc_args );
+ parent::run_query( 'FLUSH PRIVILEGES;', $assoc_args );
WP_CLI::success( "Database user '{$username}'@'{$host}' created with privileges on database '{$database}'." );
} else {
@@ -94,19 +94,6 @@ public function create( $args, $assoc_args ) {
}
}
- /**
- * Run a single query via the 'mysql' binary.
- *
- * This method adds SQL mode compatibility and delegates to the parent class.
- *
- * @param string $query Query to execute.
- * @param array $assoc_args Optional. Associative array of arguments.
- */
- private function run_user_query( $query, $assoc_args = [] ) {
- // Use parent class's run_query method which handles SQL mode compatibility.
- parent::run_query( $query, $assoc_args );
- }
-
/**
* Escapes a string for use in a SQL query.
*
@@ -123,6 +110,9 @@ private function esc_sql_string( $value ) {
/**
* Escapes (backticks) MySQL identifiers (aka schema object names).
*
+ * Note: This duplicates functionality from parent DB_Command::esc_sql_ident()
+ * which is private static and cannot be accessed from child classes.
+ *
* @param string $ident A single identifier.
* @return string An escaped string.
*/
diff --git a/test-output.txt b/test-output.txt
deleted file mode 100644
index cef192a40..000000000
--- a/test-output.txt
+++ /dev/null
@@ -1,45 +0,0 @@
-WP_CLI_TEST_DBTYPE is set to 'sqlite', skipping database check.
-.F-------.F------.F-----.F-----
-
---- Failed steps:
-
-001 Scenario: Create database user without privileges # features/db-users.feature:3
- And WP files # features/db-users.feature:5
- $ curl -sSfL 'https://downloads.wordpress.org/plugin/sqlite-database-integration.zip' > '/tmp/wp-cli-test-sqlite-integration-cache/sqlite-database-integration.zip'
-
- curl: (6) Could not resolve host: downloads.wordpress.org
- cwd:
- run time: 0.0067920684814453
- exit status: 6 (RuntimeException)
-
-002 Scenario: Create database user with privileges # features/db-users.feature:26
- And WP files # features/db-users.feature:28
- $ cp -r '/tmp/wp-cli-test-core-download-cache'/* '/tmp/wp-cli-test-run--696e307f102bc5.10488262/'
-
- cp: cannot stat '/tmp/wp-cli-test-core-download-cache/*': No such file or directory
- cwd:
- run time: 0.0016000270843506
- exit status: 1 (RuntimeException)
-
-003 Scenario: Create database user with custom host # features/db-users.feature:47
- And WP files # features/db-users.feature:49
- $ cp -r '/tmp/wp-cli-test-core-download-cache'/* '/tmp/wp-cli-test-run--696e307f10e798.58842661/'
-
- cp: cannot stat '/tmp/wp-cli-test-core-download-cache/*': No such file or directory
- cwd:
- run time: 0.001478910446167
- exit status: 1 (RuntimeException)
-
-004 Scenario: Create database user with no password # features/db-users.feature:64
- And WP files # features/db-users.feature:66
- $ cp -r '/tmp/wp-cli-test-core-download-cache'/* '/tmp/wp-cli-test-run--696e307f118931.57377979/'
-
- cp: cannot stat '/tmp/wp-cli-test-core-download-cache/*': No such file or directory
- cwd:
- run time: 0.0014328956604004
- exit status: 1 (RuntimeException)
-
-4 scenarios (4 failed)
-31 steps (4 passed, 4 failed, 23 skipped)
-0m0.21s (12.58Mb)
-Script run-behat-tests handling the behat event returned with error code 1
From 84b425ff7caca7a1ade1fd56fbb67daa0758a38c Mon Sep 17 00:00:00 2001
From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com>
Date: Mon, 19 Jan 2026 15:15:02 +0000
Subject: [PATCH 05/15] Make esc_sql_ident protected in parent class and call
it statically
Co-authored-by: swissspidy <841956+swissspidy@users.noreply.github.com>
---
src/DB_Command.php | 2 +-
src/DB_Users_Command.php | 27 ++++++++-------------------
2 files changed, 9 insertions(+), 20 deletions(-)
diff --git a/src/DB_Command.php b/src/DB_Command.php
index 06781ceed..25992fd30 100644
--- a/src/DB_Command.php
+++ b/src/DB_Command.php
@@ -1923,7 +1923,7 @@ private static function is_text_col( $type ) {
*
* @phpstan-return ($idents is string ? string : array)
*/
- private static function esc_sql_ident( $idents ) {
+ protected static function esc_sql_ident( $idents ) {
$backtick = static function ( $v ) {
// Escape any backticks in the identifier by doubling.
return '`' . str_replace( '`', '``', $v ) . '`';
diff --git a/src/DB_Users_Command.php b/src/DB_Users_Command.php
index f6c6737cb..7699fc764 100644
--- a/src/DB_Users_Command.php
+++ b/src/DB_Users_Command.php
@@ -64,9 +64,11 @@ public function create( $args, $assoc_args ) {
$grant_privileges = Utils\get_flag_value( $assoc_args, 'grant-privileges', false );
// Escape identifiers for SQL
- $username_escaped = $this->esc_sql_ident( $username );
- $host_escaped = $this->esc_sql_ident( $host );
- $user_identifier = "{$username_escaped}@{$host_escaped}";
+ $username_escaped = self::esc_sql_ident( $username );
+ $host_escaped = self::esc_sql_ident( $host );
+ assert( is_string( $username_escaped ) );
+ assert( is_string( $host_escaped ) );
+ $user_identifier = "{$username_escaped}@{$host_escaped}";
// Create user
$create_query = "CREATE USER {$user_identifier}";
@@ -81,8 +83,9 @@ public function create( $args, $assoc_args ) {
// Grant privileges if requested
if ( $grant_privileges ) {
$database = DB_NAME;
- $database_escaped = $this->esc_sql_ident( $database );
- $grant_query = "GRANT ALL PRIVILEGES ON {$database_escaped}.* TO {$user_identifier};";
+ $database_escaped = self::esc_sql_ident( $database );
+ assert( is_string( $database_escaped ) );
+ $grant_query = "GRANT ALL PRIVILEGES ON {$database_escaped}.* TO {$user_identifier};";
parent::run_query( $grant_query, $assoc_args );
// Flush privileges
@@ -106,18 +109,4 @@ private function esc_sql_string( $value ) {
$value = str_replace( "'", "''", $value );
return "'" . $value . "'";
}
-
- /**
- * Escapes (backticks) MySQL identifiers (aka schema object names).
- *
- * Note: This duplicates functionality from parent DB_Command::esc_sql_ident()
- * which is private static and cannot be accessed from child classes.
- *
- * @param string $ident A single identifier.
- * @return string An escaped string.
- */
- private function esc_sql_ident( $ident ) {
- // Escape any backticks in the identifier by doubling.
- return '`' . str_replace( '`', '``', $ident ) . '`';
- }
}
From 421a9a4ef08a7dc76f4777625de6734953faab55 Mon Sep 17 00:00:00 2001
From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com>
Date: Mon, 19 Jan 2026 16:24:24 +0000
Subject: [PATCH 06/15] Remove assert calls and improve SQL string escaping for
security
Co-authored-by: swissspidy <841956+swissspidy@users.noreply.github.com>
---
src/DB_Users_Command.php | 20 +++++++++++++-------
1 file changed, 13 insertions(+), 7 deletions(-)
diff --git a/src/DB_Users_Command.php b/src/DB_Users_Command.php
index 7699fc764..f5fad023a 100644
--- a/src/DB_Users_Command.php
+++ b/src/DB_Users_Command.php
@@ -66,8 +66,8 @@ public function create( $args, $assoc_args ) {
// Escape identifiers for SQL
$username_escaped = self::esc_sql_ident( $username );
$host_escaped = self::esc_sql_ident( $host );
- assert( is_string( $username_escaped ) );
- assert( is_string( $host_escaped ) );
+ /** @var string $username_escaped */
+ /** @var string $host_escaped */
$user_identifier = "{$username_escaped}@{$host_escaped}";
// Create user
@@ -84,7 +84,7 @@ public function create( $args, $assoc_args ) {
if ( $grant_privileges ) {
$database = DB_NAME;
$database_escaped = self::esc_sql_ident( $database );
- assert( is_string( $database_escaped ) );
+ /** @var string $database_escaped */
$grant_query = "GRANT ALL PRIVILEGES ON {$database_escaped}.* TO {$user_identifier};";
parent::run_query( $grant_query, $assoc_args );
@@ -100,13 +100,19 @@ public function create( $args, $assoc_args ) {
/**
* Escapes a string for use in a SQL query.
*
+ * Follows MySQL's documented string literal escaping rules.
+ * See https://dev.mysql.com/doc/refman/en/string-literals.html
+ *
* @param string $value String to escape.
- * @return string Escaped string.
+ * @return string Escaped string, wrapped in single quotes.
*/
private function esc_sql_string( $value ) {
- // Escape backslashes first, then single quotes.
- $value = str_replace( '\\', '\\\\', $value );
- $value = str_replace( "'", "''", $value );
+ // Escape special characters according to MySQL string literal rules.
+ $value = str_replace(
+ [ '\\', "\x00", "\n", "\r", "'", '"', "\x1a" ],
+ [ '\\\\', "\\0", "\\n", "\\r", "\\'", '\\"', '\\Z' ],
+ $value
+ );
return "'" . $value . "'";
}
}
From c57a6c6065e40d07fc07c2818d124264ccdbb1e4 Mon Sep 17 00:00:00 2001
From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com>
Date: Wed, 11 Mar 2026 17:15:51 +0000
Subject: [PATCH 07/15] Remove redundant @var annotations and use explicit type
casting
Co-authored-by: swissspidy <841956+swissspidy@users.noreply.github.com>
---
src/DB_Users_Command.php | 15 +++++++--------
1 file changed, 7 insertions(+), 8 deletions(-)
diff --git a/src/DB_Users_Command.php b/src/DB_Users_Command.php
index f5fad023a..c6b0d3d4d 100644
--- a/src/DB_Users_Command.php
+++ b/src/DB_Users_Command.php
@@ -64,11 +64,11 @@ public function create( $args, $assoc_args ) {
$grant_privileges = Utils\get_flag_value( $assoc_args, 'grant-privileges', false );
// Escape identifiers for SQL
- $username_escaped = self::esc_sql_ident( $username );
- $host_escaped = self::esc_sql_ident( $host );
- /** @var string $username_escaped */
- /** @var string $host_escaped */
- $user_identifier = "{$username_escaped}@{$host_escaped}";
+ // @phpstan-ignore cast.string (PHPStan doesn't infer conditional return type from parent method)
+ $username_escaped = (string) self::esc_sql_ident( $username );
+ // @phpstan-ignore cast.string (PHPStan doesn't infer conditional return type from parent method)
+ $host_escaped = (string) self::esc_sql_ident( $host );
+ $user_identifier = $username_escaped . '@' . $host_escaped;
// Create user
$create_query = "CREATE USER {$user_identifier}";
@@ -83,9 +83,8 @@ public function create( $args, $assoc_args ) {
// Grant privileges if requested
if ( $grant_privileges ) {
$database = DB_NAME;
- $database_escaped = self::esc_sql_ident( $database );
- /** @var string $database_escaped */
- $grant_query = "GRANT ALL PRIVILEGES ON {$database_escaped}.* TO {$user_identifier};";
+ $database_escaped = (string) self::esc_sql_ident( $database );
+ $grant_query = 'GRANT ALL PRIVILEGES ON ' . $database_escaped . '.* TO ' . $user_identifier . ';';
parent::run_query( $grant_query, $assoc_args );
// Flush privileges
From 36fb7e1f5a1bd612bac4a04f3c1fd79b63bcd91c Mon Sep 17 00:00:00 2001
From: Pascal Birchler
Date: Fri, 17 Apr 2026 11:04:41 +0200
Subject: [PATCH 08/15] Namespaces, tests
---
db-command.php | 4 ++--
features/db-users.feature | 25 +++++--------------------
phpcs.xml.dist | 4 ----
src/DB_Command.php | 3 +--
src/DB_Command_SQLite.php | 4 ++++
src/DB_Users_Command.php | 4 ++++
6 files changed, 16 insertions(+), 28 deletions(-)
diff --git a/db-command.php b/db-command.php
index 3af9a7ec0..07de4604a 100644
--- a/db-command.php
+++ b/db-command.php
@@ -9,5 +9,5 @@
require_once $wpcli_db_autoloader;
}
-WP_CLI::add_command( 'db', 'DB_Command' );
-WP_CLI::add_command( 'db users', 'DB_Users_Command' );
+WP_CLI::add_command( 'db', DB_Command::class );
+WP_CLI::add_command( 'db users', \WP_CLI\Db\DB_Users_Command::class );
diff --git a/features/db-users.feature b/features/db-users.feature
index 06e8d9170..7f0a982df 100644
--- a/features/db-users.feature
+++ b/features/db-users.feature
@@ -1,3 +1,4 @@
+@skip-sqlite
Feature: Manage database users
Scenario: Create database user without privileges
@@ -5,11 +6,7 @@ Feature: Manage database users
And WP files
And wp-config.php
- When I run `wp db create`
- Then STDOUT should be:
- """
- Success: Database created.
- """
+ When I try `wp db create`
When I run `wp db users create testuser localhost --password=testpass123`
Then STDOUT should contain:
@@ -28,11 +25,7 @@ Feature: Manage database users
And WP files
And wp-config.php
- When I run `wp db create`
- Then STDOUT should be:
- """
- Success: Database created.
- """
+ When I try `wp db create`
When I run `wp db users create appuser localhost --password=secret123 --grant-privileges`
Then STDOUT should contain:
@@ -49,11 +42,7 @@ Feature: Manage database users
And WP files
And wp-config.php
- When I run `wp db create`
- Then STDOUT should be:
- """
- Success: Database created.
- """
+ When I try `wp db create`
When I run `wp db users create remoteuser '%' --password=remote123`
Then STDOUT should contain:
@@ -66,11 +55,7 @@ Feature: Manage database users
And WP files
And wp-config.php
- When I run `wp db create`
- Then STDOUT should be:
- """
- Success: Database created.
- """
+ When I try `wp db create`
When I run `wp db users create nopassuser localhost`
Then STDOUT should contain:
diff --git a/phpcs.xml.dist b/phpcs.xml.dist
index 7357c5bd3..c613cfe47 100644
--- a/phpcs.xml.dist
+++ b/phpcs.xml.dist
@@ -54,10 +54,6 @@
*/src/DB_Command\.php$
- */src/DB_Users_Command\.php$
-
-
- */src/DB_Command_SQLite\.php$
/tests/phpstan/scan-files
diff --git a/src/DB_Command.php b/src/DB_Command.php
index 634cb8bc2..210e08536 100644
--- a/src/DB_Command.php
+++ b/src/DB_Command.php
@@ -3,8 +3,7 @@
use WP_CLI\Formatter;
use WP_CLI\Utils;
use cli\table\Column;
-
-require_once __DIR__ . '/DB_Command_SQLite.php';
+use WP_CLI\Db\DB_Command_SQLite;
/**
* Performs basic database operations using credentials stored in wp-config.php.
diff --git a/src/DB_Command_SQLite.php b/src/DB_Command_SQLite.php
index 77893a005..6ec6e7d8f 100644
--- a/src/DB_Command_SQLite.php
+++ b/src/DB_Command_SQLite.php
@@ -1,7 +1,11 @@
Date: Fri, 17 Apr 2026 11:09:07 +0200
Subject: [PATCH 09/15] Lint fix
---
features/db-users.feature | 12 ++++--------
1 file changed, 4 insertions(+), 8 deletions(-)
diff --git a/features/db-users.feature b/features/db-users.feature
index 7f0a982df..339b7627f 100644
--- a/features/db-users.feature
+++ b/features/db-users.feature
@@ -7,8 +7,7 @@ Feature: Manage database users
And wp-config.php
When I try `wp db create`
-
- When I run `wp db users create testuser localhost --password=testpass123`
+ And I run `wp db users create testuser localhost --password=testpass123`
Then STDOUT should contain:
"""
Success: Database user 'testuser'@'localhost' created.
@@ -26,8 +25,7 @@ Feature: Manage database users
And wp-config.php
When I try `wp db create`
-
- When I run `wp db users create appuser localhost --password=secret123 --grant-privileges`
+ And I run `wp db users create appuser localhost --password=secret123 --grant-privileges`
Then STDOUT should contain:
"""
created with privileges on database
@@ -43,8 +41,7 @@ Feature: Manage database users
And wp-config.php
When I try `wp db create`
-
- When I run `wp db users create remoteuser '%' --password=remote123`
+ And I run `wp db users create remoteuser '%' --password=remote123`
Then STDOUT should contain:
"""
Success: Database user 'remoteuser'@'%' created.
@@ -56,8 +53,7 @@ Feature: Manage database users
And wp-config.php
When I try `wp db create`
-
- When I run `wp db users create nopassuser localhost`
+ And I run `wp db users create nopassuser localhost`
Then STDOUT should contain:
"""
Success: Database user 'nopassuser'@'localhost' created.
From e70699d8962714e93f7de688fe5c9d4e8bf7f3e7 Mon Sep 17 00:00:00 2001
From: Pascal Birchler
Date: Sun, 19 Apr 2026 22:11:33 +0200
Subject: [PATCH 10/15] Update src/DB_Users_Command.php
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
---
src/DB_Users_Command.php | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/DB_Users_Command.php b/src/DB_Users_Command.php
index b642d6a7e..863fccd2a 100644
--- a/src/DB_Users_Command.php
+++ b/src/DB_Users_Command.php
@@ -13,7 +13,7 @@
*
* # Create a new database user with privileges.
* $ wp db users create myuser myhost --password=mypass --grant-privileges
- * Success: Database user 'myuser'@'myhost' created with privileges.
+ * Success: Database user 'myuser'@'myhost' created with privileges on database 'wp_database'.
*
* @when after_wp_config_load
*/
From 381a520a39a07cd2689c21049e491a0f76259753 Mon Sep 17 00:00:00 2001
From: Pascal Birchler
Date: Sun, 19 Apr 2026 22:11:58 +0200
Subject: [PATCH 11/15] Update src/DB_Users_Command.php
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
---
src/DB_Users_Command.php | 10 ++++------
1 file changed, 4 insertions(+), 6 deletions(-)
diff --git a/src/DB_Users_Command.php b/src/DB_Users_Command.php
index 863fccd2a..d559532a4 100644
--- a/src/DB_Users_Command.php
+++ b/src/DB_Users_Command.php
@@ -67,12 +67,10 @@ public function create( $args, $assoc_args ) {
$password = Utils\get_flag_value( $assoc_args, 'password', '' );
$grant_privileges = Utils\get_flag_value( $assoc_args, 'grant-privileges', false );
- // Escape identifiers for SQL
- // @phpstan-ignore cast.string (PHPStan doesn't infer conditional return type from parent method)
- $username_escaped = (string) self::esc_sql_ident( $username );
- // @phpstan-ignore cast.string (PHPStan doesn't infer conditional return type from parent method)
- $host_escaped = (string) self::esc_sql_ident( $host );
- $user_identifier = $username_escaped . '@' . $host_escaped;
+ // MySQL account names in CREATE USER / GRANT ... TO use string literals, not identifiers.
+ $username_escaped = $this->esc_sql_string( $username );
+ $host_escaped = $this->esc_sql_string( $host );
+ $user_identifier = $username_escaped . '@' . $host_escaped;
// Create user
$create_query = "CREATE USER {$user_identifier}";
From f273be92f84213420ed1e8931b804a79f6c85102 Mon Sep 17 00:00:00 2001
From: Pascal Birchler
Date: Sun, 19 Apr 2026 22:12:09 +0200
Subject: [PATCH 12/15] Update src/DB_Users_Command.php
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
---
src/DB_Users_Command.php | 13 ++++---------
1 file changed, 4 insertions(+), 9 deletions(-)
diff --git a/src/DB_Users_Command.php b/src/DB_Users_Command.php
index d559532a4..c15ef3822 100644
--- a/src/DB_Users_Command.php
+++ b/src/DB_Users_Command.php
@@ -101,19 +101,14 @@ public function create( $args, $assoc_args ) {
/**
* Escapes a string for use in a SQL query.
*
- * Follows MySQL's documented string literal escaping rules.
- * See https://dev.mysql.com/doc/refman/en/string-literals.html
+ * Uses SQL-standard single-quote escaping (`'` => `''`) so the generated
+ * literal remains valid even when MySQL is running with
+ * `NO_BACKSLASH_ESCAPES`.
*
* @param string $value String to escape.
* @return string Escaped string, wrapped in single quotes.
*/
private function esc_sql_string( $value ) {
- // Escape special characters according to MySQL string literal rules.
- $value = str_replace(
- [ '\\', "\x00", "\n", "\r", "'", '"', "\x1a" ],
- [ '\\\\', "\\0", "\\n", "\\r", "\\'", '\\"', '\\Z' ],
- $value
- );
- return "'" . $value . "'";
+ return "'" . str_replace( "'", "''", $value ) . "'";
}
}
From cb1156a5a7f4ec1817b15ee29799c4a95b3a5388 Mon Sep 17 00:00:00 2001
From: Pascal Birchler
Date: Tue, 24 Nov 2026 15:08:22 +0000
Subject: [PATCH 13/15] Make `wp db users` a standalone command
`DB_Users_Command` extended `DB_Command`, so every public method of it
became a subcommand of `wp db users` too: `wp db users drop` dropped the
WordPress database, and so on. It is now a standalone command whose
only subcommand is `create`.
The statements are passed to the mysql client through STDIN, so the new
user's password no longer shows up in the process list or in --debug
output. If --password is omitted, it is read from STDIN when piped and
prompted for otherwise, and creating a user without a password is an
error. NO_BACKSLASH_ESCAPES is turned off for the session so that
quoting the password and account name is reliable, and `_` and `%` are
escaped in the database name so that GRANT only matches that database.
FLUSH PRIVILEGES is not needed after GRANT and is dropped.
SQLite is refused with a clear error, and the unrelated changes to the
db command registration, the SQLite trait and phpcs.xml.dist are
reverted.
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01UWTd5pwpi2xQfDA6mUYkkx
---
db-command.php | 4 +-
features/db-users.feature | 124 ++++++++++++++------
phpcs.xml.dist | 3 +
src/DB_Command.php | 5 +-
src/DB_Command_SQLite.php | 4 -
src/DB_Users_Command.php | 114 ------------------
src/Users_Command.php | 236 ++++++++++++++++++++++++++++++++++++++
7 files changed, 331 insertions(+), 159 deletions(-)
delete mode 100644 src/DB_Users_Command.php
create mode 100644 src/Users_Command.php
diff --git a/db-command.php b/db-command.php
index 07de4604a..540b1776e 100644
--- a/db-command.php
+++ b/db-command.php
@@ -9,5 +9,5 @@
require_once $wpcli_db_autoloader;
}
-WP_CLI::add_command( 'db', DB_Command::class );
-WP_CLI::add_command( 'db users', \WP_CLI\Db\DB_Users_Command::class );
+WP_CLI::add_command( 'db', 'DB_Command' );
+WP_CLI::add_command( 'db users', 'WP_CLI\DB\Users_Command' );
diff --git a/features/db-users.feature b/features/db-users.feature
index 339b7627f..b27e83d5a 100644
--- a/features/db-users.feature
+++ b/features/db-users.feature
@@ -1,60 +1,110 @@
-@skip-sqlite
Feature: Manage database users
- Scenario: Create database user without privileges
- Given an empty directory
- And WP files
- And wp-config.php
+ @require-mysql-or-mariadb
+ Scenario: Create a database user without privileges
+ Given a WP install
+ And I run `wp db query "DROP USER IF EXISTS 'wpcli_dbusers_1'@'%'" --dbuser={DB_ROOT_USER} --dbpass={DB_ROOT_PASSWORD}`
- When I try `wp db create`
- And I run `wp db users create testuser localhost --password=testpass123`
- Then STDOUT should contain:
+ When I run `wp db users create wpcli_dbusers_1 '%' --password=first-Pa55 --dbuser={DB_ROOT_USER} --dbpass={DB_ROOT_PASSWORD}`
+ Then STDOUT should be:
"""
- Success: Database user 'testuser'@'localhost' created.
+ Success: Created database user 'wpcli_dbusers_1'@'%'.
"""
- When I run `wp db query "SELECT User, Host FROM mysql.user WHERE User='testuser'"`
- Then STDOUT should contain:
+ When I run `wp db query "SELECT User FROM mysql.user WHERE User = 'wpcli_dbusers_1'" --skip-column-names --dbuser={DB_ROOT_USER} --dbpass={DB_ROOT_PASSWORD}`
+ Then STDOUT should be:
"""
- testuser
+ wpcli_dbusers_1
"""
- Scenario: Create database user with privileges
- Given an empty directory
- And WP files
- And wp-config.php
+ When I try `wp db query "SELECT 1" --dbuser=wpcli_dbusers_1 --dbpass=first-Pa55`
+ Then the return code should be 1
+ And STDERR should contain:
+ """
+ denied
+ """
- When I try `wp db create`
- And I run `wp db users create appuser localhost --password=secret123 --grant-privileges`
- Then STDOUT should contain:
+ When I try `wp db users create wpcli_dbusers_1 '%' --password=first-Pa55 --dbuser={DB_ROOT_USER} --dbpass={DB_ROOT_PASSWORD}`
+ Then the return code should be 1
+ And STDERR should contain:
+ """
+ Error:
+ """
+
+ When I run `wp db query "DROP USER 'wpcli_dbusers_1'@'%'" --dbuser={DB_ROOT_USER} --dbpass={DB_ROOT_PASSWORD}`
+
+ @require-mysql-or-mariadb
+ Scenario: Create a database user with privileges on the WordPress database
+ Given a WP install
+ And I run `wp db query "DROP USER IF EXISTS 'wpcli_dbusers_2'@'%'" --dbuser={DB_ROOT_USER} --dbpass={DB_ROOT_PASSWORD}`
+
+ When I run `echo "it's a \"tricky\" pass\\word;" | wp db users create wpcli_dbusers_2 '%' --grant-privileges --dbuser={DB_ROOT_USER} --dbpass={DB_ROOT_PASSWORD}`
+ Then STDOUT should be:
"""
- created with privileges on database
+ Success: Created database user 'wpcli_dbusers_2'@'%' with all privileges on '{DB_NAME}'.
"""
- And STDOUT should contain:
+
+ When I run `wp db query "SELECT option_value FROM wp_options WHERE option_name = 'siteurl'" --skip-column-names --dbuser=wpcli_dbusers_2 --dbpass="it's a \"tricky\" pass\\word;"`
+ Then STDOUT should be:
"""
- appuser
+ https://example.com
"""
- Scenario: Create database user with custom host
- Given an empty directory
- And WP files
- And wp-config.php
+ When I run `wp db query "DROP USER 'wpcli_dbusers_2'@'%'" --dbuser={DB_ROOT_USER} --dbpass={DB_ROOT_PASSWORD}`
- When I try `wp db create`
- And I run `wp db users create remoteuser '%' --password=remote123`
- Then STDOUT should contain:
+ @require-mysql-or-mariadb
+ Scenario: The new user's password is not leaked into the debug output
+ Given a WP install
+ And I run `wp db query "DROP USER IF EXISTS 'wpcli_dbusers_3'@'%'" --dbuser={DB_ROOT_USER} --dbpass={DB_ROOT_PASSWORD}`
+
+ When I try `wp db users create wpcli_dbusers_3 '%' --password=leak-Ch3ck-Value --dbuser={DB_ROOT_USER} --dbpass={DB_ROOT_PASSWORD} --debug=db`
+ Then the return code should be 0
+ And STDERR should contain:
+ """
+ Creating database user 'wpcli_dbusers_3'@'%'.
"""
- Success: Database user 'remoteuser'@'%' created.
+ And STDERR should not contain:
"""
+ leak-Ch3ck-Value
+ """
+
+ When I run `wp db query "DROP USER 'wpcli_dbusers_3'@'%'" --dbuser={DB_ROOT_USER} --dbpass={DB_ROOT_PASSWORD}`
- Scenario: Create database user with no password
- Given an empty directory
- And WP files
- And wp-config.php
+ @require-mysql-or-mariadb
+ Scenario: A password is required
+ Given a WP install
- When I try `wp db create`
- And I run `wp db users create nopassuser localhost`
+ When I try `wp db users create wpcli_dbusers_4 '%' --dbuser={DB_ROOT_USER} --dbpass={DB_ROOT_PASSWORD} < /dev/null`
+ Then the return code should be 1
+ And STDERR should contain:
+ """
+ Error: A password is required.
+ """
+
+ @require-mysql-or-mariadb
+ Scenario: Only the create subcommand is available
+ Given a WP install
+
+ When I try `wp db users drop --yes`
+ Then the return code should be 1
+ And STDERR should contain:
+ """
+ is not a registered subcommand of 'db users'
+ """
+
+ When I run `wp db check`
Then STDOUT should contain:
"""
- Success: Database user 'nopassuser'@'localhost' created.
+ Success: Database checked.
+ """
+
+ @require-sqlite
+ Scenario: Database users are not supported with SQLite
+ Given a WP install
+
+ When I try `wp db users create someone --password=some-Pa55`
+ Then the return code should be 1
+ And STDERR should be:
+ """
+ Error: Database users are not supported with SQLite.
"""
diff --git a/phpcs.xml.dist b/phpcs.xml.dist
index c613cfe47..b439f14f0 100644
--- a/phpcs.xml.dist
+++ b/phpcs.xml.dist
@@ -55,6 +55,9 @@
*/src/DB_Command\.php$
+
+ */src/DB_Command_SQLite\.php$
+
/tests/phpstan/scan-files
diff --git a/src/DB_Command.php b/src/DB_Command.php
index 6c67cfc71..3b126a6c2 100644
--- a/src/DB_Command.php
+++ b/src/DB_Command.php
@@ -4,7 +4,8 @@
use WP_CLI\Process;
use WP_CLI\Utils;
use cli\table\Column;
-use WP_CLI\Db\DB_Command_SQLite;
+
+require_once __DIR__ . '/DB_Command_SQLite.php';
/**
* Performs basic database operations using credentials stored in wp-config.php.
@@ -2234,7 +2235,7 @@ private static function is_text_col( $type ) {
*
* @phpstan-return ($idents is string ? string : array)
*/
- protected static function esc_sql_ident( $idents ) {
+ private static function esc_sql_ident( $idents ) {
$backtick = static function ( $v ) {
// Escape any backticks in the identifier by doubling.
return '`' . str_replace( '`', '``', $v ) . '`';
diff --git a/src/DB_Command_SQLite.php b/src/DB_Command_SQLite.php
index 7fc409625..978c21903 100644
--- a/src/DB_Command_SQLite.php
+++ b/src/DB_Command_SQLite.php
@@ -1,11 +1,7 @@
- * : MySQL username for the new user account.
- *
- * []
- * : MySQL host for the new user account.
- * ---
- * default: localhost
- * ---
- *
- * [--password=]
- * : Password for the new user account. If not provided, MySQL will use no password.
- *
- * [--grant-privileges]
- * : Grant full privileges on the current database to the new user.
- *
- * [--dbuser=]
- * : Username to connect as (privileged user). Defaults to DB_USER.
- *
- * [--dbpass=]
- * : Password to connect with (privileged user). Defaults to DB_PASSWORD.
- *
- * [--defaults]
- * : Loads the environment's MySQL option files. Default behavior is to skip loading them to avoid failures due to misconfiguration.
- *
- * ## EXAMPLES
- *
- * # Create a user without privileges.
- * $ wp db users create myuser localhost --password=mypass
- * Success: Database user 'myuser'@'localhost' created.
- *
- * # Create a user with full privileges on the current database.
- * $ wp db users create appuser localhost --password=secret123 --grant-privileges
- * Success: Database user 'appuser'@'localhost' created with privileges on database 'wp_database'.
- */
- public function create( $args, $assoc_args ) {
- list( $username, $host ) = array_pad( $args, 2, 'localhost' );
-
- $password = Utils\get_flag_value( $assoc_args, 'password', '' );
- $grant_privileges = Utils\get_flag_value( $assoc_args, 'grant-privileges', false );
-
- // MySQL account names in CREATE USER / GRANT ... TO use string literals, not identifiers.
- $username_escaped = $this->esc_sql_string( $username );
- $host_escaped = $this->esc_sql_string( $host );
- $user_identifier = $username_escaped . '@' . $host_escaped;
-
- // Create user
- $create_query = "CREATE USER {$user_identifier}";
- if ( ! empty( $password ) ) {
- $password_escaped = $this->esc_sql_string( $password );
- $create_query .= " IDENTIFIED BY {$password_escaped}";
- }
- $create_query .= ';';
-
- parent::run_query( $create_query, $assoc_args );
-
- // Grant privileges if requested
- if ( $grant_privileges ) {
- $database = DB_NAME;
- $database_escaped = (string) self::esc_sql_ident( $database );
- $grant_query = 'GRANT ALL PRIVILEGES ON ' . $database_escaped . '.* TO ' . $user_identifier . ';';
- parent::run_query( $grant_query, $assoc_args );
-
- // Flush privileges
- parent::run_query( 'FLUSH PRIVILEGES;', $assoc_args );
-
- WP_CLI::success( "Database user '{$username}'@'{$host}' created with privileges on database '{$database}'." );
- } else {
- WP_CLI::success( "Database user '{$username}'@'{$host}' created." );
- }
- }
-
- /**
- * Escapes a string for use in a SQL query.
- *
- * Uses SQL-standard single-quote escaping (`'` => `''`) so the generated
- * literal remains valid even when MySQL is running with
- * `NO_BACKSLASH_ESCAPES`.
- *
- * @param string $value String to escape.
- * @return string Escaped string, wrapped in single quotes.
- */
- private function esc_sql_string( $value ) {
- return "'" . str_replace( "'", "''", $value ) . "'";
- }
-}
diff --git a/src/Users_Command.php b/src/Users_Command.php
new file mode 100644
index 000000000..826f980ec
--- /dev/null
+++ b/src/Users_Command.php
@@ -0,0 +1,236 @@
+]:
+ * Password:
+ * Success: Created database user 'appuser'@'localhost' with all privileges on 'wp_database'.
+ *
+ * @when after_wp_config_load
+ */
+class Users_Command extends WP_CLI_Command {
+
+ use DB_Command_SQLite;
+
+ /**
+ * Creates a database user.
+ *
+ * The statements are sent to the `mysql` client through STDIN, so the new
+ * user's password doesn't show up in the process list or in `--debug` output.
+ *
+ * ## OPTIONS
+ *
+ *
+ * : Name of the user to create.
+ *
+ * []
+ * : Host the user is allowed to connect from. Use `%` for any host.
+ * ---
+ * default: localhost
+ * ---
+ *
+ * [--password=]
+ * : Password for the new user. If omitted, it is read from STDIN when input is piped, and prompted for otherwise. Avoid passing it here on shared systems, as it ends up in the shell history.
+ *
+ * [--grant-privileges]
+ * : Grant the new user all privileges on the WordPress database (DB_NAME).
+ *
+ * [--dbuser=]
+ * : Username to connect as. Needs the `CREATE USER` privilege. Defaults to DB_USER.
+ *
+ * [--dbpass=]
+ * : Password to connect with. Defaults to DB_PASSWORD.
+ *
+ * [--defaults]
+ * : Loads the environment's MySQL option files. Default behavior is to skip loading them to avoid failures due to misconfiguration.
+ *
+ * ## EXAMPLES
+ *
+ * # Create a user that can connect from any host, reading the password from a file.
+ * $ wp db users create appuser '%' --dbuser=root --prompt=dbpass < password.txt
+ * 1/1 [--dbpass=]:
+ * Success: Created database user 'appuser'@'%'.
+ *
+ * # Create a user with full privileges on the WordPress database.
+ * $ wp db users create appuser localhost --grant-privileges --dbuser=root --prompt=dbpass
+ * 1/1 [--dbpass=]:
+ * Password:
+ * Success: Created database user 'appuser'@'localhost' with all privileges on 'wp_database'.
+ */
+ public function create( $args, $assoc_args ) {
+ if ( $this->is_sqlite() ) {
+ WP_CLI::error( 'Database users are not supported with SQLite.' );
+ }
+
+ $username = $args[0];
+ $host = isset( $args[1] ) ? $args[1] : 'localhost';
+
+ if ( '' === $username ) {
+ WP_CLI::error( 'The username cannot be empty.' );
+ }
+
+ $password = $this->get_password( $assoc_args );
+ $account = self::esc_sql_string( $username ) . '@' . self::esc_sql_string( $host );
+
+ // Turn off NO_BACKSLASH_ESCAPES for this session, so the escaping of the
+ // string literals below is correct regardless of the server's SQL mode.
+ $statements = [
+ "SET SESSION sql_mode = TRIM( BOTH ',' FROM REPLACE( CONCAT( ',', @@SESSION.sql_mode, ',' ), ',NO_BACKSLASH_ESCAPES,', ',' ) )",
+ "CREATE USER {$account} IDENTIFIED BY " . self::esc_sql_string( $password ),
+ ];
+
+ $grant = (bool) Utils\get_flag_value( $assoc_args, 'grant-privileges', false );
+ if ( $grant ) {
+ $statements[] = 'GRANT ALL PRIVILEGES ON ' . self::esc_grant_database( DB_NAME ) . ".* TO {$account}";
+ }
+
+ WP_CLI::debug( "Creating database user '{$username}'@'{$host}'" . ( $grant ? ' with all privileges on ' . DB_NAME : '' ) . '.', 'db' );
+
+ $this->run_statements( implode( ";\n", $statements ) . ";\n", $assoc_args );
+
+ if ( $grant ) {
+ WP_CLI::success( "Created database user '{$username}'@'{$host}' with all privileges on '" . DB_NAME . "'." );
+ } else {
+ WP_CLI::success( "Created database user '{$username}'@'{$host}'." );
+ }
+ }
+
+ /**
+ * Gets the new user's password from the arguments, STDIN or a prompt.
+ *
+ * @param array $assoc_args Associative arguments.
+ * @return string Password.
+ */
+ private function get_password( $assoc_args ) {
+ if ( isset( $assoc_args['password'] ) && true !== $assoc_args['password'] ) {
+ $password = (string) $assoc_args['password'];
+ } elseif ( function_exists( 'stream_isatty' ) && stream_isatty( STDIN ) ) {
+ $password = (string) \cli\prompt( 'Password', false, ': ', true );
+ } else {
+ $password = (string) stream_get_contents( STDIN );
+ // Strip the trailing newline of piped input, but nothing else.
+ $password = (string) preg_replace( '/\r?\n\z/', '', $password );
+ }
+
+ if ( '' === $password ) {
+ WP_CLI::error( 'A password is required. Pass it with --password, pipe it to STDIN, or enter it when prompted.' );
+ }
+
+ return $password;
+ }
+
+ /**
+ * Runs SQL statements with the `mysql` client, passing them through STDIN.
+ *
+ * @param string $sql SQL statements to run.
+ * @param array $assoc_args Associative arguments.
+ */
+ private function run_statements( $sql, $assoc_args ) {
+ $mysql_args = [
+ 'user' => Utils\get_flag_value( $assoc_args, 'dbuser', DB_USER ),
+ ];
+
+ // phpcs:ignore WordPress.DB.RestrictedFunctions.mysql_mysql_host_to_cli_args, PHPCompatibility.Extensions.RemovedExtensions.mysql_DeprecatedRemoved -- Misidentified as PHP native MySQL function.
+ $mysql_args = array_merge( $mysql_args, Utils\mysql_host_to_cli_args( DB_HOST ) );
+
+ if ( defined( 'DB_CHARSET' ) && constant( 'DB_CHARSET' ) ) {
+ $mysql_args['default-character-set'] = constant( 'DB_CHARSET' );
+ }
+
+ // See DB_Command::run(): skip the certificate check like WordPress does.
+ if ( 'mariadb' === Utils\get_db_type() ) {
+ $mysql_args['skip-ssl-verify-server-cert'] = true;
+ }
+
+ $defaults = Utils\get_flag_value( $assoc_args, 'defaults', false ) ? '' : ' --no-defaults';
+ $command = Utils\force_env_on_nix_systems( Utils\get_mysql_binary_path() . $defaults . ' --no-auto-rehash --batch' )
+ . Utils\assoc_args_to_str( $mysql_args );
+
+ WP_CLI::debug( "Final MySQL command: {$command}", 'db' );
+
+ // The connection password goes through the environment, the statements through STDIN.
+ $old_password = getenv( 'MYSQL_PWD' );
+ $dbpass = Utils\get_flag_value( $assoc_args, 'dbpass', DB_PASSWORD );
+ putenv( 'MYSQL_PWD=' . ( is_string( $dbpass ) ? $dbpass : '' ) );
+
+ $pipes = [];
+ $process = Utils\proc_open_compat(
+ $command,
+ [
+ 0 => [ 'pipe', 'r' ],
+ 1 => [ 'pipe', 'w' ],
+ 2 => [ 'pipe', 'w' ],
+ ],
+ $pipes
+ );
+
+ if ( false === $old_password ) {
+ putenv( 'MYSQL_PWD' );
+ } else {
+ putenv( 'MYSQL_PWD=' . $old_password );
+ }
+
+ if ( ! is_resource( $process ) ) {
+ WP_CLI::error( 'Could not run the mysql client.' );
+ }
+
+ fwrite( $pipes[0], $sql );
+ fclose( $pipes[0] );
+
+ $stdout = (string) stream_get_contents( $pipes[1] );
+ $stderr = (string) stream_get_contents( $pipes[2] );
+ fclose( $pipes[1] );
+ fclose( $pipes[2] );
+
+ $exit_code = proc_close( $process );
+
+ if ( '' !== trim( $stdout ) ) {
+ WP_CLI::debug( trim( $stdout ), 'db' );
+ }
+
+ if ( 0 !== $exit_code ) {
+ WP_CLI::error( '' !== trim( $stderr ) ? trim( $stderr ) : "The mysql client exited with code {$exit_code}." );
+ }
+ }
+
+ /**
+ * Quotes a value as an SQL string literal.
+ *
+ * Assumes backslash escapes are enabled, see create().
+ *
+ * @param string $value Value to quote.
+ * @return string Quoted value.
+ */
+ private static function esc_sql_string( $value ) {
+ return "'" . str_replace( [ '\\', "'" ], [ '\\\\', "''" ], $value ) . "'";
+ }
+
+ /**
+ * Quotes a database name for use in a GRANT statement.
+ *
+ * GRANT treats `_` and `%` in database names as wildcards, so they are
+ * escaped to only match this one database.
+ *
+ * @param string $database Database name.
+ * @return string Quoted database name.
+ */
+ private static function esc_grant_database( $database ) {
+ return '`' . str_replace( [ '`', '_', '%' ], [ '``', '\\_', '\\%' ], $database ) . '`';
+ }
+}
From 439f64e4e32950a972c2393e2142b3ce2c007ec0 Mon Sep 17 00:00:00 2001
From: Pascal Birchler
Date: Tue, 24 Nov 2026 15:14:05 +0000
Subject: [PATCH 14/15] Do not use DROP USER IF EXISTS in the db users tests
MySQL 5.6 does not support it, which failed the three scenarios on the
MySQL 5.6 jobs. Use a plain DROP USER with `I try` for the cleanup instead.
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01UWTd5pwpi2xQfDA6mUYkkx
---
features/db-users.feature | 7 ++++---
1 file changed, 4 insertions(+), 3 deletions(-)
diff --git a/features/db-users.feature b/features/db-users.feature
index b27e83d5a..608c23b45 100644
--- a/features/db-users.feature
+++ b/features/db-users.feature
@@ -1,9 +1,10 @@
Feature: Manage database users
+ # The cleanup uses `I try` with a plain DROP USER, as MySQL 5.6 has no DROP USER IF EXISTS.
@require-mysql-or-mariadb
Scenario: Create a database user without privileges
Given a WP install
- And I run `wp db query "DROP USER IF EXISTS 'wpcli_dbusers_1'@'%'" --dbuser={DB_ROOT_USER} --dbpass={DB_ROOT_PASSWORD}`
+ And I try `wp db query "DROP USER 'wpcli_dbusers_1'@'%'" --dbuser={DB_ROOT_USER} --dbpass={DB_ROOT_PASSWORD}`
When I run `wp db users create wpcli_dbusers_1 '%' --password=first-Pa55 --dbuser={DB_ROOT_USER} --dbpass={DB_ROOT_PASSWORD}`
Then STDOUT should be:
@@ -36,7 +37,7 @@ Feature: Manage database users
@require-mysql-or-mariadb
Scenario: Create a database user with privileges on the WordPress database
Given a WP install
- And I run `wp db query "DROP USER IF EXISTS 'wpcli_dbusers_2'@'%'" --dbuser={DB_ROOT_USER} --dbpass={DB_ROOT_PASSWORD}`
+ And I try `wp db query "DROP USER 'wpcli_dbusers_2'@'%'" --dbuser={DB_ROOT_USER} --dbpass={DB_ROOT_PASSWORD}`
When I run `echo "it's a \"tricky\" pass\\word;" | wp db users create wpcli_dbusers_2 '%' --grant-privileges --dbuser={DB_ROOT_USER} --dbpass={DB_ROOT_PASSWORD}`
Then STDOUT should be:
@@ -55,7 +56,7 @@ Feature: Manage database users
@require-mysql-or-mariadb
Scenario: The new user's password is not leaked into the debug output
Given a WP install
- And I run `wp db query "DROP USER IF EXISTS 'wpcli_dbusers_3'@'%'" --dbuser={DB_ROOT_USER} --dbpass={DB_ROOT_PASSWORD}`
+ And I try `wp db query "DROP USER 'wpcli_dbusers_3'@'%'" --dbuser={DB_ROOT_USER} --dbpass={DB_ROOT_PASSWORD}`
When I try `wp db users create wpcli_dbusers_3 '%' --password=leak-Ch3ck-Value --dbuser={DB_ROOT_USER} --dbpass={DB_ROOT_PASSWORD} --debug=db`
Then the return code should be 0
From 0a895d3683a5f9df738f25b29628a3d3bfac5ce3 Mon Sep 17 00:00:00 2001
From: Pascal Birchler
Date: Tue, 24 Nov 2026 21:54:51 +0000
Subject: [PATCH 15/15] Keep the new password out of errors and intact in `wp
db users create`
- Only show the client's ERROR lines on failure. The MariaDB client
echoes the failed CREATE USER statement, password included.
- Pass --binary-mode so a CRLF inside the password isn't turned into LF.
- Don't escape `_` and `%` in the GRANT database name when MySQL's
partial_revokes is on, as they're literal characters then.
- Fix the example that read both passwords from the same STDIN.
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01UWTd5pwpi2xQfDA6mUYkkx
---
features/db-users.feature | 34 ++++++++++++++++++--
src/Users_Command.php | 67 +++++++++++++++++++++++++++++----------
2 files changed, 83 insertions(+), 18 deletions(-)
diff --git a/features/db-users.feature b/features/db-users.feature
index 608c23b45..8a884cb9b 100644
--- a/features/db-users.feature
+++ b/features/db-users.feature
@@ -25,11 +25,15 @@ Feature: Manage database users
denied
"""
- When I try `wp db users create wpcli_dbusers_1 '%' --password=first-Pa55 --dbuser={DB_ROOT_USER} --dbpass={DB_ROOT_PASSWORD}`
+ When I try `wp db users create wpcli_dbusers_1 '%' --password=dupe-Pa55-Value --dbuser={DB_ROOT_USER} --dbpass={DB_ROOT_PASSWORD}`
Then the return code should be 1
And STDERR should contain:
"""
- Error:
+ Error: ERROR 1396
+ """
+ And STDERR should not contain:
+ """
+ dupe-Pa55-Value
"""
When I run `wp db query "DROP USER 'wpcli_dbusers_1'@'%'" --dbuser={DB_ROOT_USER} --dbpass={DB_ROOT_PASSWORD}`
@@ -53,6 +57,32 @@ Feature: Manage database users
When I run `wp db query "DROP USER 'wpcli_dbusers_2'@'%'" --dbuser={DB_ROOT_USER} --dbpass={DB_ROOT_PASSWORD}`
+ @require-mysql-or-mariadb
+ Scenario: A password with an internal CRLF is kept as is
+ Given a WP install
+ And I try `wp db query "DROP USER 'wpcli_dbusers_5'@'%'" --dbuser={DB_ROOT_USER} --dbpass={DB_ROOT_PASSWORD}`
+
+ When I run `printf 'crlf\r\nPa55\n' | wp db users create wpcli_dbusers_5 '%' --grant-privileges --dbuser={DB_ROOT_USER} --dbpass={DB_ROOT_PASSWORD}`
+ Then STDOUT should contain:
+ """
+ Success:
+ """
+
+ When I run `wp db query "SELECT 'connected'" --skip-column-names --dbuser=wpcli_dbusers_5 --dbpass="$(printf 'crlf\r\nPa55')"`
+ Then STDOUT should be:
+ """
+ connected
+ """
+
+ When I try `wp db query "SELECT 'connected'" --skip-column-names --dbuser=wpcli_dbusers_5 --dbpass="$(printf 'crlf\nPa55')"`
+ Then the return code should be 1
+ And STDERR should contain:
+ """
+ ERROR 1045
+ """
+
+ When I run `wp db query "DROP USER 'wpcli_dbusers_5'@'%'" --dbuser={DB_ROOT_USER} --dbpass={DB_ROOT_PASSWORD}`
+
@require-mysql-or-mariadb
Scenario: The new user's password is not leaked into the debug output
Given a WP install
diff --git a/src/Users_Command.php b/src/Users_Command.php
index 826f980ec..d84fb8c10 100644
--- a/src/Users_Command.php
+++ b/src/Users_Command.php
@@ -62,9 +62,9 @@ class Users_Command extends WP_CLI_Command {
*
* ## EXAMPLES
*
- * # Create a user that can connect from any host, reading the password from a file.
- * $ wp db users create appuser '%' --dbuser=root --prompt=dbpass < password.txt
- * 1/1 [--dbpass=]:
+ * # Create a user that can connect from any host, reading its password from a file.
+ * # This connects as DB_USER, which then needs the CREATE USER privilege.
+ * $ wp db users create appuser '%' < password.txt
* Success: Created database user 'appuser'@'%'.
*
* # Create a user with full privileges on the WordPress database.
@@ -97,12 +97,12 @@ public function create( $args, $assoc_args ) {
$grant = (bool) Utils\get_flag_value( $assoc_args, 'grant-privileges', false );
if ( $grant ) {
- $statements[] = 'GRANT ALL PRIVILEGES ON ' . self::esc_grant_database( DB_NAME ) . ".* TO {$account}";
+ $statements[] = 'GRANT ALL PRIVILEGES ON ' . self::esc_grant_database( DB_NAME, $this->has_partial_revokes( $assoc_args ) ) . ".* TO {$account}";
}
WP_CLI::debug( "Creating database user '{$username}'@'{$host}'" . ( $grant ? ' with all privileges on ' . DB_NAME : '' ) . '.', 'db' );
- $this->run_statements( implode( ";\n", $statements ) . ";\n", $assoc_args );
+ $this->run_statements( implode( ";\n", $statements ) . ";\n", $assoc_args, $password );
if ( $grant ) {
WP_CLI::success( "Created database user '{$username}'@'{$host}' with all privileges on '" . DB_NAME . "'." );
@@ -135,13 +135,35 @@ private function get_password( $assoc_args ) {
return $password;
}
+ /**
+ * Checks whether the server has MySQL's `partial_revokes` enabled.
+ *
+ * With it, `_` and `%` in GRANT database names are literal characters
+ * instead of wildcards. Only checked when DB_NAME contains them.
+ *
+ * @param array $assoc_args Associative arguments.
+ * @return bool
+ */
+ private function has_partial_revokes( $assoc_args ) {
+ if ( false === strpbrk( DB_NAME, '_%' ) ) {
+ return false;
+ }
+
+ // MariaDB and MySQL before 8.0.16 have no such variable, which returns no rows.
+ $output = $this->run_statements( "SHOW GLOBAL VARIABLES LIKE 'partial_revokes';\n", $assoc_args );
+
+ return (bool) preg_match( '/^partial_revokes\s+(ON|1)\s*$/mi', $output );
+ }
+
/**
* Runs SQL statements with the `mysql` client, passing them through STDIN.
*
* @param string $sql SQL statements to run.
* @param array $assoc_args Associative arguments.
+ * @param string $secret Optional value to keep out of error messages.
+ * @return string Output of the statements.
*/
- private function run_statements( $sql, $assoc_args ) {
+ private function run_statements( $sql, $assoc_args, $secret = '' ) {
$mysql_args = [
'user' => Utils\get_flag_value( $assoc_args, 'dbuser', DB_USER ),
];
@@ -159,7 +181,8 @@ private function run_statements( $sql, $assoc_args ) {
}
$defaults = Utils\get_flag_value( $assoc_args, 'defaults', false ) ? '' : ' --no-defaults';
- $command = Utils\force_env_on_nix_systems( Utils\get_mysql_binary_path() . $defaults . ' --no-auto-rehash --batch' )
+ // --binary-mode keeps the client from turning CRLF in the statements (and so in passwords) into LF.
+ $command = Utils\force_env_on_nix_systems( Utils\get_mysql_binary_path() . $defaults . ' --no-auto-rehash --batch --binary-mode' )
. Utils\assoc_args_to_str( $mysql_args );
WP_CLI::debug( "Final MySQL command: {$command}", 'db' );
@@ -200,13 +223,18 @@ private function run_statements( $sql, $assoc_args ) {
$exit_code = proc_close( $process );
- if ( '' !== trim( $stdout ) ) {
- WP_CLI::debug( trim( $stdout ), 'db' );
- }
-
if ( 0 !== $exit_code ) {
- WP_CLI::error( '' !== trim( $stderr ) ? trim( $stderr ) : "The mysql client exited with code {$exit_code}." );
+ // The MariaDB client echoes a failed statement, including the new user's password,
+ // before the error. Only keep the error lines, and redact the password just in case.
+ $errors = preg_grep( '/^ERROR\b/', explode( "\n", str_replace( "\r\n", "\n", $stderr ) ) );
+ $errors = trim( implode( "\n", $errors ? $errors : [] ) );
+ if ( '' !== $secret ) {
+ $errors = str_replace( [ $secret, substr( self::esc_sql_string( $secret ), 1, -1 ) ], '***', $errors );
+ }
+ WP_CLI::error( '' !== $errors ? $errors : "The mysql client exited with code {$exit_code}." );
}
+
+ return $stdout;
}
/**
@@ -225,12 +253,19 @@ private static function esc_sql_string( $value ) {
* Quotes a database name for use in a GRANT statement.
*
* GRANT treats `_` and `%` in database names as wildcards, so they are
- * escaped to only match this one database.
+ * escaped to only match this one database. With MySQL's `partial_revokes`
+ * enabled they are literal characters, and escaping them would make the
+ * name match no database.
*
- * @param string $database Database name.
+ * @param string $database Database name.
+ * @param bool $partial_revokes Whether `partial_revokes` is enabled.
* @return string Quoted database name.
*/
- private static function esc_grant_database( $database ) {
- return '`' . str_replace( [ '`', '_', '%' ], [ '``', '\\_', '\\%' ], $database ) . '`';
+ private static function esc_grant_database( $database, $partial_revokes = false ) {
+ $database = str_replace( '`', '``', $database );
+ if ( ! $partial_revokes ) {
+ $database = str_replace( [ '_', '%' ], [ '\\_', '\\%' ], $database );
+ }
+ return '`' . $database . '`';
}
}