Skip to content
Merged
Show file tree
Hide file tree
Changes from 13 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions features/db.feature
Original file line number Diff line number Diff line change
Expand Up @@ -326,3 +326,19 @@ Feature: Perform database operations
"""
latin1_spanish_ci
"""

Scenario: Running an UPDATE query should return the number of affected rows
Given a WP install
When I run `wp db query "UPDATE wp_users SET user_status = 1 WHERE ID = 1"`
Then STDOUT should contain:
"""
Query succeeded. Rows affected: 1
"""

Scenario: Running an DELETE query should return the number of affected rows
Given a WP install
When I run `wp db query "DELETE FROM wp_users WHERE ID = 1"`
Then STDOUT should contain:
"""
Query succeeded. Rows affected: 1
"""
26 changes: 21 additions & 5 deletions src/DB_Command.php
Original file line number Diff line number Diff line change
Expand Up @@ -495,24 +495,40 @@ public function cli( $_, $assoc_args ) {
* +---------+-----------------------+
*/
public function query( $args, $assoc_args ) {

$command = sprintf( '/usr/bin/env mysql%s --no-auto-rehash', $this->get_defaults_flag_string( $assoc_args ) );
WP_CLI::debug( "Running shell command: {$command}", 'db' );

$assoc_args['database'] = DB_NAME;

// The query might come from STDIN.
if ( ! empty( $args ) ) {
$assoc_args['execute'] = $args[0];
}

if ( isset( $assoc_args['execute'] ) ) {
// Ensure that the SQL mode is compatible with WPDB.
$assoc_args['execute'] = $this->get_sql_mode_query( $assoc_args ) . $assoc_args['execute'];
}

$is_update_or_delete = isset( $assoc_args['execute'] ) && preg_match( '/\b(UPDATE|DELETE|INSERT)\b/i', $assoc_args['execute'] );

if ( $is_update_or_delete ) {
// Append `SELECT ROW_COUNT()` to the query.
$assoc_args['execute'] .= '; SELECT ROW_COUNT();';
}

WP_CLI::debug( 'Associative arguments: ' . json_encode( $assoc_args ), 'db' );
self::run( $command, $assoc_args );
list( $stdout, $stderr, $exit_code ) = self::run( $command, $assoc_args, false );

if ( $exit_code ) {
WP_CLI::error( "Query failed: {$stderr}" );
}

// For UPDATE/DELETE queries, parse the output to get the number of rows affected.
if ( $is_update_or_delete ) {
$output_lines = explode( "\n", trim( $stdout ) );
$affected_rows = (int) trim( end( $output_lines ) );
WP_CLI::success( "Query succeeded. Rows affected: {$affected_rows}" );
} elseif ( ! empty( $stdout ) ) {
WP_CLI::line( $stdout );
}
}

/**
Expand Down
Loading