Skip to content

Commit 24d205f

Browse files
committed
Scan each table once to check all columns
For every text column, search-replace ran a REGEXP query to look for serialized data, which scans the whole table unless a match is found, and then a LIKE query to count or replace the matches, which scans it again. Reading the table dominates the cost of these queries, so on a large wp_posts table this meant ~28 full scans. Get the number of matching rows and whether there is serialized data for all columns of a table in a single query instead. Columns without matches are then skipped entirely, and dry runs use the counts directly. The SQL or PHP handling of each column, and therefore the report, is unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01D26yjkN2BiqCXT6p6o1WqS
1 parent be1577e commit 24d205f

2 files changed

Lines changed: 153 additions & 12 deletions

File tree

‎features/search-replace.feature‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1592,3 +1592,50 @@ Feature: Do global search/replace
15921592
"""
15931593
Table is read-only
15941594
"""
1595+
1596+
@require-mysql
1597+
Scenario: Report types and counts are based on serialized data in the column
1598+
Given a WP install
1599+
And I run `wp option add sr_serialized_match '{"url":"https://match.example/x"}' --format=json`
1600+
And I run `wp option add sr_plain_match 'see https://match.example/y'`
1601+
And I run `wp post create --post_title='Has match.example in it' --post_content='Plain match.example content' --porcelain`
1602+
And save STDOUT as {POST_ID}
1603+
1604+
# option_value holds serialized data (the option above), so it is handled in PHP.
1605+
# post_title has no serialized data, so it is handled in SQL. post_excerpt has no matches.
1606+
When I run `wp search-replace match.example other.example --dry-run --include-columns=option_value,post_title,post_excerpt`
1607+
Then STDOUT should be a table containing rows:
1608+
| Table | Column | Replacements | Type |
1609+
| wp_options | option_value | 2 | PHP |
1610+
| wp_posts | post_title | 1 | SQL |
1611+
| wp_posts | post_excerpt | 0 | SQL |
1612+
1613+
# A column with serialized data is reported as PHP even when none of it matches.
1614+
When I run `wp search-replace no-such-string other.example --dry-run --include-columns=option_value`
1615+
Then STDOUT should be a table containing rows:
1616+
| Table | Column | Replacements | Type |
1617+
| wp_options | option_value | 0 | PHP |
1618+
1619+
When I run `wp search-replace match.example other.example`
1620+
Then STDOUT should contain:
1621+
"""
1622+
Success: Made 4 replacements.
1623+
"""
1624+
1625+
When I run `wp option get sr_serialized_match --format=json`
1626+
Then STDOUT should be:
1627+
"""
1628+
{"url":"https:\/\/other.example\/x"}
1629+
"""
1630+
1631+
When I run `wp option get sr_plain_match`
1632+
Then STDOUT should be:
1633+
"""
1634+
see https://other.example/y
1635+
"""
1636+
1637+
When I run `wp post get {POST_ID} --field=post_content`
1638+
Then STDOUT should be:
1639+
"""
1640+
Plain other.example content
1641+
"""

‎src/Search_Replace_Command.php‎

Lines changed: 106 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -545,23 +545,39 @@ public function __invoke( $args, $assoc_args ) {
545545
continue;
546546
}
547547

