From ea90c3842a921573e35734cc7f7a3033d88f16c9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Droz?= Date: Thu, 16 Oct 2025 22:43:41 -0300 Subject: [PATCH 01/41] Added --where flag to finely select rows aimed for replacement Added --revision / --no-revision Added --callback Reroll wp-cli#104, wp-cli#128, wp-cli#184 Fixes wp-cli#125, wp-cli#127, wp-cli#142 --- features/search-replace-new-options.feature | 513 ++++++++++++++++++++ src/Search_Replace_Command.php | 155 +++++- src/WP_CLI/SearchReplacer.php | 38 +- 3 files changed, 673 insertions(+), 33 deletions(-) create mode 100644 features/search-replace-new-options.feature diff --git a/features/search-replace-new-options.feature b/features/search-replace-new-options.feature new file mode 100644 index 00000000..c2c918a9 --- /dev/null +++ b/features/search-replace-new-options.feature @@ -0,0 +1,513 @@ +Feature: Test new search-replace options (--callback, --revisions, --where) + + @require-mysql + Scenario: Search replace with callback function + Given a WP install + And a callback-function.php file: + """ + ] + * : Perform the replacement on specific rows. Use semi-colon to + * specify multiple specifictions. + * format: [,table]:[column,...]:quoted-SQL-condition + * + * [--revisions] + * : Default true. + * If false, then identical to --where='posts::post_status="publish";postmeta::post_id IN (SELECT ID FROM {posts} WHERE post_status="publish")' + * * [--precise] * : Force the use of PHP (instead of SQL) which is more thorough, - * but slower. + * but slower. If --callback is specified, --precise is inferred. * * [--recurse-objects] * : Enable recursing into objects to replace strings. Defaults to true; @@ -193,6 +212,9 @@ class Search_Replace_Command extends WP_CLI_Command { * [--verbose] * : Prints rows to the console as they're updated. * + * [--callback=] + * : Runs a user-specified function on each string that contains . is passed as the second argument and the regex string as the third if it exists: call_user_func( 'callback', $data, $new, $search_regex ). + * * [--regex] * : Runs the search using a regular expression (without delimiters). * Warning: search-replace will take about 15-20x longer when using --regex. @@ -268,10 +290,10 @@ public function __invoke( $args, $assoc_args ) { $this->dry_run = Utils\get_flag_value( $assoc_args, 'dry-run', false ); $php_only = Utils\get_flag_value( $assoc_args, 'precise', false ); $this->recurse_objects = Utils\get_flag_value( $assoc_args, 'recurse-objects', true ); + $this->callback = Utils\get_flag_value( $assoc_args, 'callback', false ); $this->verbose = Utils\get_flag_value( $assoc_args, 'verbose', false ); $this->format = Utils\get_flag_value( $assoc_args, 'format' ); $this->regex = Utils\get_flag_value( $assoc_args, 'regex', false ); - $default_regex_delimiter = false; if ( null !== $this->regex ) { @@ -317,12 +339,30 @@ public function __invoke( $args, $assoc_args ) { $this->skip_columns = explode( ',', Utils\get_flag_value( $assoc_args, 'skip-columns', '' ) ); $this->skip_tables = explode( ',', Utils\get_flag_value( $assoc_args, 'skip-tables', '' ) ); $this->include_columns = array_filter( explode( ',', Utils\get_flag_value( $assoc_args, 'include-columns', '' ) ) ); + $this->where = $this->develop_where_specs( Utils\get_flag_value( $assoc_args, 'where' ) ); + $revisions = Utils\get_flag_value( $assoc_args, 'revisions', true ); + if ( ! $revisions ) { + $this->no_revision(); + } if ( $old === $new && ! $this->regex ) { WP_CLI::warning( "Replacement value '{$old}' is identical to search value '{$new}'. Skipping operation." ); exit; } + if ( $this->callback ) { + // We must load WordPress as the function may depend on it. + WP_CLI::get_runner()->load_wordpress(); + if ( ! function_exists( $this->callback ) ) { + WP_CLI::error( 'The callback function does not exist. Skipping operation.' ); + } + + if ( false === $php_only ) { + WP_CLI::error( 'PHP is required to execute a callback function. --no-precise cannot be set.' ); + } + $php_only = true; + } + $export = Utils\get_flag_value( $assoc_args, 'export' ); if ( null !== $export ) { if ( $this->dry_run ) { @@ -413,6 +453,28 @@ public function __invoke( $args, $assoc_args ) { // Get table names based on leftover $args or supplied $assoc_args $tables = Utils\wp_get_table_names( $args, $assoc_args ); + // If a custom `where` conditions were passed, then exclude other tables from processing. + if ( $this->where ) { + $tables = array_intersect( $tables, array_keys( $this->where ) ); + $columns = []; + foreach ( array_values( $this->where ) as $_ => $cols ) { + $columns = array_merge( $columns, array_keys( $cols ) ); + } + if ( $columns ) { + if ( in_array( '*', $columns ) ) { + $columns = array_filter( + $columns, + function ( $e ) { + return $e !== '*'; + } + ); + if ( $this->include_columns ) { + WP_CLI::warning( 'Column-catch was passed to --where while. But --include-columns will still restrict replacements to columns: ' . implode( ',', $this->include_columns ) ); + } + } + $this->include_columns = array_merge( $this->include_columns, $columns ); + } + } foreach ( $tables as $table ) { @@ -467,6 +529,8 @@ public function __invoke( $args, $assoc_args ) { continue; } + $clauses = $this->get_clauses( $table, $col ); + if ( $this->verbose && 'count' !== $this->format ) { $this->start_time = microtime( true ); WP_CLI::log( sprintf( 'Checking: %s.%s', $table, $col ) ); @@ -478,8 +542,9 @@ public function __invoke( $args, $assoc_args ) { $col_sql = self::esc_sql_ident( $col ); $wpdb->last_error = ''; + $where = $clauses ? ' AND ' . implode( ' AND ', $clauses ) : ''; // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- escaped through self::esc_sql_ident - $serial_row = $wpdb->get_row( "SELECT * FROM $table_sql WHERE $col_sql REGEXP '^[aiO]:[1-9]' LIMIT 1" ); + $serial_row = $wpdb->get_row( "SELECT * FROM $table_sql WHERE $col_sql REGEXP '^[aiO]:[1-9]' $where LIMIT 1" ); // When the regex triggers an error, we should fall back to PHP if ( false !== strpos( $wpdb->last_error, 'ERROR 1139' ) ) { @@ -489,10 +554,10 @@ public function __invoke( $args, $assoc_args ) { if ( $php_only || $this->regex || null !== $serial_row ) { $type = 'PHP'; - $count = $this->php_handle_col( $col, $primary_keys, $table, $old, $new ); + $count = $this->php_handle_col( $col, $primary_keys, $table, $old, $new, $clauses ); } else { $type = 'SQL'; - $count = $this->sql_handle_col( $col, $primary_keys, $table, $old, $new ); + $count = $this->sql_handle_col( $col, $primary_keys, $table, $old, $new, $clauses ); } if ( $this->report && ( $count || ! $this->report_changed_only ) ) { @@ -563,7 +628,15 @@ private function php_export_table( $table, $old, $new ) { foreach ( $all_columns as $col ) { $value = $row->$col; if ( $value && ! in_array( $col, $primary_keys, true ) && ! in_array( $col, $this->skip_columns, true ) ) { - $new_value = $replacer->run( $value ); + $new_value = $replacer->run( + $value, + false, + [ + 'table' => $table, + 'col' => $col, + 'key' => $primary_keys, + ] + ); if ( $new_value !== $value ) { ++$col_counts[ $col ]; $value = $new_value; @@ -596,24 +669,26 @@ private function php_export_table( $table, $old, $new ) { return array( $table_report, $total_rows ); } - private function sql_handle_col( $col, $primary_keys, $table, $old, $new ) { + private function sql_handle_col( $col, $primary_keys, $table, $old, $new, $clauses ) { global $wpdb; $table_sql = self::esc_sql_ident( $table ); $col_sql = self::esc_sql_ident( $col ); if ( $this->dry_run ) { if ( $this->log_handle ) { - $count = $this->log_sql_diff( $col, $primary_keys, $table, $old, $new ); + $count = $this->log_sql_diff( $col, $primary_keys, $table, $old, $new, $clauses ); } else { + $where = $clauses ? ' AND ' . implode( ' AND ', $clauses ) : ''; // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- escaped through self::esc_sql_ident - $count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT($col_sql) FROM $table_sql WHERE $col_sql LIKE BINARY %s;", '%' . self::esc_like( $old ) . '%' ) ); + $count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT($col_sql) FROM $table_sql WHERE $col_sql LIKE BINARY %s $where;", '%' . self::esc_like( $old ) . '%' ) ); } } else { if ( $this->log_handle ) { - $this->log_sql_diff( $col, $primary_keys, $table, $old, $new ); + $this->log_sql_diff( $col, $primary_keys, $table, $old, $new, $clauses ); } + $where = $clauses ? ' WHERE ' . implode( ' AND ', $clauses ) : ''; // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- escaped through self::esc_sql_ident - $count = $wpdb->query( $wpdb->prepare( "UPDATE $table_sql SET $col_sql = REPLACE($col_sql, %s, %s);", $old, $new ) ); + $count = $wpdb->query( $wpdb->prepare( "UPDATE $table_sql SET $col_sql = REPLACE($col_sql, %s, %s) $where;", $old, $new ) ); } if ( $this->verbose && 'table' === $this->format ) { @@ -623,22 +698,21 @@ private function sql_handle_col( $col, $primary_keys, $table, $old, $new ) { return $count; } - private function php_handle_col( $col, $primary_keys, $table, $old, $new ) { + private function php_handle_col( $col, $primary_keys, $table, $old, $new, $additional_where ) { global $wpdb; $count = 0; - $replacer = new SearchReplacer( $old, $new, $this->recurse_objects, $this->regex, $this->regex_flags, $this->regex_delimiter, null !== $this->log_handle, $this->regex_limit ); + $replacer = new SearchReplacer( $old, $new, $this->recurse_objects, $this->regex, $this->regex_flags, $this->regex_delimiter, null !== $this->log_handle, $this->regex_limit, $this->callback ); $table_sql = self::esc_sql_ident( $table ); $col_sql = self::esc_sql_ident( $col ); - $base_key_condition = ''; - $where_key = ''; + $base_key_condition = $additional_where; if ( ! $this->regex ) { - $base_key_condition = "$col_sql" . $wpdb->prepare( ' LIKE BINARY %s', '%' . self::esc_like( $old ) . '%' ); - $where_key = "WHERE $base_key_condition"; + $base_key_condition[] = "$col_sql" . $wpdb->prepare( ' LIKE BINARY %s', '%' . self::esc_like( $old ) . '%' ); } + $where_key = $base_key_condition ? ' WHERE ' . implode( ' AND ', $base_key_condition ) : ''; $escaped_primary_keys = self::esc_sql_ident( $primary_keys ); $primary_keys_sql = implode( ',', $escaped_primary_keys ); $order_by_keys = array_map( @@ -726,13 +800,8 @@ static function ( $key ) { $next_key_conditions[] = '( ' . implode( ' AND ', $next_key_subconditions ) . ' )'; } - $where_key_conditions = array(); - if ( $base_key_condition ) { - $where_key_conditions[] = $base_key_condition; - } - $where_key_conditions[] = '( ' . implode( ' OR ', $next_key_conditions ) . ' )'; - - $where_key = 'WHERE ' . implode( ' AND ', $where_key_conditions ); + $base_key_condition[] = '( ' . implode( ' OR ', $next_key_conditions ) . ' )'; + $where_key = 'WHERE ' . implode( ' AND ', $base_key_condition ); } if ( $this->verbose && 'table' === $this->format ) { @@ -955,7 +1024,7 @@ private function get_colors( $assoc_args, $colors ) { * @param string $new New value to replace the old value with. * @return int Count of changed rows. */ - private function log_sql_diff( $col, $primary_keys, $table, $old, $new ) { + private function log_sql_diff( $col, $primary_keys, $table, $old, $new, $clauses ) { global $wpdb; if ( $primary_keys ) { $esc_primary_keys = implode( ', ', self::esc_sql_ident( $primary_keys ) ); @@ -966,9 +1035,10 @@ private function log_sql_diff( $col, $primary_keys, $table, $old, $new ) { $table_sql = self::esc_sql_ident( $table ); $col_sql = self::esc_sql_ident( $col ); + $where_sql = $clauses ? ' AND ' . implode( ' AND ', $clauses ) : ''; // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- escaped through self::esc_sql_ident - $results = $wpdb->get_results( $wpdb->prepare( "SELECT {$primary_keys_sql}{$col_sql} FROM {$table_sql} WHERE {$col_sql} LIKE BINARY %s", '%' . self::esc_like( $old ) . '%' ), ARRAY_N ); + $results = $wpdb->get_results( $wpdb->prepare( "SELECT {$primary_keys_sql}{$col_sql} FROM {$table_sql} WHERE {$col_sql} LIKE BINARY %s {$where_sql}", '%' . self::esc_like( $old ) . '%' ), ARRAY_N ); if ( empty( $results ) ) { return 0; @@ -1149,4 +1219,37 @@ private function log_write( $col, $keys, $table, $old_bits, $new_bits ) { fwrite( $this->log_handle, "{$table_column_id_log}\n{$old_log}\n{$new_log}\n" ); } + + public function develop_where_specs( $str_specs ) { + global $wpdb; + $specs = array_filter( explode( ';', $str_specs ) ); + $clauses = []; + foreach ( $specs as $spec ) { + list( $tables, $cols, $conditions ) = explode( ':', $spec, 3 ); + $tables = array_filter( explode( ',', $tables ) ); + $cols = array_filter( explode( ',', $cols ) ) ? : [ '*' ]; + foreach ( $tables as $table ) { + foreach ( $cols as $col ) { + $clauses[ empty( $wpdb->{$table} ) ? $table : $wpdb->{$table} ][ $col ][] = $conditions; + } + } + } + + return $clauses; + } + + public function no_revision() { + global $wpdb; + $this->where[ $wpdb->posts ]['*'][] = self::esc_sql_ident( 'post_status' ) . '=' . self::esc_sql_value( 'publish' ); + $this->where[ $wpdb->postmeta ]['*'][] = self::esc_sql_ident( 'post_id' ) . ' IN ( SELECT ID FROM ' . $wpdb->posts . ' WHERE ' . self::esc_sql_ident( 'post_status' ) . '=' . self::esc_sql_value( 'publish' ) . ')'; + } + + public function get_clauses( $table, $column = null ) { + return array_filter( + array_merge( + $this->where[ $table ][ $column ] ?? [], + $this->where[ $table ]['*'] ?? [] + ) + ); + } } diff --git a/src/WP_CLI/SearchReplacer.php b/src/WP_CLI/SearchReplacer.php index 8c5ee951..a4bb8108 100644 --- a/src/WP_CLI/SearchReplacer.php +++ b/src/WP_CLI/SearchReplacer.php @@ -67,7 +67,7 @@ class SearchReplacer { * @param bool $logging Whether logging. * @param integer $regex_limit The maximum possible replacements for each pattern in each subject string. */ - public function __construct( $from, $to, $recurse_objects = false, $regex = false, $regex_flags = '', $regex_delimiter = '/', $logging = false, $regex_limit = -1 ) { + public function __construct( $from, $to, $recurse_objects = false, $regex = false, $regex_flags = '', $regex_delimiter = '/', $logging = false, $regex_limit = -1, $callback = false ) { $this->from = $from; $this->to = $to; $this->recurse_objects = $recurse_objects; @@ -76,6 +76,7 @@ public function __construct( $from, $to, $recurse_objects = false, $regex = fals $this->regex_delimiter = $regex_delimiter; $this->regex_limit = $regex_limit; $this->logging = $logging; + $this->callback = $callback; $this->clear_log_data(); // Get the XDebug nesting level. Will be zero (no limit) if no value is set @@ -92,15 +93,15 @@ public function __construct( $from, $to, $recurse_objects = false, $regex = fals * * @return array The original array with all elements replaced as needed. */ - public function run( $data, $serialised = false ) { - return $this->run_recursively( $data, $serialised ); + public function run( $data, $serialised = false, $opts = [] ) { + return $this->run_recursively( $data, $serialised, 0, [], $opts ); } /** * @param int $recursion_level Current recursion depth within the original data. * @param array $visited_data Data that has been seen in previous recursion iterations. */ - private function run_recursively( $data, $serialised, $recursion_level = 0, $visited_data = array() ) { + private function run_recursively( $data, $serialised, $recursion_level = 0, $visited_data = array(), $opts = [] ) { // some unseriliased data cannot be re-serialised eg. SimpleXMLElements try { @@ -192,7 +193,11 @@ private function run_recursively( $data, $serialised, $recursion_level = 0, $vis $search_regex .= $this->regex_delimiter; $search_regex .= $this->regex_flags; - $result = preg_replace( $search_regex, $this->to, $data, $this->regex_limit ); + if ( $this->callback ) { + $result = \call_user_func( $this->callback, $data, $this->to, $search_regex, $opts ); + } else { + $result = preg_replace( $search_regex, $this->to, $data, $this->regex_limit ); + } if ( null === $result || PREG_NO_ERROR !== preg_last_error() ) { \WP_CLI::warning( sprintf( @@ -201,10 +206,29 @@ private function run_recursively( $data, $serialised, $recursion_level = 0, $vis ) ); } - $data = $result; + } elseif ( $this->callback ) { + if ( strpos( $data, $this->from ) !== false ) { + $result = \call_user_func( $this->callback, $data, $this->to, $opts ); + } else { + // We can skip calling the function here. It must still be set so we don't remove text. + $result = $data; + } } else { - $data = str_replace( $this->from, $this->to, $data ); + $result = str_replace( $this->from, $this->to, $data ); + } + + if ( $this->callback ) { + if ( false === $result ) { + WP_CLI::error( 'The callback function return false. Stopping operation.' ); + } elseif ( is_wp_error( $result ) ) { + $message = $errors->get_error_message(); + WP_CLI::error( 'The callback function threw an error. Stopping operation. ' . $message ); + } elseif ( ! is_string( $result ) ) { + WP_CLI::error( 'The callback function did not return a string. Stopping operation.' ); + } } + + $data = $result; if ( $this->logging && $old_data !== $data ) { $this->log_data[] = $old_data; } From 0071c869a415f8208c4f8f87f5a0a7cfcbbe27dc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Droz?= Date: Sun, 19 Oct 2025 00:55:29 -0300 Subject: [PATCH 02/41] phpcbf + features split --- features/search-replace-callback.feature | 129 ++++++++++ features/search-replace-revisions.feature | 106 ++++++++ ...s.feature => search-replace-where.feature} | 235 +----------------- src/Search_Replace_Command.php | 26 +- 4 files changed, 249 insertions(+), 247 deletions(-) create mode 100644 features/search-replace-callback.feature create mode 100644 features/search-replace-revisions.feature rename features/{search-replace-new-options.feature => search-replace-where.feature} (55%) diff --git a/features/search-replace-callback.feature b/features/search-replace-callback.feature new file mode 100644 index 00000000..cc1df240 --- /dev/null +++ b/features/search-replace-callback.feature @@ -0,0 +1,129 @@ +Feature: Test search-replace --callback option + + @require-mysql + Scenario: Search replace with callback function + Given a WP install + And a callback-function.php file: + """ + dry_run = Utils\get_flag_value( $assoc_args, 'dry-run', false ); - $php_only = Utils\get_flag_value( $assoc_args, 'precise', false ); - $this->recurse_objects = Utils\get_flag_value( $assoc_args, 'recurse-objects', true ); - $this->callback = Utils\get_flag_value( $assoc_args, 'callback', false ); - $this->verbose = Utils\get_flag_value( $assoc_args, 'verbose', false ); - $this->format = Utils\get_flag_value( $assoc_args, 'format' ); - $this->regex = Utils\get_flag_value( $assoc_args, 'regex', false ); + $old = array_shift( $args ); + $new = array_shift( $args ); + $total = 0; + $report = array(); + $this->dry_run = Utils\get_flag_value( $assoc_args, 'dry-run', false ); + $php_only = Utils\get_flag_value( $assoc_args, 'precise', false ); + $this->recurse_objects = Utils\get_flag_value( $assoc_args, 'recurse-objects', true ); + $this->callback = Utils\get_flag_value( $assoc_args, 'callback', false ); + $this->verbose = Utils\get_flag_value( $assoc_args, 'verbose', false ); + $this->format = Utils\get_flag_value( $assoc_args, 'format' ); + $this->regex = Utils\get_flag_value( $assoc_args, 'regex', false ); $default_regex_delimiter = false; if ( null !== $this->regex ) { @@ -461,11 +461,11 @@ public function __invoke( $args, $assoc_args ) { $columns = array_merge( $columns, array_keys( $cols ) ); } if ( $columns ) { - if ( in_array( '*', $columns ) ) { + if ( in_array( '*', $columns, true ) ) { $columns = array_filter( $columns, function ( $e ) { - return $e !== '*'; + return '*' !== $e; } ); if ( $this->include_columns ) { From 82cbe76d437bc2727428726678e2f6413caa34ef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Droz?= Date: Sun, 19 Oct 2025 01:03:25 -0300 Subject: [PATCH 03/41] phpstan --- src/WP_CLI/SearchReplacer.php | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/src/WP_CLI/SearchReplacer.php b/src/WP_CLI/SearchReplacer.php index a4bb8108..4c8e17b3 100644 --- a/src/WP_CLI/SearchReplacer.php +++ b/src/WP_CLI/SearchReplacer.php @@ -57,6 +57,11 @@ class SearchReplacer { */ private $max_recursion; + /** + * @var bool + */ + private $callback; + /** * @param string $from String we're looking to replace. * @param string $to What we want it to be replaced with. @@ -219,12 +224,12 @@ private function run_recursively( $data, $serialised, $recursion_level = 0, $vis if ( $this->callback ) { if ( false === $result ) { - WP_CLI::error( 'The callback function return false. Stopping operation.' ); + \WP_CLI::error( 'The callback function return false. Stopping operation.' ); } elseif ( is_wp_error( $result ) ) { $message = $errors->get_error_message(); - WP_CLI::error( 'The callback function threw an error. Stopping operation. ' . $message ); + \WP_CLI::error( 'The callback function threw an error. Stopping operation. ' . $message ); } elseif ( ! is_string( $result ) ) { - WP_CLI::error( 'The callback function did not return a string. Stopping operation.' ); + \WP_CLI::error( 'The callback function did not return a string. Stopping operation.' ); } } From faef60ff1ff43ff8957000f9b26d8049e852a193 Mon Sep 17 00:00:00 2001 From: Pascal Birchler Date: Tue, 4 Nov 2025 19:10:28 +0100 Subject: [PATCH 04/41] PHPStan fix --- src/Search_Replace_Command.php | 2 +- src/WP_CLI/SearchReplacer.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Search_Replace_Command.php b/src/Search_Replace_Command.php index a94afd3f..fa518aa2 100644 --- a/src/Search_Replace_Command.php +++ b/src/Search_Replace_Command.php @@ -120,7 +120,7 @@ class Search_Replace_Command extends WP_CLI_Command { private $start_time; /** - * @var string|false + * @var array>|false */ private $where; diff --git a/src/WP_CLI/SearchReplacer.php b/src/WP_CLI/SearchReplacer.php index 4c8e17b3..76602944 100644 --- a/src/WP_CLI/SearchReplacer.php +++ b/src/WP_CLI/SearchReplacer.php @@ -226,7 +226,7 @@ private function run_recursively( $data, $serialised, $recursion_level = 0, $vis if ( false === $result ) { \WP_CLI::error( 'The callback function return false. Stopping operation.' ); } elseif ( is_wp_error( $result ) ) { - $message = $errors->get_error_message(); + $message = $result->get_error_message(); \WP_CLI::error( 'The callback function threw an error. Stopping operation. ' . $message ); } elseif ( ! is_string( $result ) ) { \WP_CLI::error( 'The callback function did not return a string. Stopping operation.' ); From e84713815c43b9c960485284d963cae72f6485b1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Droz?= Date: Tue, 11 Nov 2025 14:57:04 -0300 Subject: [PATCH 05/41] Update src/Search_Replace_Command.php Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- src/Search_Replace_Command.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Search_Replace_Command.php b/src/Search_Replace_Command.php index fa518aa2..c963dca0 100644 --- a/src/Search_Replace_Command.php +++ b/src/Search_Replace_Command.php @@ -469,7 +469,7 @@ function ( $e ) { } ); if ( $this->include_columns ) { - WP_CLI::warning( 'Column-catch was passed to --where while. But --include-columns will still restrict replacements to columns: ' . implode( ',', $this->include_columns ) ); + WP_CLI::warning( 'Column wildcard (*) was passed to --where. But --include-columns will still restrict replacements to columns: ' . implode( ',', $this->include_columns ) ); } } $this->include_columns = array_merge( $this->include_columns, $columns ); From 76c2296aa665293f49fd06f7bb7118aa66a5fbc1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Droz?= Date: Tue, 11 Nov 2025 14:58:00 -0300 Subject: [PATCH 06/41] Update src/Search_Replace_Command.php Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- src/Search_Replace_Command.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Search_Replace_Command.php b/src/Search_Replace_Command.php index c963dca0..8bb0bc04 100644 --- a/src/Search_Replace_Command.php +++ b/src/Search_Replace_Command.php @@ -194,7 +194,7 @@ class Search_Replace_Command extends WP_CLI_Command { * * [--where=] * : Perform the replacement on specific rows. Use semi-colon to - * specify multiple specifictions. + * specify multiple specifications. * format:
[,table]:[column,...]:quoted-SQL-condition * * [--revisions] From c4fe56cbc5fccf3cab3afeb7422cc96976ede0f4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Droz?= Date: Tue, 11 Nov 2025 14:58:19 -0300 Subject: [PATCH 07/41] Update src/Search_Replace_Command.php Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- src/Search_Replace_Command.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Search_Replace_Command.php b/src/Search_Replace_Command.php index 8bb0bc04..88868a16 100644 --- a/src/Search_Replace_Command.php +++ b/src/Search_Replace_Command.php @@ -1238,7 +1238,7 @@ public function develop_where_specs( $str_specs ) { return $clauses; } - public function no_revision() { + private function no_revision() { global $wpdb; $this->where[ $wpdb->posts ]['*'][] = self::esc_sql_ident( 'post_status' ) . '=' . self::esc_sql_value( 'publish' ); $this->where[ $wpdb->postmeta ]['*'][] = self::esc_sql_ident( 'post_id' ) . ' IN ( SELECT ID FROM ' . $wpdb->posts . ' WHERE ' . self::esc_sql_ident( 'post_status' ) . '=' . self::esc_sql_value( 'publish' ) . ')'; From 735fedfa5c77c79b8eb49253a0f2412d64622a4b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Droz?= Date: Tue, 11 Nov 2025 14:58:38 -0300 Subject: [PATCH 08/41] Update src/Search_Replace_Command.php Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- src/Search_Replace_Command.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Search_Replace_Command.php b/src/Search_Replace_Command.php index 88868a16..ffb85e15 100644 --- a/src/Search_Replace_Command.php +++ b/src/Search_Replace_Command.php @@ -1220,7 +1220,7 @@ private function log_write( $col, $keys, $table, $old_bits, $new_bits ) { fwrite( $this->log_handle, "{$table_column_id_log}\n{$old_log}\n{$new_log}\n" ); } - public function develop_where_specs( $str_specs ) { + private function develop_where_specs( $str_specs ) { global $wpdb; $specs = array_filter( explode( ';', $str_specs ) ); $clauses = []; From cf89ef581fee3fc2deba7fa3687c28623a312361 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Droz?= Date: Tue, 11 Nov 2025 14:58:53 -0300 Subject: [PATCH 09/41] Update src/Search_Replace_Command.php Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- src/Search_Replace_Command.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Search_Replace_Command.php b/src/Search_Replace_Command.php index ffb85e15..3219ea52 100644 --- a/src/Search_Replace_Command.php +++ b/src/Search_Replace_Command.php @@ -1244,7 +1244,7 @@ private function no_revision() { $this->where[ $wpdb->postmeta ]['*'][] = self::esc_sql_ident( 'post_id' ) . ' IN ( SELECT ID FROM ' . $wpdb->posts . ' WHERE ' . self::esc_sql_ident( 'post_status' ) . '=' . self::esc_sql_value( 'publish' ) . ')'; } - public function get_clauses( $table, $column = null ) { + private function get_clauses( $table, $column = null ) { return array_filter( array_merge( $this->where[ $table ][ $column ] ?? [], From 8b45d7e495d25da06c8e8a1e0e3870d7802d5cd7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Droz?= Date: Tue, 11 Nov 2025 15:01:35 -0300 Subject: [PATCH 10/41] Update src/WP_CLI/SearchReplacer.php Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- src/WP_CLI/SearchReplacer.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/WP_CLI/SearchReplacer.php b/src/WP_CLI/SearchReplacer.php index 76602944..7264b394 100644 --- a/src/WP_CLI/SearchReplacer.php +++ b/src/WP_CLI/SearchReplacer.php @@ -58,7 +58,9 @@ class SearchReplacer { private $max_recursion; /** - * @var bool + * @var callable|string|bool Callback function or method to be invoked during search/replace operations. + * If set to a callable or a string (function name), this will be called for each replacement. + * If false, no callback is used. */ private $callback; From eb1cc917d093a8267c27b7bf086ca6c703bb2080 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Droz?= Date: Tue, 11 Nov 2025 15:02:54 -0300 Subject: [PATCH 11/41] Update src/Search_Replace_Command.php Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- src/Search_Replace_Command.php | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/Search_Replace_Command.php b/src/Search_Replace_Command.php index 3219ea52..6d53035a 100644 --- a/src/Search_Replace_Command.php +++ b/src/Search_Replace_Command.php @@ -120,6 +120,12 @@ class Search_Replace_Command extends WP_CLI_Command { private $start_time; /** + * WHERE clause specifications for filtering rows during search-replace operations. + * + * The array is structured as [table_name => [column_name => [values]]], where each + * table name maps to an array of column names, each of which maps to an array of + * string values to match in the WHERE clause. If set to false, no filtering is applied. + * * @var array>|false */ private $where; From 21c0b81839d1ad5243ab13efd12463c6df70469b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Droz?= Date: Tue, 11 Nov 2025 15:10:53 -0300 Subject: [PATCH 12/41] Update src/WP_CLI/SearchReplacer.php Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- src/WP_CLI/SearchReplacer.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/WP_CLI/SearchReplacer.php b/src/WP_CLI/SearchReplacer.php index 7264b394..80e9b5af 100644 --- a/src/WP_CLI/SearchReplacer.php +++ b/src/WP_CLI/SearchReplacer.php @@ -215,7 +215,7 @@ private function run_recursively( $data, $serialised, $recursion_level = 0, $vis } } elseif ( $this->callback ) { if ( strpos( $data, $this->from ) !== false ) { - $result = \call_user_func( $this->callback, $data, $this->to, $opts ); + $result = \call_user_func( $this->callback, $data, $this->to, null, $opts ); } else { // We can skip calling the function here. It must still be set so we don't remove text. $result = $data; From 05041ab4da57455bfd17a5de91baa07e00f4c9c6 Mon Sep 17 00:00:00 2001 From: Pascal Birchler Date: Tue, 11 Nov 2025 23:05:18 +0100 Subject: [PATCH 13/41] Add some docblocks --- src/Search_Replace_Command.php | 111 +++++++++++++++++++++++++++------ src/WP_CLI/SearchReplacer.php | 16 +++-- 2 files changed, 103 insertions(+), 24 deletions(-) diff --git a/src/Search_Replace_Command.php b/src/Search_Replace_Command.php index 6d53035a..508c0137 100644 --- a/src/Search_Replace_Command.php +++ b/src/Search_Replace_Command.php @@ -611,6 +611,14 @@ function ( $e ) { } } + /** + * Exports a table's data with search and replace. + * + * @param string $table The table to export. + * @param string $old The string to search for. + * @param string $new The string to replace with. + * @return array A tuple containing the report array and the total number of rows. + */ private function php_export_table( $table, $old, $new ) { list( $primary_keys, $columns, $all_columns ) = self::get_columns( $table ); @@ -675,6 +683,17 @@ private function php_export_table( $table, $old, $new ) { return array( $table_report, $total_rows ); } + /** + * Performs a search and replace on a column using SQL. + * + * @param string $col The column to perform the search-replace on. + * @param string[] $primary_keys The primary keys of the table. + * @param string $table The table to perform the search-replace on. + * @param string $old The string to search for. + * @param string $new The string to replace with. + * @param string[] $clauses The WHERE clauses to apply. + * @return int The number of replacements made. + */ private function sql_handle_col( $col, $primary_keys, $table, $old, $new, $clauses ) { global $wpdb; @@ -704,6 +723,17 @@ private function sql_handle_col( $col, $primary_keys, $table, $old, $new, $claus return $count; } + /** + * Performs a search and replace on a column using PHP. + * + * @param string $col The column to perform the search-replace on. + * @param string[] $primary_keys The primary keys of the table. + * @param string $table The table to perform the search-replace on. + * @param string $old The string to search for. + * @param string $new The string to replace with. + * @param string[] $additional_where The additional WHERE clauses to apply. + * @return int The number of replacements made. + */ private function php_handle_col( $col, $primary_keys, $table, $old, $new, $additional_where ) { global $wpdb; @@ -818,6 +848,12 @@ static function ( $key ) { return $count; } + /** + * Writes a set of rows to the export file as SQL INSERT statements. + * + * @param string $table The table to write the rows for. + * @param array $rows The rows to write. + */ private function write_sql_row_fields( $table, $rows ) { global $wpdb; @@ -888,6 +924,12 @@ private function write_sql_row_fields( $table, $rows ) { } } + /** + * Gets the primary keys, text columns, and all columns for a table. + * + * @param string $table The table to get the columns for. + * @return array A tuple containing the primary keys, text columns, and all columns. + */ private static function get_columns( $table ) { global $wpdb; @@ -915,6 +957,12 @@ private static function get_columns( $table ) { return array( $primary_keys, $text_columns, $all_columns ); } + /** + * Checks if a column type is a text type. + * + * @param string $type The column type to check. + * @return bool Whether the column type is a text type. + */ private static function is_text_col( $type ) { foreach ( array( 'text', 'varchar' ) as $token ) { if ( false !== stripos( $type, $token ) ) { @@ -925,6 +973,12 @@ private static function is_text_col( $type ) { return false; } + /** + * Escapes a string for a MySQL LIKE statement. + * + * @param string $old The string to escape. + * @return string The escaped string. + */ private static function esc_like( $old ) { global $wpdb; @@ -1020,14 +1074,15 @@ private function get_colors( $assoc_args, $colors ) { return $colors; } - /* + /** * Logs the difference between old match and new replacement for SQL replacement. * - * @param string $col Column being processed. - * @param array $primary_keys Primary keys for table. - * @param string $table Table being processed. - * @param string $old Old value to match. - * @param string $new New value to replace the old value with. + * @param string $col Column being processed. + * @param string[] $primary_keys Primary keys for table. + * @param string $table Table being processed. + * @param string $old Old value to match. + * @param string $new New value to replace the old value with. + * @param string[] $clauses The WHERE clauses to apply. * @return int Count of changed rows. */ private function log_sql_diff( $col, $primary_keys, $table, $old, $new, $clauses ) { @@ -1062,15 +1117,15 @@ private function log_sql_diff( $col, $primary_keys, $table, $old, $new, $clauses return count( $results ); } - /* + /** * Logs the difference between old matches and new replacements at the end of a PHP (regex) replacement of a database row. * - * @param string $col Column being processed. - * @param array $keys Associative array (or object) of primary key names and their values for the row being processed. - * @param string $table Table being processed. - * @param string $old Old value to match. - * @param string $new New value to replace the old value with. - * @param array $log_data Array of data strings before replacements. + * @param string $col Column being processed. + * @param array|object $keys Associative array (or object) of primary key names and their values for the row being processed. + * @param string $table Table being processed. + * @param string $old Old value to match. + * @param string $new New value to replace the old value with. + * @param string[] $log_data Array of data strings before replacements. */ private function log_php_diff( $col, $keys, $table, $old, $new, $log_data ) { if ( $this->regex ) { @@ -1196,14 +1251,14 @@ static function ( $m ) use ( $matches ) { return array( $old_bits, $new_bits ); } - /* + /** * Outputs the log strings. * - * @param string $col Column being processed. - * @param array $keys Associative array (or object) of primary key names and their values for the row being processed. - * @param string $table Table being processed. - * @param array $old_bits Array of old match log strings. - * @param array $new_bits Array of new replacement log strings. + * @param string $col Column being processed. + * @param array|object $keys Associative array (or object) of primary key names and their values for the row being processed. + * @param string $table Table being processed. + * @param string[] $old_bits Array of old match log strings. + * @param string[] $new_bits Array of new replacement log strings. */ private function log_write( $col, $keys, $table, $old_bits, $new_bits ) { if ( ! $this->log_handle ) { @@ -1226,9 +1281,15 @@ private function log_write( $col, $keys, $table, $old_bits, $new_bits ) { fwrite( $this->log_handle, "{$table_column_id_log}\n{$old_log}\n{$new_log}\n" ); } + /** + * Develops the WHERE specifications from a string. + * + * @param string|null $str_specs The string of WHERE specifications. + * @return array The WHERE specifications as an array. + */ private function develop_where_specs( $str_specs ) { global $wpdb; - $specs = array_filter( explode( ';', $str_specs ) ); + $specs = array_filter( explode( ';', (string) $str_specs ) ); $clauses = []; foreach ( $specs as $spec ) { list( $tables, $cols, $conditions ) = explode( ':', $spec, 3 ); @@ -1244,12 +1305,22 @@ private function develop_where_specs( $str_specs ) { return $clauses; } + /** + * Excludes revisions from the search-replace operation. + */ private function no_revision() { global $wpdb; $this->where[ $wpdb->posts ]['*'][] = self::esc_sql_ident( 'post_status' ) . '=' . self::esc_sql_value( 'publish' ); $this->where[ $wpdb->postmeta ]['*'][] = self::esc_sql_ident( 'post_id' ) . ' IN ( SELECT ID FROM ' . $wpdb->posts . ' WHERE ' . self::esc_sql_ident( 'post_status' ) . '=' . self::esc_sql_value( 'publish' ) . ')'; } + /** + * Gets the WHERE clauses for a given table and column. + * + * @param string $table The table to get the clauses for. + * @param string|null $column The column to get the clauses for. + * @return string[] The WHERE clauses. + */ private function get_clauses( $table, $column = null ) { return array_filter( array_merge( diff --git a/src/WP_CLI/SearchReplacer.php b/src/WP_CLI/SearchReplacer.php index 80e9b5af..204f256f 100644 --- a/src/WP_CLI/SearchReplacer.php +++ b/src/WP_CLI/SearchReplacer.php @@ -73,6 +73,7 @@ class SearchReplacer { * @param string $regex_delimiter Delimiter for regular expression. * @param bool $logging Whether logging. * @param integer $regex_limit The maximum possible replacements for each pattern in each subject string. + * @param callable|string|false $callback The callback function to invoke. */ public function __construct( $from, $to, $recurse_objects = false, $regex = false, $regex_flags = '', $regex_delimiter = '/', $logging = false, $regex_limit = -1, $callback = false ) { $this->from = $from; @@ -97,16 +98,23 @@ public function __construct( $from, $to, $recurse_objects = false, $regex = fals * * @param array|string $data The data to operate on. * @param bool $serialised Does the value of $data need to be unserialized? + * @param array $opts Options for the callback. * - * @return array The original array with all elements replaced as needed. + * @return array|string The original array with all elements replaced as needed. */ public function run( $data, $serialised = false, $opts = [] ) { return $this->run_recursively( $data, $serialised, 0, [], $opts ); } /** - * @param int $recursion_level Current recursion depth within the original data. - * @param array $visited_data Data that has been seen in previous recursion iterations. + * The main workhorse of the run method. + * + * @param mixed $data The data to operate on. + * @param bool $serialised Does the value of $data need to be unserialized? + * @param int $recursion_level Current recursion depth within the original data. + * @param array $visited_data Data that has been seen in previous recursion iterations. + * @param array $opts Options for the callback. + * @return mixed The original data with all elements replaced as needed. */ private function run_recursively( $data, $serialised, $recursion_level = 0, $visited_data = array(), $opts = [] ) { @@ -269,7 +277,7 @@ public function clear_log_data() { /** * Get the PCRE error constant name from an error value. * - * @param integer $error Error code. + * @param int|null $error Error code. * @return string Error constant name. */ private function preg_error_message( $error ) { From c5e06bdde7b5b204d085d09913dd38b249a4a5f2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Droz?= Date: Tue, 11 Nov 2025 21:20:35 -0300 Subject: [PATCH 14/41] various fixes --- features/search-replace-callback.feature | 60 +++++++++++++++++++++++- src/Search_Replace_Command.php | 11 +++-- src/WP_CLI/SearchReplacer.php | 2 + 3 files changed, 69 insertions(+), 4 deletions(-) diff --git a/features/search-replace-callback.feature b/features/search-replace-callback.feature index cc1df240..373f37fb 100644 --- a/features/search-replace-callback.feature +++ b/features/search-replace-callback.feature @@ -6,7 +6,11 @@ Feature: Test search-replace --callback option And a callback-function.php file: """ >|false + * @var array> */ - private $where; + private $where = []; /** * @var bool @@ -219,7 +219,12 @@ class Search_Replace_Command extends WP_CLI_Command { * : Prints rows to the console as they're updated. * * [--callback=] - * : Runs a user-specified function on each string that contains . is passed as the second argument and the regex string as the third if it exists: call_user_func( 'callback', $data, $new, $search_regex ). + * : Runs a user-specified function on each string that contains . The callback is called as follows: + * call_user_func( 'callback', $data, $new, $search_regex, $opts ) + * * $data is the matched string + * * $new is the replacement string + * * $search_regex is the regex pattern (if applicable, null otherwise) + * * $opts is an array of options. * * [--regex] * : Runs the search using a regular expression (without delimiters). diff --git a/src/WP_CLI/SearchReplacer.php b/src/WP_CLI/SearchReplacer.php index 204f256f..6fe80a66 100644 --- a/src/WP_CLI/SearchReplacer.php +++ b/src/WP_CLI/SearchReplacer.php @@ -97,6 +97,8 @@ public function __construct( $from, $to, $recurse_objects = false, $regex = fals * Ignores any serialized objects unless $recurse_objects is set to true. * * @param array|string $data The data to operate on. + * @param array $opts Additional options for the replacement passed through to the callback + * An array like: ['table' => $table, 'col' => $col, 'key' => $primary_keys] * @param bool $serialised Does the value of $data need to be unserialized? * @param array $opts Options for the callback. * From 363b893ce8270251f6afeacd17ab85887a8c546f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Droz?= Date: Wed, 12 Nov 2025 00:12:00 -0300 Subject: [PATCH 15/41] misc fixes --- features/search-replace-where.feature | 2 +- src/Search_Replace_Command.php | 10 ++++++---- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/features/search-replace-where.feature b/features/search-replace-where.feature index 5ed528c0..0c71d3b1 100644 --- a/features/search-replace-where.feature +++ b/features/search-replace-where.feature @@ -217,7 +217,7 @@ Feature: Test search-replace --where option When I try `wp search-replace 'foobar' 'replaced' --where='posts::post_status="publish"' --include-columns=post_title` Then STDERR should contain: """ - Warning: Column-catch was passed to --where while. But --include-columns will still restrict replacements to columns: post_title + Warning: Column wildcard (*) was passed to --where. But --include-columns will still restrict replacements to columns: post_title """ And STDOUT should contain: diff --git a/src/Search_Replace_Command.php b/src/Search_Replace_Command.php index a2fa68a8..eeb9fe84 100644 --- a/src/Search_Replace_Command.php +++ b/src/Search_Replace_Command.php @@ -483,7 +483,7 @@ function ( $e ) { WP_CLI::warning( 'Column wildcard (*) was passed to --where. But --include-columns will still restrict replacements to columns: ' . implode( ',', $this->include_columns ) ); } } - $this->include_columns = array_merge( $this->include_columns, $columns ); + $this->include_columns = array_merge( $this->include_columns, $columns ); } } @@ -1297,9 +1297,11 @@ private function develop_where_specs( $str_specs ) { $specs = array_filter( explode( ';', (string) $str_specs ) ); $clauses = []; foreach ( $specs as $spec ) { - list( $tables, $cols, $conditions ) = explode( ':', $spec, 3 ); - $tables = array_filter( explode( ',', $tables ) ); - $cols = array_filter( explode( ',', $cols ) ) ? : [ '*' ]; + $parts = array_map( 'trim', explode( ':', $spec, 3 ) ); + if ( count( $parts ) < 3 ) continue; + list( $tables, $cols, $conditions ) = $parts; + $tables = array_filter( array_map( 'trim', explode( ',', $tables ) ) ); + $cols = array_filter( array_map( 'trim', explode( ',', $cols ) ) ) ?: ['*']; foreach ( $tables as $table ) { foreach ( $cols as $col ) { $clauses[ empty( $wpdb->{$table} ) ? $table : $wpdb->{$table} ][ $col ][] = $conditions; From a821c3dfbea5a4e34836939ce725c0bc53c5f4f2 Mon Sep 17 00:00:00 2001 From: Pascal Birchler Date: Wed, 12 Nov 2025 09:00:25 +0100 Subject: [PATCH 16/41] Lint fixes --- src/Search_Replace_Command.php | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/Search_Replace_Command.php b/src/Search_Replace_Command.php index eeb9fe84..a3e5ba88 100644 --- a/src/Search_Replace_Command.php +++ b/src/Search_Replace_Command.php @@ -1298,10 +1298,12 @@ private function develop_where_specs( $str_specs ) { $clauses = []; foreach ( $specs as $spec ) { $parts = array_map( 'trim', explode( ':', $spec, 3 ) ); - if ( count( $parts ) < 3 ) continue; + if ( count( $parts ) < 3 ) { + continue; + } list( $tables, $cols, $conditions ) = $parts; - $tables = array_filter( array_map( 'trim', explode( ',', $tables ) ) ); - $cols = array_filter( array_map( 'trim', explode( ',', $cols ) ) ) ?: ['*']; + $tables = array_filter( array_map( 'trim', explode( ',', $tables ) ) ); + $cols = array_filter( array_map( 'trim', explode( ',', $cols ) ) ) ?: [ '*' ]; foreach ( $tables as $table ) { foreach ( $cols as $col ) { $clauses[ empty( $wpdb->{$table} ) ? $table : $wpdb->{$table} ][ $col ][] = $conditions; From 001381a964bfcc66888f387307dfc107239ece92 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Droz?= Date: Wed, 12 Nov 2025 11:47:25 -0300 Subject: [PATCH 17/41] Update src/WP_CLI/SearchReplacer.php Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- src/WP_CLI/SearchReplacer.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/WP_CLI/SearchReplacer.php b/src/WP_CLI/SearchReplacer.php index 6fe80a66..6c09c0f2 100644 --- a/src/WP_CLI/SearchReplacer.php +++ b/src/WP_CLI/SearchReplacer.php @@ -236,7 +236,7 @@ private function run_recursively( $data, $serialised, $recursion_level = 0, $vis if ( $this->callback ) { if ( false === $result ) { - \WP_CLI::error( 'The callback function return false. Stopping operation.' ); + \WP_CLI::error( 'The callback function returned false. Stopping operation.' ); } elseif ( is_wp_error( $result ) ) { $message = $result->get_error_message(); \WP_CLI::error( 'The callback function threw an error. Stopping operation. ' . $message ); From 5f8498c51a358c398bc1dfbdc4c59dc15247c24c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Droz?= Date: Wed, 12 Nov 2025 11:49:18 -0300 Subject: [PATCH 18/41] Update src/Search_Replace_Command.php Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- src/Search_Replace_Command.php | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/Search_Replace_Command.php b/src/Search_Replace_Command.php index a3e5ba88..791f1006 100644 --- a/src/Search_Replace_Command.php +++ b/src/Search_Replace_Command.php @@ -204,8 +204,7 @@ class Search_Replace_Command extends WP_CLI_Command { * format:
[,table]:[column,...]:quoted-SQL-condition * * [--revisions] - * : Default true. - * If false, then identical to --where='posts::post_status="publish";postmeta::post_id IN (SELECT ID FROM {posts} WHERE post_status="publish")' + * : Include revisions in the search/replace. Defaults to true; pass --no-revisions to exclude revisions (identical to --where='posts::post_status="publish";postmeta::post_id IN (SELECT ID FROM {posts} WHERE post_status="publish")'). * * [--precise] * : Force the use of PHP (instead of SQL) which is more thorough, From 816a51abbad4e8caf11b264fb2a54d87e884f284 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Droz?= Date: Wed, 12 Nov 2025 11:50:04 -0300 Subject: [PATCH 19/41] Update src/Search_Replace_Command.php Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- src/Search_Replace_Command.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Search_Replace_Command.php b/src/Search_Replace_Command.php index 791f1006..85561cf4 100644 --- a/src/Search_Replace_Command.php +++ b/src/Search_Replace_Command.php @@ -131,7 +131,7 @@ class Search_Replace_Command extends WP_CLI_Command { private $where = []; /** - * @var bool + * @var string|false */ private $callback; From 6176cb01f0d77dd01d900d0a229125e6b6945a15 Mon Sep 17 00:00:00 2001 From: Pascal Birchler Date: Thu, 22 Jan 2026 10:45:23 +0100 Subject: [PATCH 20/41] Lint fix --- src/Search_Replace_Command.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Search_Replace_Command.php b/src/Search_Replace_Command.php index 44d76354..e99c006b 100644 --- a/src/Search_Replace_Command.php +++ b/src/Search_Replace_Command.php @@ -210,7 +210,7 @@ class Search_Replace_Command extends WP_CLI_Command { * : Force the use of PHP (instead of SQL) for all columns. By default, the command * uses fast SQL queries, but automatically switches to PHP for columns containing * serialized data. Use this flag to ensure PHP processes all columns, which is - * slower but handles complex serialized data structures more reliably.
 * If --callback is specified, --precise is inferred. + * slower but handles complex serialized data structures more reliably.
 * If --callback is specified, --precise is inferred. * * [--recurse-objects] * : Enable recursing into objects to replace strings. Defaults to true; From 2a5c4287ce20e8899012078ed14d941dc1c6200a Mon Sep 17 00:00:00 2001 From: Pascal Birchler Date: Thu, 12 Mar 2026 11:31:55 +0100 Subject: [PATCH 21/41] Fix issue after merge --- src/Search_Replace_Command.php | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/Search_Replace_Command.php b/src/Search_Replace_Command.php index 529dac27..b95fba59 100644 --- a/src/Search_Replace_Command.php +++ b/src/Search_Replace_Command.php @@ -820,15 +820,18 @@ private function php_handle_col( $col, $primary_keys, $table, $old, $new, $addit $col_sql = self::esc_sql_ident( $col ); $base_key_condition = $additional_where; + $where_key = ''; + if ( ! $this->regex ) { $old_json = self::json_encode_strip_quotes( $old ); $base_key_condition = "$col_sql" . $wpdb->prepare( ' LIKE BINARY %s', '%' . self::esc_like( $old ) . '%' ); if ( $old_json !== $old ) { $base_key_condition = "( $base_key_condition OR $col_sql" . $wpdb->prepare( ' LIKE BINARY %s', '%' . self::esc_like( $old_json ) . '%' ) . ' )'; } + + $where_key = $base_key_condition ? ' WHERE ' . implode( ' AND ', $base_key_condition ) : ''; } - $where_key = $base_key_condition ? ' WHERE ' . implode( ' AND ', $base_key_condition ) : ''; $escaped_primary_keys = self::esc_sql_ident( $primary_keys ); $primary_keys_sql = implode( ',', $escaped_primary_keys ); $order_by_keys = array_map( From 00d2fc783d6da097e50c9d3b3f5150bdf7137186 Mon Sep 17 00:00:00 2001 From: Pascal Birchler Date: Thu, 12 Mar 2026 11:43:23 +0100 Subject: [PATCH 22/41] Array fix --- src/Search_Replace_Command.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/Search_Replace_Command.php b/src/Search_Replace_Command.php index b95fba59..e6b7939a 100644 --- a/src/Search_Replace_Command.php +++ b/src/Search_Replace_Command.php @@ -824,14 +824,14 @@ private function php_handle_col( $col, $primary_keys, $table, $old, $new, $addit if ( ! $this->regex ) { $old_json = self::json_encode_strip_quotes( $old ); - $base_key_condition = "$col_sql" . $wpdb->prepare( ' LIKE BINARY %s', '%' . self::esc_like( $old ) . '%' ); + $condition = "$col_sql" . $wpdb->prepare( ' LIKE BINARY %s', '%' . self::esc_like( $old ) . '%' ); if ( $old_json !== $old ) { - $base_key_condition = "( $base_key_condition OR $col_sql" . $wpdb->prepare( ' LIKE BINARY %s', '%' . self::esc_like( $old_json ) . '%' ) . ' )'; + $condition = "( $condition OR $col_sql" . $wpdb->prepare( ' LIKE BINARY %s', '%' . self::esc_like( $old_json ) . '%' ) . ' )'; } - - $where_key = $base_key_condition ? ' WHERE ' . implode( ' AND ', $base_key_condition ) : ''; + $base_key_condition[] = $condition; } + $where_key = $base_key_condition ? ' WHERE ' . implode( ' AND ', $base_key_condition ) : ''; $escaped_primary_keys = self::esc_sql_ident( $primary_keys ); $primary_keys_sql = implode( ',', $escaped_primary_keys ); $order_by_keys = array_map( From 37c820690f25a4edcae76848bf13d407225e2ae7 Mon Sep 17 00:00:00 2001 From: Pascal Birchler Date: Thu, 12 Mar 2026 12:18:06 +0100 Subject: [PATCH 23/41] Lint fix --- src/Search_Replace_Command.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Search_Replace_Command.php b/src/Search_Replace_Command.php index e6b7939a..80aec65b 100644 --- a/src/Search_Replace_Command.php +++ b/src/Search_Replace_Command.php @@ -823,7 +823,7 @@ private function php_handle_col( $col, $primary_keys, $table, $old, $new, $addit $where_key = ''; if ( ! $this->regex ) { - $old_json = self::json_encode_strip_quotes( $old ); + $old_json = self::json_encode_strip_quotes( $old ); $condition = "$col_sql" . $wpdb->prepare( ' LIKE BINARY %s', '%' . self::esc_like( $old ) . '%' ); if ( $old_json !== $old ) { $condition = "( $condition OR $col_sql" . $wpdb->prepare( ' LIKE BINARY %s', '%' . self::esc_like( $old_json ) . '%' ) . ' )'; From 47f941920188e79e52f7dba5b0ce2b6b8411ee90 Mon Sep 17 00:00:00 2001 From: Pascal Birchler Date: Thu, 12 Mar 2026 12:22:46 +0100 Subject: [PATCH 24/41] Fix variable name after merge --- src/WP_CLI/SearchReplacer.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/WP_CLI/SearchReplacer.php b/src/WP_CLI/SearchReplacer.php index 7a4b70ab..e4790ecd 100644 --- a/src/WP_CLI/SearchReplacer.php +++ b/src/WP_CLI/SearchReplacer.php @@ -247,7 +247,7 @@ private function run_recursively( $data, $serialised, $recursion_level = 0, $vis } else { $result = str_replace( $this->from, $this->to, $data ); if ( $this->from_json !== $this->from ) { - $result = str_replace( $this->from_json, $this->to_json, $data ); + $result = str_replace( $this->from_json, $this->to_json, $result ); } } From 7eb3bb7b6d57b238f6172c98ee0e06691c4e8c7b Mon Sep 17 00:00:00 2001 From: Pascal Birchler Date: Thu, 12 Mar 2026 12:26:30 +0100 Subject: [PATCH 25/41] Default to null --- src/Search_Replace_Command.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Search_Replace_Command.php b/src/Search_Replace_Command.php index 80aec65b..a104136c 100644 --- a/src/Search_Replace_Command.php +++ b/src/Search_Replace_Command.php @@ -598,7 +598,7 @@ function ( $e ) { WP_CLI::log( sprintf( 'Checking: %s.%s', $table, $col ) ); } - $serial_row = false; + $serial_row = null; if ( ! $php_only && ! $this->regex ) { $col_sql = self::esc_sql_ident( $col ); From 8d4954a35f0da7de297d516b321b681ba0f2e0cc Mon Sep 17 00:00:00 2001 From: Pascal Birchler Date: Thu, 12 Mar 2026 12:26:35 +0100 Subject: [PATCH 26/41] Pass opts --- src/WP_CLI/SearchReplacer.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/WP_CLI/SearchReplacer.php b/src/WP_CLI/SearchReplacer.php index e4790ecd..7ec63982 100644 --- a/src/WP_CLI/SearchReplacer.php +++ b/src/WP_CLI/SearchReplacer.php @@ -179,11 +179,11 @@ private function run_recursively( $data, $serialised, $recursion_level = 0, $vis } if ( false !== $unserialized ) { - $data = $this->run_recursively( $unserialized, true, $recursion_level + 1 ); + $data = $this->run_recursively( $unserialized, true, $recursion_level + 1, $visited_data, $opts ); } elseif ( is_array( $data ) ) { $keys = array_keys( $data ); foreach ( $keys as $key ) { - $data[ $key ] = $this->run_recursively( $data[ $key ], false, $recursion_level + 1, $visited_data ); + $data[ $key ] = $this->run_recursively( $data[ $key ], false, $recursion_level + 1, $visited_data, $opts ); } } elseif ( $this->recurse_objects && ( is_object( $data ) || $data instanceof \__PHP_Incomplete_Class ) ) { if ( $data instanceof \__PHP_Incomplete_Class ) { @@ -197,7 +197,7 @@ private function run_recursively( $data, $serialised, $recursion_level = 0, $vis } else { try { foreach ( $data as $key => $value ) { - $data->$key = $this->run_recursively( $value, false, $recursion_level + 1, $visited_data ); + $data->$key = $this->run_recursively( $value, false, $recursion_level + 1, $visited_data, $opts ); } } catch ( \Error $exception ) { // phpcs:ignore PHPCompatibility.Classes.NewClasses.errorFound // This error is thrown when the object that was unserialized cannot be iterated upon. From 6003c54005672ee9ac6dfbc4cea454efe1bc8ea3 Mon Sep 17 00:00:00 2001 From: Pascal Birchler Date: Wed, 25 Nov 2026 11:31:48 +0000 Subject: [PATCH 27/41] Fix --where, --no-revisions and --callback edge cases --no-revisions: - Exclude posts of the `revision` post type (and their meta) instead of everything that is not published, which also skipped drafts, private posts and attachments. - Do not restrict the run to the posts and postmeta tables. - Apply to the posts and postmeta tables of every site, for --network. --where: - Parenthesize each clause, so an OR cannot escape the AND with the search condition or the primary key paging (which looped forever). - Append the raw clauses after $wpdb->prepare(), so a LIKE "%s..." pattern is not taken as a placeholder. - Apply the clauses to the dry-run count for JSON-escaped search strings. - Restrict columns per table, instead of adding the columns of one specification to --include-columns for all tables. - Refuse --where and --no-revisions with --export, which ignored them. - Rebuild the primary key paging condition per chunk instead of appending one more condition for every chunk. --callback: - Only refuse an explicit --no-precise; the callback failed whenever --precise was not passed. - Pass the table, column and primary key values to the callback for regular (non-export) runs too. - With --regex, only call the callback for strings that match. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01UWTd5pwpi2xQfDA6mUYkkx --- features/search-replace-callback.feature | 28 ++++ features/search-replace-revisions.feature | 89 ++++++++++-- features/search-replace-where.feature | 86 ++++++++++++ src/Search_Replace_Command.php | 158 +++++++++++++++------- src/WP_CLI/SearchReplacer.php | 8 +- 5 files changed, 300 insertions(+), 69 deletions(-) diff --git a/features/search-replace-callback.feature b/features/search-replace-callback.feature index 373f37fb..0a38893a 100644 --- a/features/search-replace-callback.feature +++ b/features/search-replace-callback.feature @@ -150,6 +150,9 @@ Feature: Test search-replace --callback option """ ] * : Perform the replacement on specific rows. Use semi-colon to - * specify multiple specifications. + * specify multiple specifications. Only the tables named in --where are processed. * format:
[,table]:[column,...]:quoted-SQL-condition + * Cannot be combined with --export. * * [--revisions] - * : Include revisions in the search/replace. Defaults to true; pass --no-revisions to exclude revisions (identical to --where='posts::post_status="publish";postmeta::post_id IN (SELECT ID FROM {posts} WHERE post_status="publish")'). + * : Include revisions in the search/replace. Defaults to true; pass --no-revisions to skip + * posts of the `revision` post type and their post meta, in every processed site. + * Cannot be combined with --export. * * [--precise] * : Force the use of PHP (instead of SQL) for all columns. By default, the command * uses fast SQL queries, but automatically switches to PHP for columns containing * serialized data. Use this flag to ensure PHP processes all columns, which is - * slower but handles complex serialized data structures more reliably. * If --callback is specified, --precise is inferred. + * slower but handles complex serialized data structures more reliably. + * If --callback is specified, --precise is inferred. * * [--recurse-objects] * : Enable recursing into objects to replace strings. Defaults to true; @@ -248,12 +259,13 @@ class Search_Replace_Command extends WP_CLI_Command { * : Prints rows to the console as they're updated. * * [--callback=] - * : Runs a user-specified function on each string that contains . The callback is called as follows: + * : Runs a user-specified function on each string that contains (or matches it, with --regex). The callback is called as follows: * call_user_func( 'callback', $data, $new, $search_regex, $opts ) - * * $data is the matched string + * * $data is the whole string that contains the match * * $new is the replacement string * * $search_regex is the regex pattern (if applicable, null otherwise) - * * $opts is an array of options. + * * $opts is an array with the 'table', the 'col' and the row's primary 'key' values. + * The callback must return the new string. * * [--regex] * : Runs the search using a regular expression (without delimiters). @@ -421,14 +433,11 @@ public function __invoke( $args, $assoc_args ) { } } - $this->skip_columns = explode( ',', Utils\get_flag_value( $assoc_args, 'skip-columns', '' ) ); - $this->skip_tables = explode( ',', Utils\get_flag_value( $assoc_args, 'skip-tables', '' ) ); - $this->include_columns = array_filter( explode( ',', Utils\get_flag_value( $assoc_args, 'include-columns', '' ) ) ); - $this->where = $this->develop_where_specs( Utils\get_flag_value( $assoc_args, 'where' ) ); - $revisions = Utils\get_flag_value( $assoc_args, 'revisions', true ); - if ( ! $revisions ) { - $this->no_revision(); - } + $this->skip_columns = explode( ',', Utils\get_flag_value( $assoc_args, 'skip-columns', '' ) ); + $this->skip_tables = explode( ',', Utils\get_flag_value( $assoc_args, 'skip-tables', '' ) ); + $this->include_columns = array_filter( explode( ',', Utils\get_flag_value( $assoc_args, 'include-columns', '' ) ) ); + $this->where = $this->develop_where_specs( Utils\get_flag_value( $assoc_args, 'where' ) ); + $this->exclude_revisions = ! Utils\get_flag_value( $assoc_args, 'revisions', true ); if ( $old === $new && ! $this->regex ) { WP_CLI::warning( "Replacement value '{$old}' is identical to search value '{$new}'. Skipping operation." ); @@ -442,7 +451,7 @@ public function __invoke( $args, $assoc_args ) { WP_CLI::error( 'The callback function does not exist. Skipping operation.' ); } - if ( false === $php_only ) { + if ( isset( $assoc_args['precise'] ) && ! $php_only ) { WP_CLI::error( 'PHP is required to execute a callback function. --no-precise cannot be set.' ); } $php_only = true; @@ -453,6 +462,9 @@ public function __invoke( $args, $assoc_args ) { if ( $this->dry_run ) { WP_CLI::error( 'You cannot supply --dry-run and --export at the same time.' ); } + if ( $this->where || $this->exclude_revisions ) { + WP_CLI::error( 'You cannot supply --where or --no-revisions together with --export.' ); + } if ( true === $export ) { $this->export_handle = STDOUT; $this->verbose = false; @@ -539,25 +551,14 @@ public function __invoke( $args, $assoc_args ) { // Get table names based on leftover $args or supplied $assoc_args $tables = Utils\wp_get_table_names( $args, $assoc_args ); // If a custom `where` conditions were passed, then exclude other tables from processing. + // The columns named in a --where specification are handled per table in is_column_searched(). if ( $this->where ) { - $tables = array_intersect( $tables, array_keys( $this->where ) ); - $columns = []; - foreach ( array_values( $this->where ) as $_ => $cols ) { - $columns = array_merge( $columns, array_keys( $cols ) ); - } - if ( $columns ) { - if ( in_array( '*', $columns, true ) ) { - $columns = array_filter( - $columns, - function ( $e ) { - return '*' !== $e; - } - ); - if ( $this->include_columns ) { - WP_CLI::warning( 'Column wildcard (*) was passed to --where. But --include-columns will still restrict replacements to columns: ' . implode( ',', $this->include_columns ) ); - } + $tables = array_values( array_intersect( $tables, array_keys( $this->where ) ) ); + foreach ( $this->where as $where_cols ) { + if ( isset( $where_cols['*'] ) && $this->include_columns ) { + WP_CLI::warning( 'Column wildcard (*) was passed to --where. But --include-columns will still restrict replacements to columns: ' . implode( ',', $this->include_columns ) ); + break; } - $this->include_columns = array_merge( $this->include_columns, $columns ); } } @@ -636,7 +637,7 @@ function ( $col ) use ( $table ) { // instead of scanning the table several times for every column. $column_stats = null; // The stats cover the whole table, so they cannot be used when --where restricts the rows. - if ( ! $this->regex && ! $this->verbose && 'sqlite' !== Utils\get_db_type() && empty( $this->where[ $table ] ) ) { + if ( ! $this->regex && ! $this->verbose && 'sqlite' !== Utils\get_db_type() && ! $this->table_has_clauses( $table ) ) { $column_stats = self::get_column_stats( $table, $columns, $old ); } @@ -791,7 +792,7 @@ private function php_export_table( $table, $old, $new ) { [ 'table' => $table, 'col' => $col, - 'key' => $primary_keys, + 'key' => array_intersect_key( (array) $row, array_flip( $primary_keys ) ), ] ); if ( $new_value !== $value ) { @@ -855,11 +856,13 @@ private function sql_handle_col( $col, $primary_keys, $table, $old, $new, $claus } elseif ( $has_json ) { // Single query with OR to avoid counting rows that match both forms twice. // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- escaped through self::esc_sql_ident - $count = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT($col_sql) FROM $table_sql WHERE $col_sql LIKE BINARY %s OR $col_sql LIKE BINARY %s;", '%' . self::esc_like( $old ) . '%', '%' . self::esc_like( $old_json ) . '%' ) ); + $where = $clauses ? ' AND ' . implode( ' AND ', $clauses ) : ''; + // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQL.NotPrepared -- escaped through self::esc_sql_ident, the --where clauses are raw SQL by design + $count = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT($col_sql) FROM $table_sql WHERE ( $col_sql LIKE BINARY %s OR $col_sql LIKE BINARY %s )", '%' . self::esc_like( $old ) . '%', '%' . self::esc_like( $old_json ) . '%' ) . $where ); } else { $where = $clauses ? ' AND ' . implode( ' AND ', $clauses ) : ''; // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- escaped through self::esc_sql_ident - $count = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT($col_sql) FROM $table_sql WHERE $col_sql LIKE BINARY %s $where;", '%' . self::esc_like( $old ) . '%' ) ); + $count = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT($col_sql) FROM $table_sql WHERE $col_sql LIKE BINARY %s", '%' . self::esc_like( $old ) . '%' ) . $where ); } } else { if ( $this->log_handle ) { @@ -872,10 +875,10 @@ private function sql_handle_col( $col, $primary_keys, $table, $old, $new, $claus if ( $has_json ) { // Single nested REPLACE handles both plain and JSON-encoded forms in one pass. // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- escaped through self::esc_sql_ident - $count = (int) $wpdb->query( $wpdb->prepare( "UPDATE $table_sql SET $col_sql = REPLACE(REPLACE($col_sql, %s, %s), %s, %s) $where;", $old, $new, $old_json, $new_json ) ); + $count = (int) $wpdb->query( $wpdb->prepare( "UPDATE $table_sql SET $col_sql = REPLACE(REPLACE($col_sql, %s, %s), %s, %s)", $old, $new, $old_json, $new_json ) . $where ); } else { // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- escaped through self::esc_sql_ident - $count = (int) $wpdb->query( $wpdb->prepare( "UPDATE $table_sql SET $col_sql = REPLACE($col_sql, %s, %s) $where;", $old, $new ) ); + $count = (int) $wpdb->query( $wpdb->prepare( "UPDATE $table_sql SET $col_sql = REPLACE($col_sql, %s, %s)", $old, $new ) . $where ); } if ( $wpdb->last_error ) { WP_CLI::warning( sprintf( "Error updating column '%s' in table '%s': %s", $col, $table, $wpdb->last_error ) ); @@ -954,7 +957,15 @@ static function ( $key ) { continue; } - $value = $replacer->run( $col_value ); + $value = $replacer->run( + $col_value, + false, + [ + 'table' => $table, + 'col' => $col, + 'key' => (array) $keys, + ] + ); if ( $value === $col_value ) { continue; @@ -1031,8 +1042,9 @@ static function ( $key ) { $next_key_conditions[] = '( ' . implode( ' AND ', $next_key_subconditions ) . ' )'; } - $base_key_condition[] = '( ' . implode( ' OR ', $next_key_conditions ) . ' )'; - $where_key = 'WHERE ' . implode( ' AND ', $base_key_condition ); + $where_key_conditions = $base_key_condition; + $where_key_conditions[] = '( ' . implode( ' OR ', $next_key_conditions ) . ' )'; + $where_key = 'WHERE ' . implode( ' AND ', $where_key_conditions ); } if ( $this->verbose && 'table' === $this->format ) { @@ -1151,11 +1163,19 @@ private static function get_columns( $table ) { * @return bool */ private function is_column_searched( $table, $col ) { - if ( ! empty( $this->include_columns ) && ! in_array( $col, $this->include_columns, true ) && ! in_array( $table . '.' . $col, $this->include_columns, true ) ) { + if ( in_array( $col, $this->skip_columns, true ) || in_array( $table . '.' . $col, $this->skip_columns, true ) ) { return false; } - return ! in_array( $col, $this->skip_columns, true ) && ! in_array( $table . '.' . $col, $this->skip_columns, true ); + $included = empty( $this->include_columns ) || in_array( $col, $this->include_columns, true ) || in_array( $table . '.' . $col, $this->include_columns, true ); + + // A --where specification that names columns restricts this table to those columns, + // in addition to the columns from --include-columns. + if ( isset( $this->where[ $table ] ) && ! isset( $this->where[ $table ]['*'] ) ) { + return isset( $this->where[ $table ][ $col ] ) || ( ! empty( $this->include_columns ) && $included ); + } + + return $included; } /** @@ -1370,7 +1390,7 @@ private function log_sql_diff( $col, $primary_keys, $table, $old, $new, $clauses $where_sql = $clauses ? ' AND ' . implode( ' AND ', $clauses ) : ''; // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- escaped through self::esc_sql_ident - $results = $wpdb->get_results( $wpdb->prepare( "SELECT {$primary_keys_sql}{$col_sql} FROM {$table_sql} WHERE {$col_sql} LIKE BINARY %s {$where_sql}", '%' . self::esc_like( $old ) . '%' ), ARRAY_N ); + $results = $wpdb->get_results( $wpdb->prepare( "SELECT {$primary_keys_sql}{$col_sql} FROM {$table_sql} WHERE {$col_sql} LIKE BINARY %s", '%' . self::esc_like( $old ) . '%' ) . $where_sql, ARRAY_N ); if ( empty( $results ) ) { return 0; @@ -1581,12 +1601,39 @@ private function develop_where_specs( $str_specs ) { } /** - * Excludes revisions from the search-replace operation. + * Gets the clause that excludes revisions for a posts or postmeta table, with --no-revisions. + * + * Matches the posts and postmeta tables of every site, so that --network works too. + * + * @param string $table The table name. + * @return string|null The clause, or null if no revisions are excluded from the table. */ - private function no_revision() { + private function get_revision_clause( $table ) { global $wpdb; - $this->where[ $wpdb->posts ]['*'][] = self::esc_sql_ident( 'post_status' ) . '=' . self::esc_sql_value( 'publish' ); - $this->where[ $wpdb->postmeta ]['*'][] = self::esc_sql_ident( 'post_id' ) . ' IN ( SELECT ID FROM ' . $wpdb->posts . ' WHERE ' . self::esc_sql_ident( 'post_status' ) . '=' . self::esc_sql_value( 'publish' ) . ')'; + + if ( ! $this->exclude_revisions || ! preg_match( '/^(' . preg_quote( $wpdb->base_prefix, '/' ) . '(?:[0-9]+_)?)(posts|postmeta)$/', $table, $matches ) ) { + return null; + } + + $not_revision = self::esc_sql_ident( 'post_type' ) . ' <> ' . self::esc_sql_value( 'revision' ); + + if ( 'posts' === $matches[2] ) { + return $not_revision; + } + + $revision_ids = 'SELECT ' . self::esc_sql_ident( 'ID' ) . ' FROM ' . self::esc_sql_ident( $matches[1] . 'posts' ) . ' WHERE ' . self::esc_sql_ident( 'post_type' ) . ' = ' . self::esc_sql_value( 'revision' ); + + return self::esc_sql_ident( 'post_id' ) . " NOT IN ( $revision_ids )"; + } + + /** + * Whether rows of a table are restricted by --where or --no-revisions. + * + * @param string $table The table name. + * @return bool + */ + private function table_has_clauses( $table ) { + return ! empty( $this->where[ $table ] ) || null !== $this->get_revision_clause( $table ); } /** @@ -1597,10 +1644,21 @@ private function no_revision() { * @return string[] The WHERE clauses. */ private function get_clauses( $table, $column = null ) { - return array_filter( + $clauses = array_filter( array_merge( $this->where[ $table ][ $column ] ?? [], - $this->where[ $table ]['*'] ?? [] + $this->where[ $table ]['*'] ?? [], + [ (string) $this->get_revision_clause( $table ) ] + ) + ); + + // Parenthesize each clause, so that an OR in one cannot escape the AND with the others. + return array_values( + array_map( + static function ( $clause ) { + return '( ' . $clause . ' )'; + }, + $clauses ) ); } diff --git a/src/WP_CLI/SearchReplacer.php b/src/WP_CLI/SearchReplacer.php index 4493468a..2e442beb 100644 --- a/src/WP_CLI/SearchReplacer.php +++ b/src/WP_CLI/SearchReplacer.php @@ -128,10 +128,9 @@ public function __construct( $from, $to, $recurse_objects = false, $regex = fals * Ignores any serialized objects unless $recurse_objects is set to true. * * @param array|string $data The data to operate on. - * @param array $opts Additional options for the replacement passed through to the callback - * An array like: ['table' => $table, 'col' => $col, 'key' => $primary_keys] * @param bool $serialised Does the value of $data need to be unserialized? - * @param array $opts Options for the callback. + * @param array $opts Additional options passed through to the callback, + * like ['table' => $table, 'col' => $col, 'key' => $primary_key_values]. * * @return array|string The original array with all elements replaced as needed. */ @@ -248,7 +247,8 @@ private function run_recursively( $data, $serialised, $recursion_level = 0, $vis $search_regex .= $this->regex_flags; if ( $this->callback ) { - $result = \call_user_func( $this->callback, $data, $this->to, $search_regex, $opts ); + // Only call the callback for strings that match, like without --regex. + $result = preg_match( $search_regex, $data ) ? \call_user_func( $this->callback, $data, $this->to, $search_regex, $opts ) : $data; } else { $result = preg_replace( $search_regex, $this->to, $data, $this->regex_limit ); } From 9818c3d0d9a4f24dfffb5bf67514dda2387ffd8d Mon Sep 17 00:00:00 2001 From: Pascal Birchler Date: Thu, 26 Nov 2026 10:24:12 +0000 Subject: [PATCH 28/41] Run --callback even when the search and replacement values are identical Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01UWTd5pwpi2xQfDA6mUYkkx --- features/search-replace-callback.feature | 26 ++++++++++++++++++++++++ src/Search_Replace_Command.php | 3 ++- src/WP_CLI/SearchReplacer.php | 20 ++++++++++++++++-- 3 files changed, 46 insertions(+), 3 deletions(-) diff --git a/features/search-replace-callback.feature b/features/search-replace-callback.feature index 0a38893a..31f296be 100644 --- a/features/search-replace-callback.feature +++ b/features/search-replace-callback.feature @@ -213,3 +213,29 @@ Feature: Test search-replace --callback option """ BAZ bar """ + + @require-mysql + Scenario: Callback runs even when the search and replacement values are identical + Given a WP install + And a callback-upper.php file: + """ + where = $this->develop_where_specs( Utils\get_flag_value( $assoc_args, 'where' ) ); $this->exclude_revisions = ! Utils\get_flag_value( $assoc_args, 'revisions', true ); - if ( $old === $new && ! $this->regex ) { + // A callback may still change the matching strings, so only skip without one. + if ( $old === $new && ! $this->regex && ! $this->callback ) { WP_CLI::warning( "Replacement value '{$old}' is identical to search value '{$new}'. Skipping operation." ); exit; } diff --git a/src/WP_CLI/SearchReplacer.php b/src/WP_CLI/SearchReplacer.php index 2e442beb..06c46235 100644 --- a/src/WP_CLI/SearchReplacer.php +++ b/src/WP_CLI/SearchReplacer.php @@ -62,6 +62,11 @@ class SearchReplacer { */ private $log_data = []; + /** + * @var string[] + */ + private $log_new_data = []; + /** * @var int */ @@ -287,7 +292,8 @@ private function run_recursively( $data, $serialised, $recursion_level = 0, $vis $data = $result; if ( $this->logging && $old_data !== $data ) { - $this->log_data[] = $old_data; + $this->log_data[] = $old_data; + $this->log_new_data[] = $data; } } @@ -309,11 +315,21 @@ public function get_log_data() { return $this->log_data; } + /** + * Gets the data strings after replacements saved for this run when logging, + * in the same order as get_log_data(). + * @return string[] Array of data strings, after replacements. + */ + public function get_log_new_data() { + return $this->log_new_data; + } + /** * Clears data stored for logging. */ public function clear_log_data() { - $this->log_data = array(); + $this->log_data = array(); + $this->log_new_data = array(); } /** From 358342a327cc771ea075a6862864397b6611a8e5 Mon Sep 17 00:00:00 2001 From: Pascal Birchler Date: Thu, 26 Nov 2026 10:24:12 +0000 Subject: [PATCH 29/41] Reject malformed --where specifications instead of ignoring them A specification without the three parts (or without a table) was skipped, which silently made the run unrestricted. Error out while parsing, before any table is processed. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01UWTd5pwpi2xQfDA6mUYkkx --- features/search-replace-where.feature | 33 +++++++++++++++++++++++++++ src/Search_Replace_Command.php | 9 +++++--- 2 files changed, 39 insertions(+), 3 deletions(-) diff --git a/features/search-replace-where.feature b/features/search-replace-where.feature index 81e3a39b..67a80c88 100644 --- a/features/search-replace-where.feature +++ b/features/search-replace-where.feature @@ -355,6 +355,39 @@ Feature: Test search-replace --where option Success: 1 replacement to be made. """ + @require-mysql + Scenario: Malformed where specifications are rejected before any table is processed + Given a WP install + And I run `wp post create --post_title='Post foo' --porcelain` + And save STDOUT as {POST_ID} + + When I try `wp search-replace foo bar --where='wp_posts:post_title'` + Then STDERR should be: + """ + Error: Invalid --where specification 'wp_posts:post_title'. Expected format:
[,table]:[column,...]:. + """ + And the return code should be 1 + + When I try `wp search-replace foo bar --where='posts::1=1;wp_postmeta:meta_value'` + Then STDERR should be: + """ + Error: Invalid --where specification 'wp_postmeta:meta_value'. Expected format:
[,table]:[column,...]:. + """ + And the return code should be 1 + + When I try `wp search-replace foo bar --where=":post_title:1=1"` + Then STDERR should be: + """ + Error: Invalid --where specification ':post_title:1=1': no table given. + """ + And the return code should be 1 + + When I run `wp post get {POST_ID} --field=title` + Then STDOUT should be: + """ + Post foo + """ + Scenario: Where clause cannot be combined with an export Given a WP install diff --git a/src/Search_Replace_Command.php b/src/Search_Replace_Command.php index ea3ad04e..342254ae 100644 --- a/src/Search_Replace_Command.php +++ b/src/Search_Replace_Command.php @@ -1586,11 +1586,14 @@ private function develop_where_specs( $str_specs ) { foreach ( $specs as $spec ) { $parts = array_map( 'trim', explode( ':', $spec, 3 ) ); if ( count( $parts ) < 3 ) { - continue; + WP_CLI::error( "Invalid --where specification '{$spec}'. Expected format:
[,table]:[column,...]:." ); } list( $tables, $cols, $conditions ) = $parts; - $tables = array_filter( array_map( 'trim', explode( ',', $tables ) ) ); - $cols = array_filter( array_map( 'trim', explode( ',', $cols ) ) ) ?: [ '*' ]; + $tables = array_filter( array_map( 'trim', explode( ',', $tables ) ), 'strlen' ); + $cols = array_filter( array_map( 'trim', explode( ',', $cols ) ), 'strlen' ) ?: [ '*' ]; + if ( ! $tables ) { + WP_CLI::error( "Invalid --where specification '{$spec}': no table given." ); + } foreach ( $tables as $table ) { foreach ( $cols as $col ) { $clauses[ empty( $wpdb->{$table} ) ? $table : $wpdb->{$table} ][ $col ][] = $conditions; From 5f3581a432e5216df8fccc852238787ddc56b7a9 Mon Sep 17 00:00:00 2001 From: Pascal Birchler Date: Thu, 26 Nov 2026 10:24:12 +0000 Subject: [PATCH 30/41] Split --where specifications only on semicolons outside quoted literals Semicolons inside SQL string literals (with '' or backslash-escaped quotes) no longer cut a condition in two. An unterminated quote is an error. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01UWTd5pwpi2xQfDA6mUYkkx --- features/search-replace-where.feature | 56 +++++++++++++++++++++++++++ src/Search_Replace_Command.php | 50 +++++++++++++++++++++++- 2 files changed, 104 insertions(+), 2 deletions(-) diff --git a/features/search-replace-where.feature b/features/search-replace-where.feature index 67a80c88..c466d6aa 100644 --- a/features/search-replace-where.feature +++ b/features/search-replace-where.feature @@ -355,6 +355,55 @@ Feature: Test search-replace --where option Success: 1 replacement to be made. """ + @require-mysql + Scenario: Where conditions with semicolons inside quoted literals + Given a WP install + And I run `wp option update blogname 'Site foo'` + And I run `wp post create --post_title='a;b foo' --porcelain` + And save STDOUT as {POST1_ID} + And I run `wp post create --post_title="it's;c foo" --porcelain` + And save STDOUT as {POST2_ID} + And I run `wp post create --post_title="it's;d foo" --porcelain` + And save STDOUT as {POST3_ID} + And I run `wp post create --post_title='other foo' --porcelain` + And save STDOUT as {POST4_ID} + + When I run `wp search-replace foo bar --where="posts:post_title:post_title IN ('a;b foo', 'it\'s;c foo', 'it''s;d foo');options:option_value:option_name = 'blogname'"` + Then STDOUT should contain: + """ + Success: Made 4 replacements. + """ + + When I run `wp post get {POST1_ID} --field=title` + Then STDOUT should be: + """ + a;b bar + """ + + When I run `wp post get {POST2_ID} --field=title` + Then STDOUT should be: + """ + it's;c bar + """ + + When I run `wp post get {POST3_ID} --field=title` + Then STDOUT should be: + """ + it's;d bar + """ + + When I run `wp post get {POST4_ID} --field=title` + Then STDOUT should be: + """ + other foo + """ + + When I run `wp option get blogname` + Then STDOUT should be: + """ + Site bar + """ + @require-mysql Scenario: Malformed where specifications are rejected before any table is processed Given a WP install @@ -382,6 +431,13 @@ Feature: Test search-replace --where option """ And the return code should be 1 + When I try `wp search-replace foo bar --where="posts::post_title = 'Post foo"` + Then STDERR should be: + """ + Error: Invalid --where specification 'posts::post_title = 'Post foo': unterminated ' quote. + """ + And the return code should be 1 + When I run `wp post get {POST_ID} --field=title` Then STDOUT should be: """ diff --git a/src/Search_Replace_Command.php b/src/Search_Replace_Command.php index 342254ae..15f69d32 100644 --- a/src/Search_Replace_Command.php +++ b/src/Search_Replace_Command.php @@ -1581,9 +1581,8 @@ private function log_write( $col, $keys, $table, $old_bits, $new_bits ) { */ private function develop_where_specs( $str_specs ) { global $wpdb; - $specs = array_filter( explode( ';', (string) $str_specs ) ); $clauses = []; - foreach ( $specs as $spec ) { + foreach ( self::split_where_specs( (string) $str_specs ) as $spec ) { $parts = array_map( 'trim', explode( ':', $spec, 3 ) ); if ( count( $parts ) < 3 ) { WP_CLI::error( "Invalid --where specification '{$spec}'. Expected format:
[,table]:[column,...]:." ); @@ -1604,6 +1603,53 @@ private function develop_where_specs( $str_specs ) { return $clauses; } + /** + * Splits the --where option into its specifications, on the semicolons outside quoted SQL literals. + * + * Inside quotes, a backslash escapes the next character, and a doubled quote character + * closes and reopens the literal, so neither ends it. + * + * @param string $str_specs The --where option value. + * @return string[] The non-empty specifications. + */ + private static function split_where_specs( $str_specs ) { + $specs = []; + $current = ''; + $quote = null; + $length = strlen( $str_specs ); + for ( $i = 0; $i < $length; $i++ ) { + $char = $str_specs[ $i ]; + if ( null !== $quote ) { + if ( '\\' === $char && $i + 1 < $length ) { + $current .= $char . $str_specs[ ++$i ]; + continue; + } + if ( $char === $quote ) { + $quote = null; + } + } elseif ( "'" === $char || '"' === $char || '`' === $char ) { + $quote = $char; + } elseif ( ';' === $char ) { + $specs[] = $current; + $current = ''; + continue; + } + $current .= $char; + } + + if ( null !== $quote ) { + WP_CLI::error( "Invalid --where specification '{$current}': unterminated {$quote} quote." ); + } + $specs[] = $current; + + return array_values( + array_filter( + array_map( 'trim', $specs ), + 'strlen' + ) + ); + } + /** * Gets the clause that excludes revisions for a posts or postmeta table, with --no-revisions. * From 93696991724ad769c859ee7d2220d74059cde8ef Mon Sep 17 00:00:00 2001 From: Pascal Birchler Date: Thu, 26 Nov 2026 10:24:12 +0000 Subject: [PATCH 31/41] Keep a --where condition of '0' instead of dropping it array_filter() removed it, so the run was unrestricted in both the SQL and the --precise paths. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01UWTd5pwpi2xQfDA6mUYkkx --- features/search-replace-where.feature | 24 ++++++++++++++++++++++++ src/Search_Replace_Command.php | 6 +++++- 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/features/search-replace-where.feature b/features/search-replace-where.feature index c466d6aa..a0c65f31 100644 --- a/features/search-replace-where.feature +++ b/features/search-replace-where.feature @@ -444,6 +444,30 @@ Feature: Test search-replace --where option Post foo """ + @require-mysql + Scenario: Where condition of 0 matches no rows + Given a WP install + And I run `wp post create --post_title='Post foo' --porcelain` + And save STDOUT as {POST_ID} + + When I run `wp search-replace foo bar --where='wp_posts:post_title:0'` + Then STDOUT should contain: + """ + Success: Made 0 replacements. + """ + + When I run `wp search-replace foo bar --where='wp_posts:post_title:0' --precise` + Then STDOUT should contain: + """ + Success: Made 0 replacements. + """ + + When I run `wp post get {POST_ID} --field=title` + Then STDOUT should be: + """ + Post foo + """ + Scenario: Where clause cannot be combined with an export Given a WP install diff --git a/src/Search_Replace_Command.php b/src/Search_Replace_Command.php index 15f69d32..e66a4a22 100644 --- a/src/Search_Replace_Command.php +++ b/src/Search_Replace_Command.php @@ -1699,7 +1699,11 @@ private function get_clauses( $table, $column = null ) { $this->where[ $table ][ $column ] ?? [], $this->where[ $table ]['*'] ?? [], [ (string) $this->get_revision_clause( $table ) ] - ) + ), + static function ( $clause ) { + // Keep a condition like '0': only drop the absent or empty ones. + return '' !== trim( $clause ); + } ); // Parenthesize each clause, so that an OR in one cannot escape the AND with the others. From 471c42be066d9377f4eee758bd1162eb1667e8c9 Mon Sep 17 00:00:00 2001 From: Pascal Birchler Date: Thu, 26 Nov 2026 10:24:13 +0000 Subject: [PATCH 32/41] Apply --callback to --export Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01UWTd5pwpi2xQfDA6mUYkkx --- features/search-replace-callback.feature | 29 ++++++++++++++++++++++++ src/Search_Replace_Command.php | 2 +- 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/features/search-replace-callback.feature b/features/search-replace-callback.feature index 31f296be..4d19c20f 100644 --- a/features/search-replace-callback.feature +++ b/features/search-replace-callback.feature @@ -239,3 +239,32 @@ Feature: Test search-replace --callback option """ FOO bar """ + + @require-mysql + Scenario: Callback is applied to an export + Given a WP install + And a callback-function.php file: + """ + $chunk_size, ); - $replacer = new SearchReplacer( $old, $new, $this->recurse_objects, $this->regex, $this->regex_flags, $this->regex_delimiter, false, $this->regex_limit ); + $replacer = new SearchReplacer( $old, $new, $this->recurse_objects, $this->regex, $this->regex_flags, $this->regex_delimiter, false, $this->regex_limit, $this->callback ); $col_counts = array_fill_keys( $all_columns, 0 ); if ( $this->verbose && 'table' === $this->format ) { $this->start_time = microtime( true ); From 42c9851dca71de9371dd4de5e70d2c56bfeaeb9d Mon Sep 17 00:00:00 2001 From: Pascal Birchler Date: Thu, 26 Nov 2026 10:24:13 +0000 Subject: [PATCH 33/41] Log the value --callback returned instead of an ordinary replacement The log (and the dry-run preview) simulated replacing the matches with . Keep the before/after strings of the actual callback run and log the part that changed, without calling the callback again. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01UWTd5pwpi2xQfDA6mUYkkx --- features/search-replace-callback.feature | 37 ++++++++++++ src/Search_Replace_Command.php | 75 +++++++++++++++++++++++- 2 files changed, 110 insertions(+), 2 deletions(-) diff --git a/features/search-replace-callback.feature b/features/search-replace-callback.feature index 4d19c20f..134e7e35 100644 --- a/features/search-replace-callback.feature +++ b/features/search-replace-callback.feature @@ -268,3 +268,40 @@ Feature: Test search-replace --callback option """ foo bar """ + + @require-mysql + Scenario: Log shows the value the callback returned + Given a WP install + And a callback-function.php file: + """ + BAZ bar + """ + + When I run `wp search-replace 'foo' 'baz' wp_posts --include-columns=post_title --callback='test_callback' --require=callback-function.php --log=- --before_context=2 --after_context=2` + Then STDOUT should contain: + """ + Success: Made 1 replacement. + """ + And STDOUT should contain: + """ + wp_posts.post_title:{POST_ID} + < foo b + > BAZ b + """ diff --git a/src/Search_Replace_Command.php b/src/Search_Replace_Command.php index 21af7d56..24916403 100644 --- a/src/Search_Replace_Command.php +++ b/src/Search_Replace_Command.php @@ -979,7 +979,7 @@ static function ( $key ) { } if ( $this->log_handle ) { - $this->log_php_diff( $col, $keys, $table, $old, $new, $replacer->get_log_data() ); + $this->log_php_diff( $col, $keys, $table, $old, $new, $replacer->get_log_data(), $replacer->get_log_new_data() ); $replacer->clear_log_data(); } @@ -1418,8 +1418,25 @@ private function log_sql_diff( $col, $primary_keys, $table, $old, $new, $clauses * @param string $old Old value to match. * @param string $new New value to replace the old value with. * @param string[] $log_data Array of data strings before replacements. + * @param string[] $log_new_data Array of the same data strings after replacements. */ - private function log_php_diff( $col, $keys, $table, $old, $new, $log_data ) { + private function log_php_diff( $col, $keys, $table, $old, $new, $log_data, $log_new_data = array() ) { + if ( $this->callback ) { + // The callback may return anything, so log what it actually returned + // instead of simulating an ordinary replacement (and never call it again). + $old_bits = array(); + $new_bits = array(); + foreach ( $log_data as $i => $data ) { + if ( isset( $log_new_data[ $i ] ) ) { + list( $old_bits[], $new_bits[] ) = $this->log_changed_bits( $data, $log_new_data[ $i ] ); + } + } + if ( $old_bits ) { + $this->log_write( $col, $keys, $table, $old_bits, $new_bits ); + } + return; + } + if ( $this->regex ) { $search_regex = $this->regex_delimiter . $old . $this->regex_delimiter . $this->regex_flags; } else { @@ -1543,6 +1560,60 @@ static function ( $m ) use ( $matches ) { return array( $old_bits, $new_bits ); } + /** + * Returns the log strings of the part that differs between two data strings, with context. + * + * Used for callback replacements, whose result cannot be derived from the matches. + * + * @param string $old_data Data before the replacement. + * @param string $new_data Data after the replacement. + * @return string[] Two element array containing the old and the new log string. + */ + private function log_changed_bits( $old_data, $new_data ) { + $encoding = $this->log_encoding; + if ( ! $encoding && ( $this->log_before_context || $this->log_after_context ) && function_exists( 'mb_detect_encoding' ) ) { + $encoding = mb_detect_encoding( $old_data, null, true /*strict*/ ); + } + + $old_len = strlen( $old_data ); + $new_len = strlen( $new_data ); + $max = min( $old_len, $new_len ); + + $prefix = 0; + while ( $prefix < $max && $old_data[ $prefix ] === $new_data[ $prefix ] ) { + ++$prefix; + } + $suffix = 0; + while ( $suffix < $max - $prefix && $old_data[ $old_len - 1 - $suffix ] === $new_data[ $new_len - 1 - $suffix ] ) { + ++$suffix; + } + + // Do not cut a UTF-8 multibyte character in two. + $is_continuation = static function ( $str, $pos ) { + return $pos < strlen( $str ) && 0x80 === ( ord( $str[ $pos ] ) & 0xC0 ); + }; + while ( $prefix > 0 && ( $is_continuation( $old_data, $prefix ) || $is_continuation( $new_data, $prefix ) ) ) { + --$prefix; + } + while ( $suffix > 0 && ( $is_continuation( $old_data, $old_len - $suffix ) || $is_continuation( $new_data, $new_len - $suffix ) ) ) { + --$suffix; + } + + $before = ''; + $after = ''; + if ( $this->log_before_context && $prefix ) { + $before = safe_substr( substr( $old_data, 0, $prefix ), -$this->log_before_context, null /*length*/, false /*is_width*/, $encoding ); + } + if ( $this->log_after_context && $suffix ) { + $after = safe_substr( substr( $old_data, $old_len - $suffix ), 0, $this->log_after_context, false /*is_width*/, $encoding ); + } + + $old_log = $this->log_colors['log_old'][0] . substr( $old_data, $prefix, $old_len - $prefix - $suffix ) . $this->log_colors['log_old'][1]; + $new_log = $this->log_colors['log_new'][0] . substr( $new_data, $prefix, $new_len - $prefix - $suffix ) . $this->log_colors['log_new'][1]; + + return array( $before . $old_log . $after, $before . $new_log . $after ); + } + /** * Outputs the log strings. * From 894ee485e7a1ad50b59ff25007b8555a5a10f0f7 Mon Sep 17 00:00:00 2001 From: Pascal Birchler Date: Thu, 26 Nov 2026 11:23:10 +0000 Subject: [PATCH 34/41] Apply --callback to a value of '0' in an export The export skipped every falsy value, so a callback never saw the string '0' there, while the live run passes it on. Only skip NULL and empty values. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01UWTd5pwpi2xQfDA6mUYkkx --- features/search-replace-callback.feature | 24 ++++++++++++++++++++++++ src/Search_Replace_Command.php | 2 +- 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/features/search-replace-callback.feature b/features/search-replace-callback.feature index 134e7e35..6f05e3fc 100644 --- a/features/search-replace-callback.feature +++ b/features/search-replace-callback.feature @@ -269,6 +269,30 @@ Feature: Test search-replace --callback option foo bar """ + @require-mysql + Scenario: Callback is applied to a value of 0 in an export + Given a WP install + And a callback-zero.php file: + """ + $col; - if ( $value + if ( null !== $value && '' !== $value && ! in_array( $col, $primary_keys, true ) && ! in_array( $col, $this->skip_columns, true ) && ! in_array( $table . '.' . $col, $this->skip_columns, true ) From 8b1b0bd70afb57e4f13e5a402ae1bd4f8bc1a878 Mon Sep 17 00:00:00 2001 From: Pascal Birchler Date: Thu, 26 Nov 2026 11:27:25 +0000 Subject: [PATCH 35/41] Select the --where rows once per table, before any column is replaced A --where condition on a column that the same run replaces was evaluated again for each column, so once one column was replaced, the next columns no longer matched it: the live run depended on the column order and made fewer replacements than the dry run reported. With more than one column, select the primary keys of the matching rows before any replacement, paging by primary key, and restrict every column's replacement and dry-run count to those keys, in chunks of 1000. Columns that share their conditions share one key list; tables without --where, and single columns, keep their existing queries. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01UWTd5pwpi2xQfDA6mUYkkx --- features/search-replace-where.feature | 45 +++++ src/Search_Replace_Command.php | 268 ++++++++++++++++++++------ 2 files changed, 251 insertions(+), 62 deletions(-) diff --git a/features/search-replace-where.feature b/features/search-replace-where.feature index a0c65f31..fdc16e92 100644 --- a/features/search-replace-where.feature +++ b/features/search-replace-where.feature @@ -468,6 +468,51 @@ Feature: Test search-replace --where option Post foo """ + @require-mysql + Scenario Outline: Where condition selects the rows before any column is replaced + Given a WP install + And I run `wp post create --post_title='Title foo' --post_content='Content foo' --porcelain` + And save STDOUT as {MATCH_ID} + And I run `wp post create --post_title='Other foo' --post_content='Other none' --porcelain` + And save STDOUT as {OTHER_ID} + + When I run `wp search-replace foo bar --where='' --dry-run --format=count ` + Then STDOUT should be: + """ + 2 + """ + + When I run `wp search-replace foo bar --where='' --format=count ` + Then STDOUT should be: + """ + 2 + """ + + When I run `wp post get {MATCH_ID} --field=title` + Then STDOUT should be: + """ + Title bar + """ + + When I run `wp post get {MATCH_ID} --field=content` + Then STDOUT should be: + """ + Content bar + """ + + When I run `wp post get {OTHER_ID} --field=title` + Then STDOUT should be: + """ + Other foo + """ + + Examples: + | where | flags | + | posts:post_content,post_title:post_content LIKE "%foo%" | | + | posts:post_content,post_title:post_content LIKE "%foo%" | --precise | + | posts:post_title:post_content LIKE "%foo%";posts:post_content:post_title LIKE "%foo%" | | + | posts:post_title:post_content LIKE "%foo%";posts:post_content:post_title LIKE "%foo%" | --precise | + Scenario: Where clause cannot be combined with an export Given a WP install diff --git a/src/Search_Replace_Command.php b/src/Search_Replace_Command.php index 14213ecd..b0452263 100644 --- a/src/Search_Replace_Command.php +++ b/src/Search_Replace_Command.php @@ -237,6 +237,8 @@ class Search_Replace_Command extends WP_CLI_Command { * : Perform the replacement on specific rows. Use semi-colon to * specify multiple specifications. Only the tables named in --where are processed. * format:
[,table]:[column,...]:quoted-SQL-condition + * The conditions select the rows once per table, before any column is replaced, so a + * replacement in a column that a condition refers to does not change the rows of the other columns. * Cannot be combined with --export. * * [--revisions] @@ -644,10 +646,23 @@ function ( $col ) use ( $table ) { $stats_outdated = false; + $key_chunks = $this->get_where_key_chunks( $table, $primary_keys, $columns, $old ); + foreach ( $columns as $i => $col ) { $clauses = $this->get_clauses( $table, $col ); + // With the rows selected up front, handle the column one chunk of those rows at a time. + $clause_sets = array( $clauses ); + if ( isset( $key_chunks[ $col ] ) ) { + $clause_sets = array_map( + static function ( $key_chunk ) { + return array( $key_chunk ); + }, + $key_chunks[ $col ] + ); + } + if ( $this->verbose && 'count' !== $this->format ) { $this->start_time = microtime( true ); WP_CLI::log( sprintf( 'Checking: %s.%s', $table, $col ) ); @@ -677,31 +692,49 @@ function ( $col ) use ( $table ) { // SQLite does not support REGEXP by default, fall back to PHP processing. $serial_row = true; } else { - $where = $clauses ? ' AND ' . implode( ' AND ', $clauses ) : ''; - // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- escaped through self::esc_sql_ident - $serial_row = $wpdb->get_row( "SELECT * FROM $table_sql WHERE $col_sql REGEXP '^[aiO]:[1-9]' $where LIMIT 1" ); - - // When the regex triggers an error, we should fall back to PHP - if ( false !== strpos( $wpdb->last_error, 'ERROR 1139' ) ) { - $serial_row = true; + $serial_row = null; + foreach ( $clause_sets as $set_clauses ) { + $where = $set_clauses ? ' AND ' . implode( ' AND ', $set_clauses ) : ''; + // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- escaped through self::esc_sql_ident + $serial_row = $wpdb->get_row( "SELECT * FROM $table_sql WHERE $col_sql REGEXP '^[aiO]:[1-9]' $where LIMIT 1" ); + + // When the regex triggers an error, we should fall back to PHP + if ( false !== strpos( $wpdb->last_error, 'ERROR 1139' ) ) { + $serial_row = true; + } + if ( null !== $serial_row ) { + break; + } } } } + $count = 0; if ( $php_only || $this->regex || null !== $serial_row ) { $type = 'PHP'; // Nothing to replace in a column without matches. - $count = null !== $stats && 0 === $stats['matches'] ? 0 : $this->php_handle_col( $col, $primary_keys, $table, $old, $new, $clauses ); + if ( null === $stats || 0 !== $stats['matches'] ) { + foreach ( $clause_sets as $set_clauses ) { + $count += $this->php_handle_col( $col, $primary_keys, $table, $old, $new, $set_clauses ); + } + } } else { $type = 'SQL'; if ( null !== $stats && ( 0 === $stats['matches'] || ( $this->dry_run && ! $this->log_handle ) ) ) { // The dry run count is the number of matching rows, which is already known. $count = $stats['matches']; } else { - $count = $this->sql_handle_col( $col, $primary_keys, $table, $old, $new, $clauses ); + foreach ( $clause_sets as $set_clauses ) { + $count += $this->sql_handle_col( $col, $primary_keys, $table, $old, $new, $set_clauses ); + } } } + if ( $this->verbose && 'table' === $this->format ) { + $time = round( microtime( true ) - $this->start_time, 3 ); + WP_CLI::log( sprintf( '%d rows affected using %s (in %ss).', $count, $type, $time ) ); + } + if ( $count && ! $this->dry_run && ! $this->export_handle ) { $stats_outdated = true; } @@ -886,10 +919,6 @@ private function sql_handle_col( $col, $primary_keys, $table, $old, $new, $claus } } - if ( $this->verbose && 'table' === $this->format ) { - $time = round( microtime( true ) - $this->start_time, 3 ); - WP_CLI::log( sprintf( '%d rows affected using SQL (in %ss).', $count, $time ) ); - } return $count; } @@ -917,12 +946,7 @@ private function php_handle_col( $col, $primary_keys, $table, $old, $new, $addit $where_key = ''; if ( ! $this->regex ) { - $old_json = self::json_encode_strip_quotes( $old ); - $condition = "$col_sql" . $wpdb->prepare( ' LIKE BINARY %s', '%' . self::esc_like( $old ) . '%' ); - if ( $old_json !== $old ) { - $condition = "( $condition OR $col_sql" . $wpdb->prepare( ' LIKE BINARY %s', '%' . self::esc_like( $old_json ) . '%' ) . ' )'; - } - $base_key_condition[] = $condition; + $base_key_condition[] = self::get_match_condition( $col, $old ); } $where_key = $base_key_condition ? ' WHERE ' . implode( ' AND ', $base_key_condition ) : ''; @@ -1016,43 +1040,12 @@ static function ( $key ) { } } - // Because we are ordering by primary keys from least to greatest, - // we can exclude previous chunks from consideration by adding greater-than conditions - // to insist the next chunk's keys must be greater than the last of this chunk's keys. - $last_row = end( $rows ); - $next_key_conditions = array(); - - // NOTE: For a composite key (X, Y, Z), selecting the next rows requires the following conditions: - // ( X = lastX AND Y = lastY AND Z > lastZ ) OR - // ( X = lastX AND Y > lastY ) OR - // ( X > lastX ) - for ( $last_key_index = count( $primary_keys ) - 1; $last_key_index >= 0; $last_key_index-- ) { - $next_key_subconditions = array(); - - for ( $i = 0; $i <= $last_key_index; $i++ ) { - $k = $primary_keys[ $i ]; - $v = $last_row->{ $k }; - - if ( $i < $last_key_index ) { - $next_key_subconditions[] = self::esc_sql_ident( $k ) . ' = ' . self::esc_sql_value( $v ); - } else { - $next_key_subconditions[] = self::esc_sql_ident( $k ) . ' > ' . self::esc_sql_value( $v ); - } - } - - $next_key_conditions[] = '( ' . implode( ' AND ', $next_key_subconditions ) . ' )'; - } - + $last_row = end( $rows ); $where_key_conditions = $base_key_condition; - $where_key_conditions[] = '( ' . implode( ' OR ', $next_key_conditions ) . ' )'; + $where_key_conditions[] = self::get_next_key_condition( $primary_keys, array_values( (array) $last_row ) ); $where_key = 'WHERE ' . implode( ' AND ', $where_key_conditions ); } - if ( $this->verbose && 'table' === $this->format ) { - $time = round( microtime( true ) - $this->start_time, 3 ); - WP_CLI::log( sprintf( '%d rows affected using PHP (in %ss).', $count, $time ) ); - } - return $count; } @@ -1197,17 +1190,10 @@ private static function get_column_stats( $table, $columns, $old ) { return array(); } - $old_json = self::json_encode_strip_quotes( $old ); - $selects = array(); + $selects = array(); foreach ( $columns as $col ) { - $col_sql = self::esc_sql_ident( $col ); - // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- escaped through self::esc_sql_ident - $match = $wpdb->prepare( "$col_sql LIKE BINARY %s", '%' . self::esc_like( $old ) . '%' ); - if ( $old_json !== $old ) { - // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- escaped through self::esc_sql_ident - $match = "( $match OR " . $wpdb->prepare( "$col_sql LIKE BINARY %s", '%' . self::esc_like( $old_json ) . '%' ) . ' )'; - } - $selects[] = "SUM( $match )"; + $col_sql = self::esc_sql_ident( $col ); + $selects[] = 'SUM( ' . self::get_match_condition( $col, $old ) . ' )'; $selects[] = "MAX( $col_sql REGEXP '^[aiO]:[1-9]' )"; } @@ -1757,6 +1743,164 @@ private function table_has_clauses( $table ) { return ! empty( $this->where[ $table ] ) || null !== $this->get_revision_clause( $table ); } + /** + * Gets the SQL condition that a column contains the search string, plain or JSON-encoded. + * + * @param string $col The column name. + * @param string $old The search string. + * @return string The condition. + */ + private static function get_match_condition( $col, $old ) { + global $wpdb; + + $col_sql = self::esc_sql_ident( $col ); + $old_json = self::json_encode_strip_quotes( $old ); + // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- escaped through self::esc_sql_ident + $condition = $wpdb->prepare( "$col_sql LIKE BINARY %s", '%' . self::esc_like( $old ) . '%' ); + if ( $old_json !== $old ) { + // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- escaped through self::esc_sql_ident + $condition = "( $condition OR " . $wpdb->prepare( "$col_sql LIKE BINARY %s", '%' . self::esc_like( $old_json ) . '%' ) . ' )'; + } + return $condition; + } + + /** + * Gets the SQL condition that selects the rows after a given row, in primary key order. + * + * For a composite key (X, Y, Z), the rows after (lastX, lastY, lastZ) are: + * ( X = lastX AND Y = lastY AND Z > lastZ ) OR ( X = lastX AND Y > lastY ) OR ( X > lastX ) + * + * @param string[] $primary_keys The primary key columns. + * @param string[] $last_values The primary key values of the last row, in the same order. + * @return string The condition. + */ + private static function get_next_key_condition( $primary_keys, $last_values ) { + $next_key_conditions = array(); + for ( $last_key_index = count( $primary_keys ) - 1; $last_key_index >= 0; $last_key_index-- ) { + $next_key_subconditions = array(); + for ( $i = 0; $i <= $last_key_index; $i++ ) { + $operator = $i < $last_key_index ? ' = ' : ' > '; + $next_key_subconditions[] = self::esc_sql_ident( $primary_keys[ $i ] ) . $operator . self::esc_sql_value( (string) $last_values[ $i ] ); + } + $next_key_conditions[] = '( ' . implode( ' AND ', $next_key_subconditions ) . ' )'; + } + return '( ' . implode( ' OR ', $next_key_conditions ) . ' )'; + } + + /** + * Selects the rows that the --where conditions match, once per table, before any column is replaced. + * + * Otherwise, replacing a column that a condition refers to would change the rows that the + * columns after it are replaced in, and the live run would differ from the dry run. + * The rows are returned as conditions on their primary keys, each covering a chunk of rows, + * so that neither the memory nor the queries grow with one huge list of keys. + * + * @param string $table The table name. + * @param string[] $primary_keys The primary key columns. + * @param string[] $columns The columns to replace in. + * @param string $old The search string. + * @return array|null The key conditions per column with --where conditions, + * or null if a single column is replaced or no --where applies. + */ + private function get_where_key_chunks( $table, $primary_keys, $columns, $old ) { + global $wpdb; + + // With a single column, no replacement can affect the rows the conditions select. + if ( empty( $this->where[ $table ] ) || count( $columns ) < 2 ) { + return null; + } + + // Columns with the same conditions share the same rows. + $groups = array(); + foreach ( $columns as $col ) { + $clauses = $this->get_clauses( $table, $col ); + if ( $clauses ) { + $id = implode( ' AND ', $clauses ); + $groups[ $id ]['clauses'] = $clauses; + $groups[ $id ]['columns'][] = $col; + } + } + if ( ! $groups ) { + return null; + } + $groups = array_values( $groups ); + + $conditions = array(); + foreach ( $groups as $group ) { + $condition = $group['clauses']; + if ( ! $this->regex ) { + // Only rows that contain the search string in one of the columns can change. + $condition[] = '( ' . implode( + ' OR ', + array_map( + static function ( $col ) use ( $old ) { + return self::get_match_condition( $col, $old ); + }, + $group['columns'] + ) + ) . ' )'; + } + $conditions[] = implode( ' AND ', $condition ); + } + + $escaped_primary_keys = self::esc_sql_ident( $primary_keys ); + $selects = $escaped_primary_keys; + if ( count( $conditions ) > 1 ) { + foreach ( $conditions as $condition ) { + $selects[] = "CASE WHEN $condition THEN 1 ELSE 0 END"; + } + } + $select_sql = implode( ', ', $selects ); + $table_sql = self::esc_sql_ident( $table ); + $order_by_sql = implode( ' ASC, ', $escaped_primary_keys ) . ' ASC'; + $base_where = '( ( ' . implode( ' ) OR ( ', $conditions ) . ' ) )'; + $key_count = count( $primary_keys ); + $key_sql = 1 === $key_count ? $escaped_primary_keys[0] : '( ' . implode( ', ', $escaped_primary_keys ) . ' )'; + $limit = 1000; + + $key_lists = array_fill( 0, count( $groups ), array() ); + $chunks = array_fill( 0, count( $groups ), array() ); + $add_chunk = static function ( $keys ) use ( $key_sql ) { + return "( $key_sql IN ( " . implode( ', ', $keys ) . ' ) )'; + }; + + $where = $base_where; + while ( true ) { + // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- escaped through self::esc_sql_ident, the --where clauses are raw SQL by design + $rows = $wpdb->get_results( "SELECT $select_sql FROM $table_sql WHERE $where ORDER BY $order_by_sql LIMIT $limit", ARRAY_N ); + if ( ! $rows ) { + break; + } + foreach ( $rows as $row ) { + $values = self::esc_sql_value( array_map( 'strval', array_slice( $row, 0, $key_count ) ) ); + $key = 1 === $key_count ? $values[0] : '( ' . implode( ', ', $values ) . ' )'; + foreach ( $groups as $g => $group ) { + if ( count( $groups ) > 1 && ! $row[ $key_count + $g ] ) { + continue; + } + $key_lists[ $g ][] = $key; + if ( count( $key_lists[ $g ] ) >= $limit ) { + $chunks[ $g ][] = $add_chunk( $key_lists[ $g ] ); + $key_lists[ $g ] = array(); + } + } + } + $where = $base_where . ' AND ' . self::get_next_key_condition( $primary_keys, array_slice( end( $rows ), 0, $key_count ) ); + } + + $key_chunks = array(); + foreach ( $groups as $g => $group ) { + if ( $key_lists[ $g ] ) { + $chunks[ $g ][] = $add_chunk( $key_lists[ $g ] ); + } + foreach ( $group['columns'] as $col ) { + $key_chunks[ $col ] = $chunks[ $g ]; + } + } + + return $key_chunks; + } + /** * Gets the WHERE clauses for a given table and column. * From 5702dfcfa39473f1c3c44bbdf404454885447fe9 Mon Sep 17 00:00:00 2001 From: Pascal Birchler Date: Thu, 26 Nov 2026 14:06:07 +0000 Subject: [PATCH 36/41] Hold the --where rows in a temporary table instead of in PHP The primary keys of the rows that --where selects were kept in PHP as chunks of `pk IN (...)` predicates: memory grew with the number of matching rows, a numeric-looking text key like '01' was written as the number 1 and also matched '1', a failed page query ended the selection silently with a partial key list, and prefiltering by the search string could miss a match that a trigger adds to a later column. Copy the keys of the matching rows database-side, with their exact types, into an indexed temporary table per set of conditions, and restrict each column's replacement and dry-run count to it. Stop with an error before any column of the table is replaced if the table cannot be created, with a hint about the CREATE TEMPORARY TABLES privilege, and error out on SQLite, whose drop-in does not support CREATE TABLE ... SELECT. Also stop when a page query of the PHP handler or a dry-run count fails, instead of reporting a partial count. Never replace the primary key columns of a table with --where, so a row stays addressable by its key, and compare text primary keys as strings when the PHP handler fetches a row or pages by key. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01UWTd5pwpi2xQfDA6mUYkkx --- features/search-replace-where.feature | 160 +++++++++++++++++ src/Search_Replace_Command.php | 245 +++++++++++++------------- 2 files changed, 285 insertions(+), 120 deletions(-) diff --git a/features/search-replace-where.feature b/features/search-replace-where.feature index fdc16e92..6012649a 100644 --- a/features/search-replace-where.feature +++ b/features/search-replace-where.feature @@ -513,6 +513,166 @@ Feature: Test search-replace --where option | posts:post_title:post_content LIKE "%foo%";posts:post_content:post_title LIKE "%foo%" | | | posts:post_title:post_content LIKE "%foo%";posts:post_content:post_title LIKE "%foo%" | --precise | + @require-mysql + Scenario Outline: Where condition on a text primary key replaces only the rows it selects + Given a WP install + And I run `wp db query "CREATE TABLE wp_slugs ( slug VARCHAR(20) NOT NULL, title TEXT, body TEXT, PRIMARY KEY (slug) )"` + And I run `wp db query "INSERT INTO wp_slugs VALUES ('01', 'zero one foo', 'zero one foo'), ('1', 'one foo', 'one foo')"` + + When I run `wp search-replace foo bar --all-tables --where="wp_slugs::slug = '1'" --dry-run --format=count ` + Then STDOUT should be: + """ + 2 + """ + + When I run `wp search-replace foo bar --all-tables --where="wp_slugs::slug = '1'" --format=count ` + Then STDOUT should be: + """ + 2 + """ + + When I run `wp db query "SELECT CONCAT_WS('|', slug, title, body) FROM wp_slugs ORDER BY slug" --skip-column-names` + Then STDOUT should be: + """ + 01|zero one foo|zero one foo + 1|one bar|one bar + """ + + Examples: + | flags | + | | + | --precise | + + @require-mysql + Scenario Outline: Where never replaces a primary key column + Given a WP install + And I run `wp db query "CREATE TABLE wp_keyed ( slug VARCHAR(20) NOT NULL, title TEXT, body TEXT, PRIMARY KEY (slug) )"` + And I run `wp db query "INSERT INTO wp_keyed VALUES ('foo', 'foo', 'foo'), ('other', 'foo', 'foo')"` + + When I run `wp search-replace foo bar --all-tables --where="wp_keyed::slug = 'foo'" --dry-run --format=count ` + Then STDOUT should be: + """ + 2 + """ + + When I run `wp search-replace foo bar --all-tables --where="wp_keyed::slug = 'foo'" --format=count ` + Then STDOUT should be: + """ + 2 + """ + + When I run `wp db query "SELECT CONCAT_WS('|', slug, title, body) FROM wp_keyed ORDER BY slug" --skip-column-names` + Then STDOUT should be: + """ + foo|bar|bar + other|foo|foo + """ + + Examples: + | flags | + | | + | --precise | + + @require-mysql + Scenario Outline: A failed row selection stops before any column is replaced + Given a WP install + And I run `wp post create --post_title='Title foo' --post_content='Content foo' --porcelain` + And save STDOUT as {POST_ID} + + When I try `wp search-replace foo bar --where='posts:post_content,post_title:no_such_column = 1' ` + Then STDERR should contain: + """ + Error: Could not select the rows of table 'wp_posts' that --where matches: + """ + And STDERR should contain: + """ + no_such_column + """ + And the return code should be 1 + + When I run `wp post get {POST_ID} --field=title` + Then STDOUT should be: + """ + Title foo + """ + + When I run `wp post get {POST_ID} --field=content` + Then STDOUT should be: + """ + Content foo + """ + + Examples: + | flags | + | | + | --dry-run | + | --precise | + + @require-mysql + Scenario: A missing privilege for the temporary table gives a clear error + Given a WP install + And a wp-content/mu-plugins/deny-temporary-tables.php file: + """ + + */ + private $string_primary_keys = array(); + /** * Searches/replaces strings in the database. * @@ -239,6 +247,9 @@ class Search_Replace_Command extends WP_CLI_Command { * format:
[,table]:[column,...]:quoted-SQL-condition * The conditions select the rows once per table, before any column is replaced, so a * replacement in a column that a condition refers to does not change the rows of the other columns. + * To replace several columns of a table, the primary keys of the selected rows are held in a + * temporary table, which needs the CREATE TEMPORARY TABLES privilege (and MySQL or MariaDB: + * on SQLite, replace one column per run). The primary key columns of these tables are not replaced. * Cannot be combined with --export. * * [--revisions] @@ -609,7 +620,9 @@ public function __invoke( $args, $assoc_args ) { continue; } - list( $primary_keys, $columns, $all_columns ) = self::get_columns( $table ); + list( $primary_keys, $columns, $all_columns, $string_keys ) = self::get_columns( $table ); + + $this->string_primary_keys[ $table ] = $string_keys; // since we'll be updating one row at a time, // we need a primary key to identify the row @@ -630,7 +643,11 @@ public function __invoke( $args, $assoc_args ) { $columns = array_values( array_filter( $columns, - function ( $col ) use ( $table ) { + function ( $col ) use ( $table, $primary_keys ) { + // With --where, the rows are identified by their primary keys, so never replace those. + if ( ! empty( $this->where[ $table ] ) && in_array( $col, $primary_keys, true ) ) { + return false; + } return $this->is_column_searched( $table, $col ); } ) @@ -646,22 +663,12 @@ function ( $col ) use ( $table ) { $stats_outdated = false; - $key_chunks = $this->get_where_key_chunks( $table, $primary_keys, $columns, $old ); + list( $key_clauses, $key_tables ) = $this->create_where_key_tables( $table, $primary_keys, $columns ); foreach ( $columns as $i => $col ) { - $clauses = $this->get_clauses( $table, $col ); - - // With the rows selected up front, handle the column one chunk of those rows at a time. - $clause_sets = array( $clauses ); - if ( isset( $key_chunks[ $col ] ) ) { - $clause_sets = array_map( - static function ( $key_chunk ) { - return array( $key_chunk ); - }, - $key_chunks[ $col ] - ); - } + // With the rows selected up front, restrict the column to those rows only. + $clauses = isset( $key_clauses[ $col ] ) ? array( $key_clauses[ $col ] ) : $this->get_clauses( $table, $col ); if ( $this->verbose && 'count' !== $this->format ) { $this->start_time = microtime( true ); @@ -692,41 +699,28 @@ static function ( $key_chunk ) { // SQLite does not support REGEXP by default, fall back to PHP processing. $serial_row = true; } else { - $serial_row = null; - foreach ( $clause_sets as $set_clauses ) { - $where = $set_clauses ? ' AND ' . implode( ' AND ', $set_clauses ) : ''; - // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- escaped through self::esc_sql_ident - $serial_row = $wpdb->get_row( "SELECT * FROM $table_sql WHERE $col_sql REGEXP '^[aiO]:[1-9]' $where LIMIT 1" ); - - // When the regex triggers an error, we should fall back to PHP - if ( false !== strpos( $wpdb->last_error, 'ERROR 1139' ) ) { - $serial_row = true; - } - if ( null !== $serial_row ) { - break; - } + $where = $clauses ? ' AND ' . implode( ' AND ', $clauses ) : ''; + // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- escaped through self::esc_sql_ident + $serial_row = $wpdb->get_row( "SELECT * FROM $table_sql WHERE $col_sql REGEXP '^[aiO]:[1-9]' $where LIMIT 1" ); + + // When the regex triggers an error, we should fall back to PHP + if ( false !== strpos( $wpdb->last_error, 'ERROR 1139' ) ) { + $serial_row = true; } } } - $count = 0; if ( $php_only || $this->regex || null !== $serial_row ) { $type = 'PHP'; // Nothing to replace in a column without matches. - if ( null === $stats || 0 !== $stats['matches'] ) { - foreach ( $clause_sets as $set_clauses ) { - $count += $this->php_handle_col( $col, $primary_keys, $table, $old, $new, $set_clauses ); - } - } + $count = null !== $stats && 0 === $stats['matches'] ? 0 : $this->php_handle_col( $col, $primary_keys, $table, $old, $new, $clauses ); } else { $type = 'SQL'; if ( null !== $stats && ( 0 === $stats['matches'] || ( $this->dry_run && ! $this->log_handle ) ) ) { // The dry run count is the number of matching rows, which is already known. $count = $stats['matches']; } else { - foreach ( $clause_sets as $set_clauses ) { - $count += $this->sql_handle_col( $col, $primary_keys, $table, $old, $new, $set_clauses ); - } + $count = $this->sql_handle_col( $col, $primary_keys, $table, $old, $new, $clauses ); } } @@ -745,6 +739,8 @@ static function ( $key_chunk ) { $total += $count; } + + self::drop_tables( $key_tables ); } if ( $this->export_handle && STDOUT !== $this->export_handle ) { @@ -898,6 +894,9 @@ private function sql_handle_col( $col, $primary_keys, $table, $old, $new, $claus // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- escaped through self::esc_sql_ident $count = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT($col_sql) FROM $table_sql WHERE $col_sql LIKE BINARY %s", '%' . self::esc_like( $old ) . '%' ) . $where ); } + if ( $wpdb->last_error ) { + WP_CLI::error( sprintf( "Error counting the matches of column '%s' in table '%s': %s", $col, $table, $wpdb->last_error ) ); + } } else { if ( $this->log_handle ) { $this->log_sql_diff( $col, $primary_keys, $table, $old, $new, $clauses ); @@ -972,7 +971,7 @@ static function ( $key ) { if ( '' !== $where_sql ) { $where_sql .= ' AND '; } - $where_sql .= self::esc_sql_ident( $k ) . ' = ' . self::esc_sql_value( $v ); + $where_sql .= self::esc_sql_ident( $k ) . ' = ' . self::esc_sql_key_value( $v, in_array( $k, $this->string_primary_keys[ $table ], true ) ); } // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- escaped through self::esc_sql_ident @@ -1042,10 +1041,15 @@ static function ( $key ) { $last_row = end( $rows ); $where_key_conditions = $base_key_condition; - $where_key_conditions[] = self::get_next_key_condition( $primary_keys, array_values( (array) $last_row ) ); + $where_key_conditions[] = self::get_next_key_condition( $primary_keys, array_values( (array) $last_row ), $this->string_primary_keys[ $table ] ); $where_key = 'WHERE ' . implode( ' AND ', $where_key_conditions ); } + // An empty page also ends the loop when its query failed: don't report that as success. + if ( $wpdb->last_error ) { + WP_CLI::error( sprintf( "Error selecting the rows of column '%s' in table '%s': %s", $col, $table, $wpdb->last_error ) ); + } + return $count; } @@ -1120,13 +1124,15 @@ private function write_sql_row_fields( $table, $rows ) { * Gets the primary keys, text columns, and all columns for a table. * * @param string $table The table to get the columns for. - * @return array A tuple containing the primary keys, text columns, and all columns. + * @return array A tuple containing the primary keys, text columns, all columns, + * and the primary keys that are not of an integer type. */ private static function get_columns( $table ) { global $wpdb; $table_sql = self::esc_sql_ident( $table ); $primary_keys = array(); + $string_keys = array(); $text_columns = array(); $all_columns = array(); $suppress_errors = $wpdb->suppress_errors(); @@ -1138,6 +1144,9 @@ private static function get_columns( $table ) { foreach ( $results as $col ) { if ( 'PRI' === $col->Key ) { $primary_keys[] = $col->Field; + if ( ! preg_match( '/^(tiny|small|medium|big)?int(eger)?\b/i', $col->Type ) ) { + $string_keys[] = $col->Field; + } } if ( self::is_text_col( $col->Type ) ) { $text_columns[] = $col->Field; @@ -1146,7 +1155,7 @@ private static function get_columns( $table ) { } } $wpdb->suppress_errors( $suppress_errors ); - return array( $primary_keys, $text_columns, $all_columns ); + return array( $primary_keys, $text_columns, $all_columns, $string_keys ); } /** @@ -1317,6 +1326,20 @@ private static function esc_sql_value( $values ) { return $quote( $values ); } + /** + * Puts a primary key value into SQL, as a string if its column is not of an integer type. + * + * A numeric-looking value of a text key, like '01', must stay a string: compared as a number, + * it would also match other keys, like '1'. + * + * @param string $value The value. + * @param bool $is_string Whether the column is not of an integer type. + * @return string The SQL value. + */ + private static function esc_sql_key_value( $value, $is_string ) { + return $is_string ? "'" . esc_sql( $value ) . "'" : self::esc_sql_value( $value ); + } + /** * Gets the color codes from the options if any, and returns the passed in array colorized with 2 elements per entry, a color code (or '') and a reset (or ''). * @@ -1772,15 +1795,16 @@ private static function get_match_condition( $col, $old ) { * * @param string[] $primary_keys The primary key columns. * @param string[] $last_values The primary key values of the last row, in the same order. + * @param string[] $string_keys The primary key columns whose values are compared as strings. * @return string The condition. */ - private static function get_next_key_condition( $primary_keys, $last_values ) { + private static function get_next_key_condition( $primary_keys, $last_values, $string_keys ) { $next_key_conditions = array(); for ( $last_key_index = count( $primary_keys ) - 1; $last_key_index >= 0; $last_key_index-- ) { $next_key_subconditions = array(); for ( $i = 0; $i <= $last_key_index; $i++ ) { $operator = $i < $last_key_index ? ' = ' : ' > '; - $next_key_subconditions[] = self::esc_sql_ident( $primary_keys[ $i ] ) . $operator . self::esc_sql_value( (string) $last_values[ $i ] ); + $next_key_subconditions[] = self::esc_sql_ident( $primary_keys[ $i ] ) . $operator . self::esc_sql_key_value( (string) $last_values[ $i ], in_array( $primary_keys[ $i ], $string_keys, true ) ); } $next_key_conditions[] = '( ' . implode( ' AND ', $next_key_subconditions ) . ' )'; } @@ -1792,22 +1816,30 @@ private static function get_next_key_condition( $primary_keys, $last_values ) { * * Otherwise, replacing a column that a condition refers to would change the rows that the * columns after it are replaced in, and the live run would differ from the dry run. - * The rows are returned as conditions on their primary keys, each covering a chunk of rows, - * so that neither the memory nor the queries grow with one huge list of keys. + * + * The primary keys of the matching rows are copied, database-side and with their exact + * column types, into a temporary table per set of conditions, so that neither the memory + * of the command nor the size of its queries grow with the number of matching rows. + * Each column is then restricted to the keys of its temporary table. + * + * Stops with an error, before any column of the table is replaced, if a temporary table + * cannot be created or populated. * * @param string $table The table name. * @param string[] $primary_keys The primary key columns. * @param string[] $columns The columns to replace in. - * @param string $old The search string. - * @return array|null The key conditions per column with --where conditions, - * or null if a single column is replaced or no --where applies. + * @return array{0: array, 1: string[]} The clause restricting each column with + * --where conditions to the selected rows, + * and the temporary tables to drop afterwards. + * Both empty if a single column is replaced + * or no --where applies. */ - private function get_where_key_chunks( $table, $primary_keys, $columns, $old ) { + private function create_where_key_tables( $table, $primary_keys, $columns ) { global $wpdb; // With a single column, no replacement can affect the rows the conditions select. if ( empty( $this->where[ $table ] ) || count( $columns ) < 2 ) { - return null; + return array( array(), array() ); } // Columns with the same conditions share the same rows. @@ -1815,90 +1847,63 @@ private function get_where_key_chunks( $table, $primary_keys, $columns, $old ) { foreach ( $columns as $col ) { $clauses = $this->get_clauses( $table, $col ); if ( $clauses ) { - $id = implode( ' AND ', $clauses ); - $groups[ $id ]['clauses'] = $clauses; - $groups[ $id ]['columns'][] = $col; + $groups[ implode( ' AND ', $clauses ) ][] = $col; } } if ( ! $groups ) { - return null; - } - $groups = array_values( $groups ); - - $conditions = array(); - foreach ( $groups as $group ) { - $condition = $group['clauses']; - if ( ! $this->regex ) { - // Only rows that contain the search string in one of the columns can change. - $condition[] = '( ' . implode( - ' OR ', - array_map( - static function ( $col ) use ( $old ) { - return self::get_match_condition( $col, $old ); - }, - $group['columns'] - ) - ) . ' )'; - } - $conditions[] = implode( ' AND ', $condition ); + return array( array(), array() ); } - $escaped_primary_keys = self::esc_sql_ident( $primary_keys ); - $selects = $escaped_primary_keys; - if ( count( $conditions ) > 1 ) { - foreach ( $conditions as $condition ) { - $selects[] = "CASE WHEN $condition THEN 1 ELSE 0 END"; - } + if ( 'sqlite' === Utils\get_db_type() ) { + WP_CLI::error( sprintf( "Replacing several columns of table '%s' with --where is not supported on SQLite. Replace one column per run instead, e.g. with --include-columns.", $table ) ); } - $select_sql = implode( ', ', $selects ); - $table_sql = self::esc_sql_ident( $table ); - $order_by_sql = implode( ' ASC, ', $escaped_primary_keys ) . ' ASC'; - $base_where = '( ( ' . implode( ' ) OR ( ', $conditions ) . ' ) )'; - $key_count = count( $primary_keys ); - $key_sql = 1 === $key_count ? $escaped_primary_keys[0] : '( ' . implode( ', ', $escaped_primary_keys ) . ' )'; - $limit = 1000; - - $key_lists = array_fill( 0, count( $groups ), array() ); - $chunks = array_fill( 0, count( $groups ), array() ); - $add_chunk = static function ( $keys ) use ( $key_sql ) { - return "( $key_sql IN ( " . implode( ', ', $keys ) . ' ) )'; - }; - $where = $base_where; - while ( true ) { + $keys_sql = implode( ', ', self::esc_sql_ident( $primary_keys ) ); + $row_key_sql = 1 === count( $primary_keys ) ? $keys_sql : "( $keys_sql )"; + $table_sql = self::esc_sql_ident( $table ); + $suffix = substr( md5( uniqid( '', true ) ), 0, 8 ); + + $key_clauses = array(); + $key_tables = array(); + foreach ( array_keys( $groups ) as $index => $condition ) { + $key_table = "wp_cli_search_replace_rows_{$suffix}_{$index}"; + $key_table_sql = self::esc_sql_ident( $key_table ); + + $suppress_errors = $wpdb->suppress_errors(); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- escaped through self::esc_sql_ident, the --where clauses are raw SQL by design - $rows = $wpdb->get_results( "SELECT $select_sql FROM $table_sql WHERE $where ORDER BY $order_by_sql LIMIT $limit", ARRAY_N ); - if ( ! $rows ) { - break; - } - foreach ( $rows as $row ) { - $values = self::esc_sql_value( array_map( 'strval', array_slice( $row, 0, $key_count ) ) ); - $key = 1 === $key_count ? $values[0] : '( ' . implode( ', ', $values ) . ' )'; - foreach ( $groups as $g => $group ) { - if ( count( $groups ) > 1 && ! $row[ $key_count + $g ] ) { - continue; - } - $key_lists[ $g ][] = $key; - if ( count( $key_lists[ $g ] ) >= $limit ) { - $chunks[ $g ][] = $add_chunk( $key_lists[ $g ] ); - $key_lists[ $g ] = array(); - } + $wpdb->query( "CREATE TEMPORARY TABLE $key_table_sql ( PRIMARY KEY ( $keys_sql ) ) SELECT $keys_sql FROM $table_sql WHERE $condition" ); + $error = $wpdb->last_error; + $wpdb->suppress_errors( $suppress_errors ); + if ( $error ) { + self::drop_tables( array_merge( $key_tables, array( $key_table ) ) ); + if ( false !== stripos( $error, 'denied' ) ) { + WP_CLI::error( sprintf( "Could not create a temporary table to hold the rows of table '%s' that --where matches: %s Replacing several columns of a table with --where needs the CREATE TEMPORARY TABLES privilege; without it, replace one column per run, e.g. with --include-columns.", $table, $error ) ); } + WP_CLI::error( sprintf( "Could not select the rows of table '%s' that --where matches: %s", $table, $error ) ); } - $where = $base_where . ' AND ' . self::get_next_key_condition( $primary_keys, array_slice( end( $rows ), 0, $key_count ) ); - } + $key_tables[] = $key_table; - $key_chunks = array(); - foreach ( $groups as $g => $group ) { - if ( $key_lists[ $g ] ) { - $chunks[ $g ][] = $add_chunk( $key_lists[ $g ] ); - } - foreach ( $group['columns'] as $col ) { - $key_chunks[ $col ] = $chunks[ $g ]; + foreach ( $groups[ $condition ] as $col ) { + $key_clauses[ $col ] = "( $row_key_sql IN ( SELECT $keys_sql FROM $key_table_sql ) )"; } } - return $key_chunks; + return array( $key_clauses, $key_tables ); + } + + /** + * Drops temporary tables. + * + * @param string[] $tables The temporary table names. + */ + private static function drop_tables( $tables ) { + global $wpdb; + + foreach ( $tables as $table ) { + $table_sql = self::esc_sql_ident( $table ); + // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- escaped through self::esc_sql_ident + $wpdb->query( "DROP TEMPORARY TABLE IF EXISTS $table_sql" ); + } } /** From 1918289f137ed4c870816823ae76fd409ab7e9b7 Mon Sep 17 00:00:00 2001 From: Pascal Birchler Date: Thu, 26 Nov 2026 14:26:22 +0000 Subject: [PATCH 37/41] Compare string primary keys as strings when updating a row with --precise wpdb->update() picks the format of each WHERE column from $wpdb->field_types when none is given, so a VARCHAR primary key named `ID` was compared as %d: the key '1' then also matched '01', and the row '01' was updated although --where did not select it. Pass %s for string keys (and for the replaced text value), and keep wpdb's default for the other keys. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01UWTd5pwpi2xQfDA6mUYkkx --- features/search-replace-where.feature | 24 ++++++++++++++++++++++++ src/Search_Replace_Command.php | 12 ++++++++++-- 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/features/search-replace-where.feature b/features/search-replace-where.feature index 6012649a..1293527a 100644 --- a/features/search-replace-where.feature +++ b/features/search-replace-where.feature @@ -573,6 +573,30 @@ Feature: Test search-replace --where option | | | --precise | + @require-mysql + Scenario Outline: Where with --precise updates only the selected row of a string primary key named like a WordPress integer column + Given a WP install + And I run `wp db query "CREATE TABLE wp_idkeyed ( ID VARCHAR(20) NOT NULL, title TEXT, body TEXT, PRIMARY KEY (ID) )"` + And I run `wp db query "INSERT INTO wp_idkeyed VALUES ('01', 'zero one foo', 'zero one foo'), ('1', 'one foo', 'one foo')"` + + When I run `wp search-replace foo bar --all-tables --where="" --precise --format=count` + Then STDOUT should be: + """ + + """ + + When I run `wp db query "SELECT CONCAT_WS('|', ID, title, body) FROM wp_idkeyed ORDER BY ID" --skip-column-names` + Then STDOUT should be: + """ + 01|zero one foo|zero one foo + 1||one bar + """ + + Examples: + | where | count | title | + | wp_idkeyed:body:ID = '1' | 1 | one foo | + | wp_idkeyed::ID = '1' | 2 | one bar | + @require-mysql Scenario Outline: A failed row selection stops before any column is replaced Given a WP install diff --git a/src/Search_Replace_Command.php b/src/Search_Replace_Command.php index c8458398..a13db92d 100644 --- a/src/Search_Replace_Command.php +++ b/src/Search_Replace_Command.php @@ -1016,12 +1016,20 @@ static function ( $key ) { // In dry-run mode, count replacements once a change has been detected. ++$count; } else { - $update_where = array(); + // Pass the formats explicitly, as wpdb would otherwise pick them from $wpdb->field_types by + // column name only, e.g. %d for any `ID` column: a string key '1' would then also match '01'. + $update_where = array(); + $where_formats = array(); foreach ( (array) $keys as $k => $v ) { $update_where[ $k ] = $v; + if ( in_array( $k, $this->string_primary_keys[ $table ], true ) ) { + $where_formats[] = '%s'; + } else { + $where_formats[] = isset( $wpdb->field_types[ $k ] ) ? $wpdb->field_types[ $k ] : '%s'; + } } - $result = $wpdb->update( $table, array( $col => $value ), $update_where ); + $result = $wpdb->update( $table, array( $col => $value ), $update_where, array( '%s' ), $where_formats ); if ( false === $result ) { if ( empty( $this->update_error_columns[ $table ][ $col ] ) ) { $this->update_error_columns[ $table ][ $col ] = true; From 9df13d23ac7f09136d0265c4d44343d53a252726 Mon Sep 17 00:00:00 2001 From: Pascal Birchler <pascal.birchler@gmail.com> Date: Thu, 26 Nov 2026 14:26:22 +0000 Subject: [PATCH 38/41] Keep the primary key prefixes in the --where temporary table A primary key on a TEXT or BLOB column indexes a prefix, e.g. PRIMARY KEY (slug(32)), and the temporary table that holds the rows --where selects could not be created without it. Read the prefix lengths of the table's primary key and index the same prefixes; the columns still hold the full values. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01UWTd5pwpi2xQfDA6mUYkkx --- features/search-replace-where.feature | 30 +++++++++++++++++++++++++++ src/Search_Replace_Command.php | 21 ++++++++++++++++++- 2 files changed, 50 insertions(+), 1 deletion(-) diff --git a/features/search-replace-where.feature b/features/search-replace-where.feature index 1293527a..2397a361 100644 --- a/features/search-replace-where.feature +++ b/features/search-replace-where.feature @@ -597,6 +597,36 @@ Feature: Test search-replace --where option | wp_idkeyed:body:ID = '1' | 1 | one foo | | wp_idkeyed::ID = '1' | 2 | one bar | + @require-mysql + Scenario Outline: Where on a table whose primary key is a prefix of a text column + Given a WP install + And I run `wp db query "CREATE TABLE wp_prefixed ( slug TEXT NOT NULL, title TEXT, body TEXT, PRIMARY KEY (slug(32)) )"` + And I run `wp db query "INSERT INTO wp_prefixed VALUES ('one-slug-that-is-longer-than-its-32-character-key', 'foo', 'foo'), ('two-slug-that-is-longer-than-its-32-character-key', 'foo', 'foo')"` + + When I run `wp search-replace foo bar --all-tables --where="wp_prefixed::slug = 'one-slug-that-is-longer-than-its-32-character-key'" --dry-run --format=count <flags>` + Then STDOUT should be: + """ + 2 + """ + + When I run `wp search-replace foo bar --all-tables --where="wp_prefixed::slug = 'one-slug-that-is-longer-than-its-32-character-key'" --format=count <flags>` + Then STDOUT should be: + """ + 2 + """ + + When I run `wp db query "SELECT CONCAT_WS('|', slug, title, body) FROM wp_prefixed ORDER BY slug" --skip-column-names` + Then STDOUT should be: + """ + one-slug-that-is-longer-than-its-32-character-key|bar|bar + two-slug-that-is-longer-than-its-32-character-key|foo|foo + """ + + Examples: + | flags | + | | + | --precise | + @require-mysql Scenario Outline: A failed row selection stops before any column is replaced Given a WP install diff --git a/src/Search_Replace_Command.php b/src/Search_Replace_Command.php index a13db92d..e33f2fb9 100644 --- a/src/Search_Replace_Command.php +++ b/src/Search_Replace_Command.php @@ -1871,6 +1871,25 @@ private function create_where_key_tables( $table, $primary_keys, $columns ) { $table_sql = self::esc_sql_ident( $table ); $suffix = substr( md5( uniqid( '', true ) ), 0, 8 ); + // The temporary table holds the full key values, but its primary key must index the same + // prefixes as the table's own, as a TEXT or BLOB column can only be indexed by a prefix. + $key_prefixes = array(); + // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- escaped through self::esc_sql_ident + foreach ( (array) $wpdb->get_results( "SHOW INDEX FROM $table_sql WHERE Key_name = 'PRIMARY'" ) as $index_col ) { + if ( isset( $index_col->Column_name, $index_col->Sub_part ) && (int) $index_col->Sub_part > 0 ) { + $key_prefixes[ $index_col->Column_name ] = (int) $index_col->Sub_part; + } + } + $key_index_sql = implode( + ', ', + array_map( + static function ( $key ) use ( $key_prefixes ) { + return self::esc_sql_ident( $key ) . ( isset( $key_prefixes[ $key ] ) ? "({$key_prefixes[ $key ]})" : '' ); + }, + $primary_keys + ) + ); + $key_clauses = array(); $key_tables = array(); foreach ( array_keys( $groups ) as $index => $condition ) { @@ -1879,7 +1898,7 @@ private function create_where_key_tables( $table, $primary_keys, $columns ) { $suppress_errors = $wpdb->suppress_errors(); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- escaped through self::esc_sql_ident, the --where clauses are raw SQL by design - $wpdb->query( "CREATE TEMPORARY TABLE $key_table_sql ( PRIMARY KEY ( $keys_sql ) ) SELECT $keys_sql FROM $table_sql WHERE $condition" ); + $wpdb->query( "CREATE TEMPORARY TABLE $key_table_sql ( PRIMARY KEY ( $key_index_sql ) ) SELECT $keys_sql FROM $table_sql WHERE $condition" ); $error = $wpdb->last_error; $wpdb->suppress_errors( $suppress_errors ); if ( $error ) { From 6333cb65b42da9089f1c4e8676afdee6408a1090 Mon Sep 17 00:00:00 2001 From: Pascal Birchler <pascal.birchler@gmail.com> Date: Thu, 26 Nov 2026 14:27:12 +0000 Subject: [PATCH 39/41] Flush the object cache before checking the title in the SQLite --where scenario The scenario reads the post title before the replacement, which puts it in a persistent object cache, and search-replace does not flush that cache (it only reminds to run `wp cache flush`), so the check after the replacement read the old title in the SQLite (Obj Cache) jobs. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01UWTd5pwpi2xQfDA6mUYkkx --- features/search-replace-where.feature | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/features/search-replace-where.feature b/features/search-replace-where.feature index 2397a361..53768647 100644 --- a/features/search-replace-where.feature +++ b/features/search-replace-where.feature @@ -721,7 +721,9 @@ Feature: Test search-replace --where option Success: Made 1 replacement. """ - When I run `wp post get {POST_ID} --field=title` + # The title was read above, so a persistent object cache still holds the old one. + When I run `wp cache flush` + And I run `wp post get {POST_ID} --field=title` Then STDOUT should be: """ Title bar From 2cf82b00f331336ddec710f3f6770463b6282f4b Mon Sep 17 00:00:00 2001 From: Pascal Birchler <pascal.birchler@gmail.com> Date: Thu, 26 Nov 2026 14:28:12 +0000 Subject: [PATCH 40/41] Read the primary key prefixes as arrays SHOW INDEX names its columns in mixed case, which the coding standards reject as object properties. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01UWTd5pwpi2xQfDA6mUYkkx --- src/Search_Replace_Command.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Search_Replace_Command.php b/src/Search_Replace_Command.php index e33f2fb9..4b69d6ca 100644 --- a/src/Search_Replace_Command.php +++ b/src/Search_Replace_Command.php @@ -1875,9 +1875,9 @@ private function create_where_key_tables( $table, $primary_keys, $columns ) { // prefixes as the table's own, as a TEXT or BLOB column can only be indexed by a prefix. $key_prefixes = array(); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- escaped through self::esc_sql_ident - foreach ( (array) $wpdb->get_results( "SHOW INDEX FROM $table_sql WHERE Key_name = 'PRIMARY'" ) as $index_col ) { - if ( isset( $index_col->Column_name, $index_col->Sub_part ) && (int) $index_col->Sub_part > 0 ) { - $key_prefixes[ $index_col->Column_name ] = (int) $index_col->Sub_part; + foreach ( (array) $wpdb->get_results( "SHOW INDEX FROM $table_sql WHERE Key_name = 'PRIMARY'", ARRAY_A ) as $index_col ) { + if ( isset( $index_col['Column_name'], $index_col['Sub_part'] ) && (int) $index_col['Sub_part'] > 0 ) { + $key_prefixes[ $index_col['Column_name'] ] = (int) $index_col['Sub_part']; } } $key_index_sql = implode( From 51f739f9aa6f5558a5068ebb6f190807a1883667 Mon Sep 17 00:00:00 2001 From: Pascal Birchler <pascal.birchler@gmail.com> Date: Thu, 26 Nov 2026 14:56:16 +0000 Subject: [PATCH 41/41] Read the title from the database in the SQLite --where scenario wp cache isn't available here (cache-command isn't a dependency), and wp post create already caches the post, so read post_title directly. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01UWTd5pwpi2xQfDA6mUYkkx --- features/search-replace-where.feature | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/features/search-replace-where.feature b/features/search-replace-where.feature index 53768647..e1c99bdd 100644 --- a/features/search-replace-where.feature +++ b/features/search-replace-where.feature @@ -709,7 +709,8 @@ Feature: Test search-replace --where option """ And the return code should be 1 - When I run `wp post get {POST_ID} --field=title` + # Read the title from the database: search-replace doesn't flush a persistent object cache. + When I run `wp db query "SELECT post_title FROM wp_posts WHERE ID = {POST_ID}" --skip-column-names` Then STDOUT should be: """ Title foo @@ -721,9 +722,7 @@ Feature: Test search-replace --where option Success: Made 1 replacement. """ - # The title was read above, so a persistent object cache still holds the old one. - When I run `wp cache flush` - And I run `wp post get {POST_ID} --field=title` + When I run `wp db query "SELECT post_title FROM wp_posts WHERE ID = {POST_ID}" --skip-column-names` Then STDOUT should be: """ Title bar