Skip to content

Commit 53d939c

Browse files
swissspidyclaude
andauthored
Scan each table once to check all columns (#246)
* 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 * Gather the column stats again after a write to the table A write to one column can change other columns of the same table through a BEFORE UPDATE trigger. The stats gathered up front could then be out of date for later columns: serialized data was replaced in SQL, which corrupts it, or a column with new matches was skipped. After each write, the stats of the remaining columns are now gathered again in one query. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01D26yjkN2BiqCXT6p6o1WqS --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 5181346 commit 53d939c

2 files changed

Lines changed: 166 additions & 12 deletions

File tree

‎features/search-replace.feature‎

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

‎src/Search_Replace_Command.php‎

Lines changed: 119 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -550,23 +550,48 @@ public function __invoke( $args, $assoc_args ) {
550550
continue;
551551
}
552552

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

558-
if ( in_array( $col, $this->skip_columns, true ) || in_array( $table . '.' . $col, $this->skip_columns, true ) ) {
559-
continue;
560-
}
569+
$stats_outdated = false;
570+
571+
foreach ( $columns as $i => $col ) {
561572

562573
if ( $this->verbose && 'count' !== $this->format ) {
563574
$this->start_time = microtime( true );
564575
WP_CLI::log( sprintf( 'Checking: %s.%s', $table, $col ) );
565576
}
566577

578+
// A write to one column can change others in the same table, through a trigger.
579+
// So gather the stats of the remaining columns again after each write.
580+
if ( $stats_outdated && null !== $column_stats ) {
581+
$column_stats = self::get_column_stats( $table, array_slice( $columns, $i ), $old );
582+
$stats_outdated = false;
583+
}
584+
567585
$serial_row = false;
586+
$stats = null !== $column_stats && isset( $column_stats[ $col ] ) ? $column_stats[ $col ] : null;
568587

569-
if ( ! $php_only && ! $this->regex ) {
588+
if ( null !== $stats ) {
589+
if ( ! $php_only && ! $this->regex && $stats['serialized'] ) {
590+
$serial_row = true;
591+
} elseif ( ! $php_only && ! $this->regex ) {
592+
$serial_row = null;
593+
}
594+
} elseif ( ! $php_only && ! $this->regex ) {
570595
$col_sql = self::esc_sql_ident( $col );
571596
$wpdb->last_error = '';
572597

@@ -585,11 +610,21 @@ public function __invoke( $args, $assoc_args ) {
585610
}
586611

587612
if ( $php_only || $this->regex || null !== $serial_row ) {
588-
$type = 'PHP';
589-
$count = $this->php_handle_col( $col, $primary_keys, $table, $old, $new );
613+
$type = 'PHP';
614+
// Nothing to replace in a column without matches.
615+
$count = null !== $stats && 0 === $stats['matches'] ? 0 : $this->php_handle_col( $col, $primary_keys, $table, $old, $new );
590616
} else {
591-
$type = 'SQL';
592-
$count = $this->sql_handle_col( $col, $primary_keys, $table, $old, $new );
617+
$type = 'SQL';
618+
if ( null !== $stats && ( 0 === $stats['matches'] || ( $this->dry_run && ! $this->log_handle ) ) ) {
619+
// The dry run count is the number of matching rows, which is already known.
620+
$count = $stats['matches'];
621+
} else {
622+
$count = $this->sql_handle_col( $col, $primary_keys, $table, $old, $new );
623+
}
624+
}
625+
626+
if ( $count && ! $this->dry_run && ! $this->export_handle ) {
627+
$stats_outdated = true;
593628
}
594629

595630
if ( $this->report && ( $count || ! $this->report_changed_only ) ) {
@@ -991,6 +1026,78 @@ private static function get_columns( $table ) {
9911026
return array( $primary_keys, $text_columns, $all_columns );
9921027
}
9931028

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

0 commit comments

Comments
 (0)