548-
foreach ( $columns as $col ) {
549-
if ( ! empty( $this->include_columns ) && ! in_array( $col, $this->include_columns, true ) && ! in_array( $table . '.' . $col, $this->include_columns, true ) ) {
550-
continue;
551-
}
548+
$columns = array_values(
549+
array_filter(
550+
$columns,
551+
function ( $col ) use ( $table ) {
552+
return $this->is_column_searched( $table, $col );
553+
}
554+
)
555+
);
556+
557+
// Gather what the per-column handling needs for all columns in a single table scan,
558+
// instead of scanning the table several times for every column.
559+
$column_stats = null;
560+
if ( ! $this->regex && ! $this->verbose && 'sqlite' !== Utils\get_db_type() ) {
561+
$column_stats = self::get_column_stats( $table, $columns, $old );
562+
}
552563

553-
if ( in_array( $col, $this->skip_columns, true ) || in_array( $table . '.' . $col, $this->skip_columns, true ) ) {
554-
continue;
555-
}
564+
foreach ( $columns as $col ) {
556565

557566
if ( $this->verbose && 'count' !== $this->format ) {
558567
$this->start_time = microtime( true );
559568
WP_CLI::log( sprintf( 'Checking: %s.%s', $table, $col ) );
560569
}
561570

562571
$serial_row = false;
572+
$stats = null !== $column_stats && isset( $column_stats[ $col ] ) ? $column_stats[ $col ] : null;
563573

564-
if ( ! $php_only && ! $this->regex ) {
574+
if ( null !== $stats ) {
575+
if ( ! $php_only && ! $this->regex && $stats['serialized'] ) {
576+
$serial_row = true;
577+
} elseif ( ! $php_only && ! $this->regex ) {
578+
$serial_row = null;
579+
}
580+
} elseif ( ! $php_only && ! $this->regex ) {
565581
$col_sql = self::esc_sql_ident( $col );
566582
$wpdb->last_error = '';
567583

@@ -580,11 +596,17 @@ public function __invoke( $args, $assoc_args ) {
580596
}
581597

582598
if ( $php_only || $this->regex || null !== $serial_row ) {
583-
$type = 'PHP';
584-
$count = $this->php_handle_col( $col, $primary_keys, $table, $old, $new );
599+
$type = 'PHP';
600+
// Nothing to replace in a column without matches.
601+
$count = null !== $stats && 0 === $stats['matches'] ? 0 : $this->php_handle_col( $col, $primary_keys, $table, $old, $new );
585602
} else {
586-
$type = 'SQL';
587-
$count = $this->sql_handle_col( $col, $primary_keys, $table, $old, $new );
603+
$type = 'SQL';
604+
if ( null !== $stats && ( 0 === $stats['matches'] || ( $this->dry_run && ! $this->log_handle ) ) ) {
605+
// The dry run count is the number of matching rows, which is already known.
606+
$count = $stats['matches'];
607+
} else {
608+
$count = $this->sql_handle_col( $col, $primary_keys, $table, $old, $new );
609+
}
588610
}
589611

590612
if ( $this->report && ( $count || ! $this->report_changed_only ) ) {
@@ -986,6 +1008,78 @@ private static function get_columns( $table ) {
9861008
return array( $primary_keys, $text_columns, $all_columns );
9871009
}
9881010

1011+
/**
1012+
* Whether a column is searched, given the --include-columns and --skip-columns options.
1013+
*
1014+
* @param string $table Table name.
1015+
* @param string $col Column name.
1016+
* @return bool
1017+
*/
1018+
private function is_column_searched( $table, $col ) {
1019+
if ( ! empty( $this->include_columns ) && ! in_array( $col, $this->include_columns, true ) && ! in_array( $table . '.' . $col, $this->include_columns, true ) ) {
1020+
return false;
1021+
}
1022+
1023+
return ! in_array( $col, $this->skip_columns, true ) && ! in_array( $table . '.' . $col, $this->skip_columns, true );
1024+
}
1025+
1026+
/**
1027+
* Count the rows matching the search string and detect serialized data, for all given columns at once.
1028+
*
1029+
* The cost of these checks is dominated by reading the table, so doing them in one
1030+
* query rather than one or two queries per column makes large tables much faster.
1031+
*
1032+
* @param string $table Table name.
1033+
* @param string[] $columns Column names.
1034+
* @param string $old Search string.
1035+
* @return array<string, array{matches: int, serialized: bool}>|null Stats per column, or null if they could not be determined.
1036+
*/
1037+
private static function get_column_stats( $table, $columns, $old ) {
1038+
global $wpdb;
1039+
1040+
if ( empty( $columns ) ) {
1041+
return array();
1042+
}
1043+
1044+
$old_json = self::json_encode_strip_quotes( $old );
1045+
$selects = array();
1046+
foreach ( $columns as $col ) {
1047+
$col_sql = self::esc_sql_ident( $col );
1048+
// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- escaped through self::esc_sql_ident
1049+
$match = $wpdb->prepare( "$col_sql LIKE BINARY %s", '%' . self::esc_like( $old ) . '%' );
1050+
if ( $old_json !== $old ) {
1051+
// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- escaped through self::esc_sql_ident
1052+
$match = "( $match OR " . $wpdb->prepare( "$col_sql LIKE BINARY %s", '%' . self::esc_like( $old_json ) . '%' ) . ' )';
1053+
}
1054+
$selects[] = "SUM( $match )";
1055+
$selects[] = "MAX( $col_sql REGEXP '^[aiO]:[1-9]' )";
1056+
}
1057+
1058+
$table_sql = self::esc_sql_ident( $table );
1059+
$wpdb->last_error = '';
1060+
$suppress_errors = $wpdb->suppress_errors();
1061+
$sql = 'SELECT ' . implode( ', ', $selects ) . " FROM $table_sql";
1062+
// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- identifiers escaped through self::esc_sql_ident, values prepared above
1063+
$row = $wpdb->get_row( $sql, ARRAY_N );
1064+
$wpdb->suppress_errors( $suppress_errors );
1065+
1066+
if ( $wpdb->last_error || ! is_array( $row ) ) {
1067+
// E.g. the regex fails for some column; fall back to checking the columns one by one.
1068+
$wpdb->last_error = '';
1069+
return null;
1070+
}
1071+
1072+
$stats = array();
1073+
foreach ( $columns as $i => $col ) {
1074+
$stats[ $col ] = array(
1075+
'matches' => (int) $row[ 2 * $i ],
1076+
'serialized' => (bool) $row[ 2 * $i + 1 ],
1077+
);
1078+
}
1079+
1080+
return $stats;
1081+
}
1082+
9891083
private static function is_text_col( $type ) {
9901084
foreach ( array( 'text', 'varchar' ) as $token ) {
9911085
if ( false !== stripos( $type, $token ) ) {

0 commit comments

Comments
 (0)