Skip to content

Commit 19b2555

Browse files
authored
Merge pull request #277 from karthick-murugan/wpcli/delet-update-changes
Add Affected Rows Count for queries that can modify data in wp db query
2 parents e9c4e8a + 7ecb070 commit 19b2555

File tree

2 files changed

+39
-1
lines changed

2 files changed

+39
-1
lines changed

Diff for: features/db.feature

+20
Original file line numberDiff line numberDiff line change
@@ -326,3 +326,23 @@ Feature: Perform database operations
326326
"""
327327
latin1_spanish_ci
328328
"""
329+
330+
Scenario: Row modifying queries should return the number of affected rows
331+
Given a WP install
332+
When I run `wp db query "UPDATE wp_users SET user_status = 1 WHERE ID = 1"`
333+
Then STDOUT should contain:
334+
"""
335+
Query succeeded. Rows affected: 1
336+
"""
337+
338+
When I run `wp db query "SELECT * FROM wp_users WHERE ID = 1"`
339+
Then STDOUT should not contain:
340+
"""
341+
Rows affected
342+
"""
343+
344+
When I run `wp db query "DELETE FROM wp_users WHERE ID = 1"`
345+
Then STDOUT should contain:
346+
"""
347+
Query succeeded. Rows affected: 1
348+
"""

Diff for: src/DB_Command.php

+19-1
Original file line numberDiff line numberDiff line change
@@ -511,8 +511,26 @@ public function query( $args, $assoc_args ) {
511511
$assoc_args['execute'] = $this->get_sql_mode_query( $assoc_args ) . $assoc_args['execute'];
512512
}
513513

514+
$is_row_modifying_query = isset( $assoc_args['execute'] ) && preg_match( '/\b(UPDATE|DELETE|INSERT|REPLACE|LOAD DATA)\b/i', $assoc_args['execute'] );
515+
516+
if ( $is_row_modifying_query ) {
517+
$assoc_args['execute'] .= '; SELECT ROW_COUNT();';
518+
}
519+
514520
WP_CLI::debug( 'Associative arguments: ' . json_encode( $assoc_args ), 'db' );
515-
self::run( $command, $assoc_args );
521+
list( $stdout, $stderr, $exit_code ) = self::run( $command, $assoc_args, false );
522+
523+
if ( $exit_code ) {
524+
WP_CLI::error( "Query failed: {$stderr}" );
525+
}
526+
527+
if ( $is_row_modifying_query ) {
528+
$output_lines = explode( "\n", trim( $stdout ) );
529+
$affected_rows = (int) trim( end( $output_lines ) );
530+
WP_CLI::success( "Query succeeded. Rows affected: {$affected_rows}" );
531+
} elseif ( ! empty( $stdout ) ) {
532+
WP_CLI::line( $stdout );
533+
}
516534
}
517535

518536
/**

0 commit comments

Comments
 (0)