@@ -495,24 +495,38 @@ public function cli( $_, $assoc_args ) {
495495 * +---------+-----------------------+
496496 */
497497 public function query ( $ args , $ assoc_args ) {
498-
499498 $ command = sprintf ( '/usr/bin/env mysql%s --no-auto-rehash ' , $ this ->get_defaults_flag_string ( $ assoc_args ) );
500- WP_CLI ::debug ( "Running shell command: {$ command }" , 'db ' );
501-
502499 $ assoc_args ['database ' ] = DB_NAME ;
503-
504- // The query might come from STDIN.
500+
505501 if ( ! empty ( $ args ) ) {
506502 $ assoc_args ['execute ' ] = $ args [0 ];
507503 }
508-
504+
509505 if ( isset ( $ assoc_args ['execute ' ] ) ) {
510- // Ensure that the SQL mode is compatible with WPDB.
511506 $ assoc_args ['execute ' ] = $ this ->get_sql_mode_query ( $ assoc_args ) . $ assoc_args ['execute ' ];
512507 }
513-
514- WP_CLI ::debug ( 'Associative arguments: ' . json_encode ( $ assoc_args ), 'db ' );
515- self ::run ( $ command , $ assoc_args );
508+
509+ // Check if the query is an UPDATE or DELETE.
510+ if ( isset ( $ assoc_args ['execute ' ] ) && preg_match ( '/\b(UPDATE|DELETE)\b/i ' , $ assoc_args ['execute ' ] ) ) {
511+ // Append `SELECT ROW_COUNT()` to the query.
512+ $ assoc_args ['execute ' ] .= '; SELECT ROW_COUNT(); ' ;
513+ }
514+
515+ list ( $ stdout , $ stderr , $ exit_code ) = self ::run ( $ command , $ assoc_args , false );
516+
517+ if ( $ exit_code ) {
518+ WP_CLI ::error ( "Query failed: {$ stderr }" );
519+ }
520+
521+ // For UPDATE/DELETE queries, parse the output to get the number of rows affected.
522+ if ( isset ( $ assoc_args ['execute ' ] ) && preg_match ( '/\b(UPDATE|DELETE)\b/i ' , $ assoc_args ['execute ' ] ) ) {
523+ $ output_lines = explode ( "\n" , trim ( $ stdout ) );
524+ $ affected_rows = (int ) trim ( end ( $ output_lines ) );
525+ WP_CLI ::success ( "Query succeeded. Rows affected: {$ affected_rows }" );
526+ } else {
527+ WP_CLI ::log ( $ stdout );
528+ WP_CLI ::success ( 'Query executed successfully. ' );
529+ }
516530 }
517531
518532 /**
0 commit comments