diff --git a/features/search-replace-callback.feature b/features/search-replace-callback.feature new file mode 100644 index 00000000..6f05e3fc --- /dev/null +++ b/features/search-replace-callback.feature @@ -0,0 +1,331 @@ +Feature: Test search-replace --callback option + + @require-mysql + Scenario: Search replace with callback function + 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/features/search-replace-revisions.feature b/features/search-replace-revisions.feature new file mode 100644 index 00000000..94f8bb0d --- /dev/null +++ b/features/search-replace-revisions.feature @@ -0,0 +1,165 @@ +Feature: Test search-replace --revisions option + + @require-mysql + Scenario: Search replace without revisions (--no-revisions) + Given a WP install + + When I run `wp post create --post_title='Published foo' --post_name='1' --post_status='publish' --porcelain` + Then save STDOUT as {PUBLISHED_ID} + + When I run `wp post create --post_title='Draft foo' --post_status='draft' --porcelain` + Then save STDOUT as {DRAFT_ID} + + When I run `wp post create --post_title='Revision foo' --post_type='revision' --post_status='inherit' --post_parent={PUBLISHED_ID} --post_name='{PUBLISHED_ID}-revision-v1' --porcelain` + Then save STDOUT as {REVISION_ID} + + When I run `wp post meta add {PUBLISHED_ID} test_key 'published_foo_meta'` + Then STDOUT should not be empty + + When I run `wp post meta add {DRAFT_ID} test_key 'draft_foo_meta'` + Then STDOUT should not be empty + + # add_post_meta() would store the meta on the parent post, not the revision. + When I run `wp eval 'add_metadata( "post", {REVISION_ID}, "test_key", "revision_foo_meta" );'` + And I run `wp option add test_option 'option_foo'` + And I run `wp search-replace 'foo' 'bar' --no-revisions` + Then STDOUT should contain: + """ + Success: Made + """ + + When I run `wp post get {PUBLISHED_ID} --field=title` + Then STDOUT should be: + """ + Published bar + """ + + # Drafts are not revisions + When I run `wp post get {DRAFT_ID} --field=title` + Then STDOUT should be: + """ + Draft bar + """ + + When I run `wp post get {REVISION_ID} --field=title` + Then STDOUT should be: + """ + Revision foo + """ + + When I run `wp post meta get {PUBLISHED_ID} test_key` + Then STDOUT should be: + """ + published_bar_meta + """ + + When I run `wp post meta get {DRAFT_ID} test_key` + Then STDOUT should be: + """ + draft_bar_meta + """ + + When I run `wp eval 'echo get_metadata( "post", {REVISION_ID}, "test_key", true );'` + Then STDOUT should be: + """ + revision_foo_meta + """ + + # Tables other than posts and postmeta are still processed + When I run `wp option get test_option` + Then STDOUT should be: + """ + option_bar + """ + + @require-mysql + Scenario: Search replace with default revisions behavior + Given a WP install + + When I run `wp post create --post_title='Published fooooo' --post_name=1 --post_status='publish' --porcelain` + Then save STDOUT as {PUBLISHED_ID} + + When I run `wp post create --post_title='Revision fooooo' --post_type='revision' --post_status='inherit' --post_parent={PUBLISHED_ID} --post_name='{PUBLISHED_ID}-revision-v1' --porcelain` + Then save STDOUT as {REVISION_ID} + + # With default behavior (--revisions=true), both should be changed + When I run `wp search-replace 'fooooo' 'baz'` + Then STDOUT should contain: + """ + Success: Made 2 replacements. + """ + + When I run `wp post get {PUBLISHED_ID} --field=title` + Then STDOUT should be: + """ + Published baz + """ + + When I run `wp post get {REVISION_ID} --field=title` + Then STDOUT should be: + """ + Revision baz + """ + + @require-mysql + Scenario: Combining no-revisions with regex + Given a WP install + And I run `wp post create --post_title='Test foo123' --post_name='pubslug' --post_status='publish' --porcelain` + And save STDOUT as {PUB_ID} + And I run `wp post create --post_title='Test foo456' --post_type='revision' --post_status='inherit' --post_parent={PUB_ID} --post_name='{PUB_ID}-revision-v1' --porcelain` + And save STDOUT as {REVISION_ID} + + When I run `wp search-replace 'foo[0-9]+' 'bar999' --regex --no-revisions` + Then STDOUT should contain: + """ + Success: Made 1 replacement. + """ + + When I run `wp post get {PUB_ID} --field=title` + Then STDOUT should be: + """ + Test bar999 + """ + + When I run `wp post get {REVISION_ID} --field=title` + Then STDOUT should be: + """ + Test foo456 + """ + + @require-mysql + Scenario: Excluding revisions on all sites of a network + Given a WP multisite install + And I run `wp site create --slug=second --porcelain` + And I run `wp post create --url=example.com/second --post_title='Second foo' --post_name='secondslug' --post_status='publish' --porcelain` + And save STDOUT as {POST_ID} + And I run `wp post create --url=example.com/second --post_title='Second revision foo' --post_type='revision' --post_status='inherit' --post_parent={POST_ID} --post_name='{POST_ID}-revision-v1' --porcelain` + And save STDOUT as {REVISION_ID} + + When I run `wp search-replace 'foo' 'bar' --network --no-revisions` + Then STDOUT should contain: + """ + Success: + """ + + When I run `wp post get {POST_ID} --url=example.com/second --field=title` + Then STDOUT should be: + """ + Second bar + """ + + When I run `wp post get {REVISION_ID} --url=example.com/second --field=title` + Then STDOUT should be: + """ + Second revision foo + """ + + Scenario: Excluding revisions cannot be combined with an export + Given a WP install + + When I try `wp search-replace 'foo' 'bar' --no-revisions --export=out.sql` + Then STDERR should be: + """ + Error: You cannot supply --where or --no-revisions together with --export. + """ + And the return code should be 1 diff --git a/features/search-replace-where.feature b/features/search-replace-where.feature new file mode 100644 index 00000000..e1c99bdd --- /dev/null +++ b/features/search-replace-where.feature @@ -0,0 +1,739 @@ +Feature: Test search-replace --where option + + @require-mysql + Scenario: Search replace with where clause on single table + Given a WP install + And I run `wp post create --post_title='Test foo 1' --post_name=1 --post_status='publish' --porcelain` + And save STDOUT as {POST1_ID} + And I run `wp post create --post_title='Test foo 2' --post_name=2 --post_status='draft' --porcelain` + And save STDOUT as {POST2_ID} + + When I run `wp search-replace 'foo' 'bar' --where='posts::post_status="publish"'` + Then STDOUT should contain: + """ + Success: Made 1 replacement. + """ + + # Verify published post was changed + When I run `wp post get {POST1_ID} --field=title` + Then STDOUT should be: + """ + Test bar 1 + """ + + # Verify draft post was NOT changed + When I run `wp post get {POST2_ID} --field=title` + Then STDOUT should be: + """ + Test foo 2 + """ + + @require-mysql + Scenario: Search replace with where clause on specific column + Given a WP install + And I run `wp post create --post_title='Title xyzfoo' --post_name=1 --post_content='Content xyzfoo' --post_status='publish' --porcelain` + And save STDOUT as {POST_ID} + + # Only replace in post_title column where post_status is publish + When I run `wp search-replace 'xyzfoo' 'bar' --where='posts:post_title:post_status="publish"'` + Then STDOUT should contain: + """ + Success: Made 1 replacement. + """ + + When I run `wp post get {POST_ID} --field=title` + Then STDOUT should be: + """ + Title bar + """ + + # Content should remain unchanged since we specified only post_title column + When I run `wp post get {POST_ID} --field=content` + Then STDOUT should be: + """ + Content xyzfoo + """ + + @require-mysql + Scenario: Search replace with where clause using IN subquery + Given a WP install + And I run `wp post create --post_title='Post foo' --post_status='publish' --porcelain` + And save STDOUT as {PUBLISHED_ID} + And I run `wp post create --post_title='Draft foo' --post_status='draft' --porcelain` + And save STDOUT as {DRAFT_ID} + And I run `wp post meta add {PUBLISHED_ID} key1 'value_foo'` + And I run `wp post meta add {DRAFT_ID} key1 'value_foo'` + + # Only replace postmeta where post_id is in published posts + When I run `wp search-replace 'foo' 'bar' wp_postmeta --where='postmeta::post_id IN (SELECT ID FROM wp_posts WHERE post_status="publish")'` + Then STDOUT should contain: + """ + Success: Made 1 replacement. + """ + + # Check published post's meta was changed + When I run `wp post meta get {PUBLISHED_ID} key1` + Then STDOUT should be: + """ + value_bar + """ + + # Check draft post's meta was NOT changed + When I run `wp post meta get {DRAFT_ID} key1` + Then STDOUT should be: + """ + value_foo + """ + + @require-mysql + Scenario: Search replace with multiple where specifications + Given a WP install + And I run `wp post create --post_title='Pub foo' --post_name='pubpost' --post_status='publish' --porcelain` + And save STDOUT as {PUB_ID} + And I run `wp post create --post_title='Draft foo' --post_name='draftpost' --post_status='draft' --porcelain` + And save STDOUT as {DRAFT_ID} + And I run `wp option set test_option 'option_foo'` + + # Multiple where specs: posts must be published, options with specific name pattern + When I run `wp search-replace 'foo' 'bar' --where='posts::post_status="publish";options::option_name LIKE "test_%"'` + Then STDOUT should contain: + """ + Success: Made 2 replacements. + """ + + When I run `wp post get {PUB_ID} --field=title` + Then STDOUT should be: + """ + Pub bar + """ + + When I run `wp post get {DRAFT_ID} --field=title` + Then STDOUT should be: + """ + Draft foo + """ + + When I run `wp option get test_option` + Then STDOUT should be: + """ + option_bar + """ + + @require-mysql + Scenario: Search replace with where clause on multiple tables + Given a WP install + And I run `wp post create --post_title='Post fooooo' --post_name='postslug' --post_status='publish' --porcelain` + And save STDOUT as {POST_ID} + And I run `wp post meta add {POST_ID} testmeta 'meta_fooooo'` + And I run `wp option set opt_name 'opt_fooooo'` + + # Apply where to posts (published only) and postmeta (where meta_key LIKE 'test%') + # This should match the post_title and the testmeta value + When I run `wp search-replace 'fooooo' 'bar' --where='posts::post_status="publish";postmeta::meta_key LIKE "test%"'` + Then STDOUT should contain: + """ + Success: Made 2 replacements. + """ + + When I run `wp post get {POST_ID} --field=title` + Then STDOUT should be: + """ + Post bar + """ + + When I run `wp post meta get {POST_ID} testmeta` + Then STDOUT should be: + """ + meta_bar + """ + + # Options should not be affected by posts/postmeta where clause + When I run `wp option get opt_name` + Then STDOUT should be: + """ + opt_fooooo + """ + + @require-mysql + Scenario: Search replace combining where with dry-run + Given a WP install + And I run `wp post create --post_title='Test foo' --post_name='testslug' --post_status='publish' --porcelain` + And save STDOUT as {POST_ID} + And I run `wp post create --post_title='Draft foo' --post_name='draftslug' --post_status='draft' --porcelain` + And save STDOUT as {DRAFT_ID} + + When I run `wp search-replace 'foo' 'bar' --where='posts::post_status="publish"' --dry-run` + Then STDOUT should contain: + """ + Success: 1 replacement to be made. + """ + + # Verify nothing was actually changed + When I run `wp post get {POST_ID} --field=title` + Then STDOUT should be: + """ + Test foo + """ + + When I run `wp post get {DRAFT_ID} --field=title` + Then STDOUT should be: + """ + Draft foo + """ + + @require-mysql + Scenario: Search replace with where clause using wildcards in table names + Given a WP install + And I run `wp post create --post_title='Post foo' --post_name='postname' --post_content='Content foo' --post_status='publish' --porcelain` + And save STDOUT as {POST_ID} + And I run `wp post meta add {POST_ID} test_meta 'meta_foo'` + + # Use wildcard pattern for table matching with WHERE clause + When I run `wp search-replace 'foo' 'bar' 'wp_post*' --where='posts::post_status="publish";postmeta::post_id IN (SELECT ID FROM wp_posts WHERE post_status="publish")'` + Then STDOUT should contain: + """ + Success: Made 3 replacements. + """ + + When I run `wp post get {POST_ID} --field=title` + Then STDOUT should be: + """ + Post bar + """ + + When I run `wp post meta get {POST_ID} test_meta` + Then STDOUT should be: + """ + meta_bar + """ + + @require-mysql + Scenario: Where clause with conflicting column restrictions + Given a WP install + And I run `wp post create --post_title='Title foobar' --post_name='testpost' --post_content='Content foobar' --post_excerpt='Excerpt foobar' --post_status='publish' --porcelain` + And save STDOUT as {POST_ID} + + # Use --where to limit to specific column and row condition + When I try `wp search-replace 'foobar' 'replaced' --where='posts::post_status="publish"' --include-columns=post_title` + Then STDERR should contain: + """ + Warning: Column wildcard (*) was passed to --where. But --include-columns will still restrict replacements to columns: post_title + """ + + And STDOUT should contain: + """ + Success: Made 1 replacement. + """ + + # Verify only title was changed + When I run `wp post get {POST_ID} --field=title` + Then STDOUT should be: + """ + Title replaced + """ + + # Content should remain unchanged since we only specified post_title column + When I run `wp post get {POST_ID} --field=content` + Then STDOUT should be: + """ + Content foobar + """ + + # Now test --where to limit by status (create draft post) + When I run `wp post create --post_title='Draft foobar' --post_name='draftpost' --post_status='draft' --porcelain` + Then save STDOUT as {DRAFT_ID} + + # Replace only in published posts using --where + When I run `wp search-replace 'replaced' 'final' --where='posts::post_status="publish"'` + Then STDOUT should contain: + """ + Success: Made 1 replacement. + """ + + When I run `wp post get {POST_ID} --field=title` + Then STDOUT should be: + """ + Title final + """ + + # Draft post should remain unchanged + When I run `wp post get {DRAFT_ID} --field=title` + Then STDOUT should be: + """ + Draft foobar + """ + + @require-mysql + Scenario: Where clause with verbose output + Given a WP install + And I run `wp post create --post_title='Test foo' --post_status='publish' --porcelain` + And save STDOUT as {POST_ID} + + When I run `wp search-replace 'foo' 'bar' --where='posts::post_status="publish"' --verbose` + Then STDOUT should contain: + """ + Checking: wp_posts.post_title + """ + And STDOUT should contain: + """ + rows affected + """ + + @require-mysql + Scenario: Where specifications with and without columns for different tables + Given a WP install + And I run `wp post create --post_title='Title foo' --post_content='Content foo' --post_status='publish' --porcelain` + And save STDOUT as {POST_ID} + And I run `wp option add test_option 'option_foo'` + + When I run `wp search-replace 'foo' 'bar' --where='posts:post_title:post_status="publish";options::option_name="test_option"'` + Then STDOUT should contain: + """ + Success: Made 2 replacements. + """ + + When I run `wp post get {POST_ID} --field=title` + Then STDOUT should be: + """ + Title bar + """ + + When I run `wp post get {POST_ID} --field=content` + Then STDOUT should be: + """ + Content foo + """ + + When I run `wp option get test_option` + Then STDOUT should be: + """ + option_bar + """ + + @require-mysql + Scenario: Where conditions with OR and with LIKE patterns + Given a WP install + And I run `wp post create --post_title='Foo sale' --post_status='publish' --porcelain` + And save STDOUT as {SALE_ID} + And I run `wp post create --post_title='Foo other' --post_status='publish' --porcelain` + And save STDOUT as {OTHER_ID} + And I run `wp post create --post_title='nothing here' --post_status='private' --porcelain` + + When I run `wp search-replace 'Foo' 'Bar' --where='posts::post_status="publish" OR post_status="private"' --dry-run` + Then STDOUT should contain: + """ + Success: 2 replacements to be made. + """ + + When I run `wp search-replace 'Foo' 'Bar' --where='posts::post_title LIKE "%sale%"'` + Then STDOUT should contain: + """ + Success: Made 1 replacement. + """ + + When I run `wp post get {SALE_ID} --field=title` + Then STDOUT should be: + """ + Bar sale + """ + + When I run `wp post get {OTHER_ID} --field=title` + Then STDOUT should be: + """ + Foo other + """ + + @require-mysql + Scenario: Where clause with dry-run and a search string that differs when JSON-encoded + Given a WP install + And I run `wp post create --post_title='http://Foo.test published' --post_status='publish' --porcelain` + And I run `wp post create --post_title='http://Foo.test draft' --post_status='draft' --porcelain` + + When I run `wp search-replace 'http://Foo.test' 'http://bar.test' wp_posts --where='posts::post_status="publish"' --dry-run` + Then STDOUT should contain: + """ + 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 + 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 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: + """ + 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 + """ + + @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 | + + @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: 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: 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 + 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' <flags>` + 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: + """ + <?php + // A temporary table in information_schema is always denied, like a missing CREATE TEMPORARY TABLES privilege. + add_filter( + 'query', + function ( $query ) { + return preg_replace( '/^CREATE TEMPORARY TABLE /', 'CREATE TEMPORARY TABLE information_schema.', $query ); + } + ); + """ + 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_status = "publish" OR post_status = "draft"'` + Then STDERR should contain: + """ + Error: Could not create a temporary table to hold the rows of table 'wp_posts' that --where matches: + """ + And STDERR should contain: + """ + needs the CREATE TEMPORARY TABLES privilege; without it, replace one column per run + """ + And the return code should be 1 + + When I run `wp post get {POST_ID} --field=title` + Then STDOUT should be: + """ + Title foo + """ + + @require-sqlite + Scenario: Where conditions for several columns of a table are rejected on SQLite + 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:post_content LIKE "%foo%"'` + Then STDERR should contain: + """ + Error: Replacing several columns of table 'wp_posts' with --where is not supported on SQLite. + """ + And the return code should be 1 + + # 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 + """ + + When I run `wp search-replace foo bar --where='posts:post_title:post_content LIKE "%foo%"'` + Then STDOUT should contain: + """ + Success: Made 1 replacement. + """ + + 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 + """ + + Scenario: Where clause cannot be combined with an export + Given a WP install + + When I try `wp search-replace 'foo' 'bar' --where='posts::post_status="publish"' --export=out.sql` + Then STDERR should be: + """ + Error: You cannot supply --where or --no-revisions together with --export. + """ + And the return code should be 1 diff --git a/src/Search_Replace_Command.php b/src/Search_Replace_Command.php index d6e73804..4b69d6ca 100644 --- a/src/Search_Replace_Command.php +++ b/src/Search_Replace_Command.php @@ -127,6 +127,37 @@ 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<string, array<string, string[]>> + */ + private $where = []; + + /** + * Whether revisions (and their post meta) are excluded, via --no-revisions. + * + * @var bool + */ + private $exclude_revisions = false; + + /** + * @var string|false + */ + private $callback; + + /** + * The primary key columns of each table whose values must be compared as strings, + * i.e. those not of an integer type. + * + * @var array<string, string[]> + */ + private $string_primary_keys = array(); + /** * Searches/replaces strings in the database. * @@ -210,11 +241,28 @@ class Search_Replace_Command extends WP_CLI_Command { * specify multiple columns. Table-qualified column names ("table.column") * are supported to apply the inclusion to a specific table only. * + * [--where=<row-col-spec>] + * : Perform the replacement on specific rows. Use semi-colon to + * specify multiple specifications. Only the tables named in --where are processed. + * <row-col-spec> format: <table>[,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] + * : 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. * * [--recurse-objects] * : Enable recursing into objects to replace strings. Defaults to true; @@ -223,6 +271,15 @@ class Search_Replace_Command extends WP_CLI_Command { * [--verbose] * : Prints rows to the console as they're updated. * + * [--callback=<user-function>] + * : Runs a user-specified function on each string that contains <old> (or matches it, with --regex). The callback is called as follows: + * call_user_func( 'callback', $data, $new, $search_regex, $opts ) + * * $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 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). * Warning: search-replace will take about 15-20x longer when using --regex. @@ -345,6 +402,7 @@ public function __invoke( $args, $assoc_args ) { $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 ); + $this->callback = Utils\get_flag_value( $assoc_args, 'callback', false ); $default_regex_delimiter = false; @@ -388,20 +446,39 @@ 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->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 ) { + // 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; } + 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 ( 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; + } + $export = Utils\get_flag_value( $assoc_args, 'export' ); if ( null !== $export ) { 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; @@ -487,6 +564,17 @@ 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_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; + } + } + } // Identify views so they can be skipped; views are dynamic and cannot be directly modified. // The SQLite integration drop-in does not support SHOW FULL TABLES and WordPress @@ -532,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 @@ -553,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 ); } ) @@ -562,14 +656,20 @@ function ( $col ) use ( $table ) { // Gather what the per-column handling needs for all columns in a single table scan, // instead of scanning the table several times for every column. $column_stats = null; - if ( ! $this->regex && ! $this->verbose && 'sqlite' !== Utils\get_db_type() ) { + // 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() && ! $this->table_has_clauses( $table ) ) { $column_stats = self::get_column_stats( $table, $columns, $old ); } $stats_outdated = false; + list( $key_clauses, $key_tables ) = $this->create_where_key_tables( $table, $primary_keys, $columns ); + foreach ( $columns as $i => $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 ); WP_CLI::log( sprintf( 'Checking: %s.%s', $table, $col ) ); @@ -599,8 +699,9 @@ 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]' 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' ) ) { @@ -612,17 +713,22 @@ function ( $col ) use ( $table ) { 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 ); + $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 { - $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->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; } @@ -633,6 +739,8 @@ function ( $col ) use ( $table ) { $total += $count; } + + self::drop_tables( $key_tables ); } if ( $this->export_handle && STDOUT !== $this->export_handle ) { @@ -672,6 +780,14 @@ function ( $col ) use ( $table ) { } } + /** + * 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 ); @@ -682,7 +798,7 @@ private function php_export_table( $table, $old, $new ) { 'chunk_size' => $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 ); @@ -694,13 +810,21 @@ private function php_export_table( $table, $old, $new ) { $row_fields = array(); foreach ( $all_columns as $col ) { $value = $row->$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 ) && ( empty( $this->include_columns ) || in_array( $col, $this->include_columns, true ) || in_array( $table . '.' . $col, $this->include_columns, true ) ) ) { - $new_value = $replacer->run( $value ); + $new_value = $replacer->run( + $value, + false, + [ + 'table' => $table, + 'col' => $col, + 'key' => array_intersect_key( (array) $row, array_flip( $primary_keys ) ), + ] + ); if ( $new_value !== $value ) { ++$col_counts[ $col ]; $value = $new_value; @@ -733,7 +857,18 @@ 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 ) { + /** + * 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; $table_sql = self::esc_sql_ident( $table ); @@ -744,65 +879,76 @@ private function sql_handle_col( $col, $primary_keys, $table, $old, $new ) { 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 ); if ( $has_json ) { - $count += $this->log_sql_diff( $col, $primary_keys, $table, $old_json, $new_json ); + $count += $this->log_sql_diff( $col, $primary_keys, $table, $old_json, $new_json, $clauses ); } } 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;", '%' . 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 ); + } + 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 ); + $this->log_sql_diff( $col, $primary_keys, $table, $old, $new, $clauses ); if ( $has_json ) { - $this->log_sql_diff( $col, $primary_keys, $table, $old_json, $new_json ); + $this->log_sql_diff( $col, $primary_keys, $table, $old_json, $new_json, $clauses ); } } + $where = $clauses ? ' WHERE ' . implode( ' AND ', $clauses ) : ''; 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);", $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);", $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 ) ); } } - 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; } - private function php_handle_col( $col, $primary_keys, $table, $old, $new ) { + /** + * 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; $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 = ''; + $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 = "WHERE $base_key_condition"; + $base_key_condition[] = self::get_match_condition( $col, $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( @@ -825,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 @@ -835,7 +981,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; @@ -848,7 +1002,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(); } @@ -862,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; @@ -885,50 +1047,26 @@ 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 ) . ' )'; - } - - $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 ); + $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 ), $this->string_primary_keys[ $table ] ); + $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 ) ); + // 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; } + /** + * 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; @@ -973,16 +1111,7 @@ private function write_sql_row_fields( $table, $rows ) { if ( ( 0 === $index % $export_insert_size && $index > 0 ) || $index === $count ) { $sql .= ";\n"; - if ( method_exists( $wpdb, 'remove_placeholder_escape' ) ) { - // since 4.8.3 - - // @phpstan-ignore method.nonObject - $sql = $wpdb->remove_placeholder_escape( $wpdb->prepare( $sql, array_values( $values ) ) ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- verified inputs above - } else { - // 4.8.2 or less - // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- verified inputs above - $sql = $wpdb->prepare( $sql, array_values( $values ) ); - } + $sql = $wpdb->remove_placeholder_escape( $wpdb->prepare( $sql, array_values( $values ) ) ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- verified inputs above fwrite( $this->export_handle, $sql ); @@ -999,11 +1128,19 @@ 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, 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(); @@ -1015,6 +1152,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; @@ -1023,7 +1163,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 ); } /** @@ -1034,11 +1174,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; } /** @@ -1059,17 +1207,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]' )"; } @@ -1098,6 +1239,12 @@ private static function get_column_stats( $table, $columns, $old ) { return $stats; } + /** + * 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 ) ) { @@ -1108,6 +1255,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; @@ -1181,6 +1334,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 ''). * @@ -1216,17 +1383,18 @@ 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 ) { + 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 ) ); @@ -1237,9 +1405,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", '%' . self::esc_like( $old ) . '%' ) . $where_sql, ARRAY_N ); if ( empty( $results ) ) { return 0; @@ -1257,17 +1426,34 @@ private function log_sql_diff( $col, $primary_keys, $table, $old, $new ) { 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. + * @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 { @@ -1391,14 +1577,68 @@ 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. * - * @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 ) { @@ -1420,4 +1660,307 @@ 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; + $clauses = []; + 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>[,table]:[column,...]:<SQL-condition>." ); + } + list( $tables, $cols, $conditions ) = $parts; + $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; + } + } + } + + 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. + * + * 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 get_revision_clause( $table ) { + global $wpdb; + + 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 ); + } + + /** + * 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. + * @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, $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_key_value( (string) $last_values[ $i ], in_array( $primary_keys[ $i ], $string_keys, true ) ); + } + $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 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. + * @return array{0: array<string, string>, 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 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 array( array(), array() ); + } + + // Columns with the same conditions share the same rows. + $groups = array(); + foreach ( $columns as $col ) { + $clauses = $this->get_clauses( $table, $col ); + if ( $clauses ) { + $groups[ implode( ' AND ', $clauses ) ][] = $col; + } + } + if ( ! $groups ) { + return array( array(), array() ); + } + + 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 ) ); + } + + $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 ); + + // 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'", 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( + ', ', + 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 ) { + $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 + $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 ) { + 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 ) ); + } + $key_tables[] = $key_table; + + foreach ( $groups[ $condition ] as $col ) { + $key_clauses[ $col ] = "( $row_key_sql IN ( SELECT $keys_sql FROM $key_table_sql ) )"; + } + } + + 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" ); + } + } + + /** + * 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 ) { + $clauses = array_filter( + array_merge( + $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. + 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 5e3ff77b..06c46235 100644 --- a/src/WP_CLI/SearchReplacer.php +++ b/src/WP_CLI/SearchReplacer.php @@ -62,11 +62,23 @@ class SearchReplacer { */ private $log_data = []; + /** + * @var string[] + */ + private $log_new_data = []; + /** * @var int */ private $max_recursion; + /** + * @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; + /** * @var array<string, mixed> */ @@ -81,8 +93,9 @@ 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 ) { + 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; @@ -91,6 +104,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(); // Compute JSON-encoded versions (stripping outer quotes) for handling raw JSON values in the database. @@ -120,18 +134,26 @@ 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 Additional options passed through to the callback, + * like ['table' => $table, 'col' => $col, 'key' => $primary_key_values]. * - * @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 ) { - 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. + * 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() ) { + private function run_recursively( $data, $serialised, $recursion_level = 0, $visited_data = array(), $opts = [] ) { // some unseriliased data cannot be re-serialised eg. SimpleXMLElements try { @@ -178,11 +200,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 +219,7 @@ private function run_recursively( $data, $serialised, $recursion_level = 0, $vis try { $is_array_access = $data instanceof \ArrayAccess; foreach ( $data as $key => $value ) { - $value = $this->run_recursively( $value, false, $recursion_level + 1, $visited_data ); + $value = $this->run_recursively( $value, false, $recursion_level + 1, $visited_data, $opts ); if ( $is_array_access ) { $data[ $key ] = $value; } else { @@ -229,7 +251,12 @@ 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 ) { + // 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 ); + } if ( null === $result || PREG_NO_ERROR !== preg_last_error() ) { \WP_CLI::warning( sprintf( @@ -238,15 +265,35 @@ 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, null, $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->from_json !== $this->from ) { - $data = str_replace( $this->from_json, $this->to_json, $data ); + $result = str_replace( $this->from_json, $this->to_json, $result ); } } + + if ( $this->callback ) { + if ( false === $result ) { + \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 ); + } 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; + $this->log_data[] = $old_data; + $this->log_new_data[] = $data; } } @@ -268,17 +315,27 @@ 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(); } /** * 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 ) {