Skip to content

Commit b7d9e53

Browse files
swissspidyclaude
andcommitted
Merge branch 'main' into pr/137-recurse-keys
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01UWTd5pwpi2xQfDA6mUYkkx
2 parents baabf9b + 17063d6 commit b7d9e53

6 files changed

Lines changed: 203 additions & 24 deletions

File tree

‎.github/workflows/copilot-setup-steps.yml‎

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -46,13 +46,13 @@ jobs:
4646
id: check_behat_file
4747
run: echo "files_exists=$(test -f behat.yml && echo true || echo false)" >> "$GITHUB_OUTPUT"
4848

49-
# Downloading and starting the database server is the slowest part of the
50-
# setup and it is independent of PHP and Composer, so it runs in the
51-
# background and is waited for right before the test database is prepared.
49+
# Not run in the background: Copilot code review builds its workflow from
50+
# these steps and failed validation while they used `background` and
51+
# `wait-all`. Also, the action unpacks its binaries with the system `tar`,
52+
# which fails to load libpcre2 while setup-php upgrades it with apt.
5253
- name: Setup MySQL Server
5354
if: steps.check_behat_file.outputs.files_exists == 'true'
54-
background: true
55-
uses: shogo82148/actions-setup-mysql@64d04a653a0c02af310009d36ce74bec5f4dce4f # v1
55+
uses: shogo82148/actions-setup-mysql@13a38f2af408e58a0c80168fc620a63a15357339 # v1
5656
with:
5757
mysql-version: '8.0' # Standard MySQL version for these tests
5858
auto-start: true
@@ -77,9 +77,6 @@ jobs:
7777
env:
7878
COMPOSER_ROOT_VERSION: dev-${{ github.event.repository.default_branch }}
7979

80-
- name: Wait for the MySQL server
81-
wait-all:
82-
8380
- name: Remove system MySQL binary
8481
if: steps.check_behat_file.outputs.files_exists == 'true'
8582
run: sudo rm -f /usr/bin/mysql /usr/bin/mysqldump
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
---
2+
name: Milestone Merged Pull Requests
3+
4+
'on':
5+
pull_request_target:
6+
types: [closed]
7+
branches:
8+
- main
9+
- master
10+
11+
permissions:
12+
issues: write
13+
pull-requests: write
14+
15+
jobs:
16+
milestone:
17+
uses: wp-cli/.github/.github/workflows/reusable-milestone-merged-prs.yml@main

‎AGENTS.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
This package is part of WP-CLI, the official command line interface for WordPress. For a detailed explanation of the project structure and development workflow, please refer to the main @README.md file.
44

5+
If the repository contains an @AGENTS.local.md file, read it as well. It holds instructions specific to this repository and takes precedence over this file where the two disagree.
6+
57
## Best Practices for Code Contributions
68

79
When contributing to this package, please adhere to the following guidelines:

‎README.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,11 @@ multisite, this will just be the tables for the current site unless
2323
Search/replace intelligently handles PHP serialized data, and does not
2424
change primary key values.
2525

26+
The JSON-encoded form of the search string is replaced as well, so a
27+
search for `https://example.com` also matches `https:\/\/example.com`
28+
in JSON stored in the database. This does not apply with `--regex`,
29+
where the pattern itself has to account for escaped slashes.
30+
2631
Tables without a primary key are skipped. To check whether a table has a
2732
primary key, run `wp db query 'DESCRIBE <table>'` and look for 'PRI' in
2833
the Key column.

‎features/search-replace.feature‎

Lines changed: 50 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1579,9 +1579,8 @@ Feature: Do global search/replace
15791579
@require-mysql
15801580
Scenario: Warn when updating a table fails due to a database error
15811581
Given a WP install
1582-
And I run `wp db query "CREATE TABLE wp_readonly_test ( id int(11) unsigned NOT NULL AUTO_INCREMENT, data TEXT, PRIMARY KEY (id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;"`
1583-
And I run `wp db query "INSERT INTO wp_readonly_test (data) VALUES ('old-value');"`
1584-
And I run `wp db query "CREATE TRIGGER prevent_update BEFORE UPDATE ON wp_readonly_test FOR EACH ROW SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Table is read-only';"`
1582+
And I run `wp db query "CREATE TABLE wp_readonly_test ( id int(11) unsigned NOT NULL AUTO_INCREMENT, data VARCHAR(191), PRIMARY KEY (id), UNIQUE KEY data (data) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;"`
1583+
And I run `wp db query "INSERT INTO wp_readonly_test (data) VALUES ('old-value'), ('new-value');"`
15851584

