Skip to content
Merged
Changes from 1 commit
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
Next Next commit
Update WPCLI update/delete query for affected rows
  • Loading branch information
karthick-murugan committed Feb 25, 2025
commit 99d44cb88010c5e823d6e18c3624e64d8b6c3330
34 changes: 24 additions & 10 deletions src/DB_Command.php
Original file line number Diff line number Diff line change
Expand Up @@ -495,24 +495,38 @@ public function cli( $_, $assoc_args ) {
* +---------+-----------------------+
*/
public function query( $args, $assoc_args ) {

Comment thread
mrsdizzie marked this conversation as resolved.
$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' );
Comment thread
swissspidy marked this conversation as resolved.

Comment thread
mrsdizzie marked this conversation as resolved.
$assoc_args['database'] = DB_NAME;

// The query might come from STDIN.
Comment thread
mrsdizzie marked this conversation as resolved.

if ( ! empty( $args ) ) {
$assoc_args['execute'] = $args[0];
}

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

WP_CLI::debug( 'Associative arguments: ' . json_encode( $assoc_args ), 'db' );
Comment thread
swissspidy marked this conversation as resolved.
self::run( $command, $assoc_args );

// Check if the query is an UPDATE or DELETE.
if ( isset( $assoc_args['execute'] ) && preg_match( '/\b(UPDATE|DELETE)\b/i', $assoc_args['execute'] ) ) {
// Append `SELECT ROW_COUNT()` to the query.
Comment thread
mrsdizzie marked this conversation as resolved.
Outdated
$assoc_args['execute'] .= '; SELECT ROW_COUNT();';
}

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.
Comment thread
mrsdizzie marked this conversation as resolved.
Outdated
if ( isset( $assoc_args['execute'] ) && preg_match( '/\b(UPDATE|DELETE)\b/i', $assoc_args['execute'] ) ) {
$output_lines = explode( "\n", trim( $stdout ) );
$affected_rows = (int) trim( end( $output_lines ) );
WP_CLI::success( "Query succeeded. Rows affected: {$affected_rows}" );
} else {
WP_CLI::log( $stdout );
WP_CLI::success( 'Query executed successfully.' );
}
}

/**
Expand Down