15861585
When I try `wp search-replace old-value new-value --all-tables-with-prefix`
15871586
Then STDERR should contain:
@@ -1590,7 +1589,54 @@ Feature: Do global search/replace
15901589
"""
15911590
And STDERR should contain:
15921591
"""
1593-
Table is read-only
1592+
Duplicate entry
1593+
"""
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
15941640
"""
15951641

15961642
@require-mysql

‎src/Search_Replace_Command.php‎

Lines changed: 124 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,11 @@ class Search_Replace_Command extends WP_CLI_Command {
145145
* Search/replace intelligently handles PHP serialized data, and does not
146146
* change primary key values.
147147
*
148+
* The JSON-encoded form of the search string is replaced as well, so a
149+
* search for `https://example.com` also matches `https:\/\/example.com`
150+
* in JSON stored in the database. This does not apply with `--regex`,
151+
* where the pattern itself has to account for escaped slashes.
152+
*
148153
* Tables without a primary key are skipped. To check whether a table has a
149154
* primary key, run `wp db query 'DESCRIBE <table>'` and look for 'PRI' in
150155
* the Key column.
@@ -555,23 +560,48 @@ public function __invoke( $args, $assoc_args ) {
555560
continue;
556561
}
557562

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

563-
if ( in_array( $col, $this->skip_columns, true ) || in_array( $table . '.' . $col, $this->skip_columns, true ) ) {
564-
continue;
565-
}
579+
$stats_outdated = false;
580+
581+
foreach ( $columns as $i => $col ) {
566582

567583
if ( $this->verbose && 'count' !== $this->format ) {
568584
$this->start_time = microtime( true );
569585
WP_CLI::log( sprintf( 'Checking: %s.%s', $table, $col ) );
570586
}
571587

588+
// A write to one column can change others in the same table, through a trigger.
589+
// So gather the stats of the remaining columns again after each write.
590+
if ( $stats_outdated && null !== $column_stats ) {
591+
$column_stats = self::get_column_stats( $table, array_slice( $columns, $i ), $old );
592+
$stats_outdated = false;
593+
}
594+
572595
$serial_row = false;
596+
$stats = null !== $column_stats && isset( $column_stats[ $col ] ) ? $column_stats[ $col ] : null;
573597

574-
if ( ! $php_only && ! $this->regex ) {
598+
if ( null !== $stats ) {
599+
if ( ! $php_only && ! $this->regex && $stats['serialized'] ) {
600+
$serial_row = true;
601+
} elseif ( ! $php_only && ! $this->regex ) {
602+
$serial_row = null;
603+
}
604+
} elseif ( ! $php_only && ! $this->regex ) {
575605
$col_sql = self::esc_sql_ident( $col );
576606
$wpdb->last_error = '';
577607

@@ -590,11 +620,21 @@ public function __invoke( $args, $assoc_args ) {
590620
}
591621

592622
if ( $php_only || $this->regex || null !== $serial_row ) {
593-
$type = 'PHP';
594-
$count = $this->php_handle_col( $col, $primary_keys, $table, $old, $new );
623+
$type = 'PHP';
624+
// Nothing to replace in a column without matches.
625+
$count = null !== $stats && 0 === $stats['matches'] ? 0 : $this->php_handle_col( $col, $primary_keys, $table, $old, $new );
595626
} else {
596-
$type = 'SQL';
597-
$count = $this->sql_handle_col( $col, $primary_keys, $table, $old, $new );
627+
$type = 'SQL';
628+
if ( null !== $stats && ( 0 === $stats['matches'] || ( $this->dry_run && ! $this->log_handle ) ) ) {
629+
// The dry run count is the number of matching rows, which is already known.
630+
$count = $stats['matches'];
631+
} else {
632+
$count = $this->sql_handle_col( $col, $primary_keys, $table, $old, $new );
633+
}
634+
}
635+
636+
if ( $count && ! $this->dry_run && ! $this->export_handle ) {
637+
$stats_outdated = true;
598638
}
599639

600640
if ( $this->report && ( $count || ! $this->report_changed_only ) ) {
@@ -996,6 +1036,78 @@ private static function get_columns( $table ) {
9961036
return array( $primary_keys, $text_columns, $all_columns );
9971037
}
9981038

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

0 commit comments

Comments
 (0)