Skip to content

Commit f9dd1b9

Browse files
swissspidyclaude
andauthored
Load posts in chunks in wp post list (#663)
* Load posts in chunks in `wp post list` `wp post list` loaded every matching post, including its full content, in a single query, primed their meta and term caches, and computed the permalink of every post even when the `url` field was not requested. On a site with ~100k posts this used ~900 MB of memory regardless of the requested fields. Query the IDs first, then load the posts in chunks with the same query arguments, clearing the object cache after each chunk, and only compute `url` when it is requested. The posts are passed to the formatter as a generator, which newer WP-CLI versions stream for CSV and JSON. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01D26yjkN2BiqCXT6p6o1WqS * Fix PHPStan findings, avoid the deprecated wp_clear_object_cache() Guard against WP_Query::$posts being null, and free the in-process object cache directly instead of through the deprecated helper, whose deprecation is reported differently depending on the PHPStan setup. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01D26yjkN2BiqCXT6p6o1WqS * Keep the object cache when listing computed post fields Fields like post meta are read through WP_Post::__get(), which uses the object cache. When the first post lacks such a field, the formatter can't stream and only reads the fields once all posts are loaded. By then the cache was cleared after each chunk, so every post needed another query, which made `wp post list --fields=ID,<meta key>` slower than before. Only clear the cache when all displayed fields are plain post properties. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01D26yjkN2BiqCXT6p6o1WqS * Always clear the object cache after each chunk of posts wp-cli/wp-cli#6426 makes the formatter read the requested fields of each item while it is current, also when it can't stream them. Post meta is therefore read before the cache of its chunk is cleared, so the cache no longer needs to be kept when computed fields are listed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01D26yjkN2BiqCXT6p6o1WqS * Test offsets and pages spanning several chunks in `wp post list` The chunk queries drop `offset` and `paged` because the ID query has already applied them. Cover a page and an offset that span more than one chunk, so applying them twice would drop posts and fail the test. Also cover that sticky posts are no longer prepended to the list, which matches what `--format=ids` already returned. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01UWTd5o4SXHZjE5AVf2xCLF * Assert the exact post in the sticky posts scenario Checking only that the sticky post is absent also passes when nothing is listed. Assert that the newest published post is the only one returned. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01UWTd5o4SXHZjE5AVf2xCLF --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 794bc5b commit f9dd1b9

2 files changed

Lines changed: 172 additions & 12 deletions

File tree

‎features/post.feature‎

Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1157,3 +1157,99 @@ Feature: Manage WordPress posts
11571157
2021-02-02
11581158
"""
11591159
And STDOUT should not be empty
1160+
1161+
Scenario: List more posts than are loaded from the database at a time
1162+
Given a WP install
1163+
And I run `wp post generate --count=1200 --post_date="2020-01-01 00:00:00"`
1164+
And I run `wp post list --post_status=publish --orderby=ID --order=asc --format=ids`
1165+
And save STDOUT as {IDS}
1166+
1167+
When I run `wp post list --post_status=publish --orderby=ID --order=asc --field=ID | tr '\n' ' ' | sed 's/ $//'`
1168+
Then STDOUT should be:
1169+
"""
1170+
{IDS}
1171+
"""
1172+
1173+
When I run `wp post list --post_status=publish --orderby=ID --order=asc --fields=ID,post_title --format=csv | wc -l`
1174+
Then STDOUT should contain:
1175+
"""
1176+
1202
1177+
"""
1178+
1179+
When I run `wp post list --post_status=publish --orderby=ID --order=desc --posts_per_page=2 --fields=ID,url --format=csv`
1180+
Then STDOUT should match /^ID,url\n(\d+),https?:\/\/example\.com\/\?p=\1\n(\d+),https?:\/\/example\.com\/\?p=\2$/
1181+
1182+
# An offset that spans more than one chunk must only be applied once.
1183+
When I run `wp post list --post_status=publish --orderby=ID --order=asc --posts_per_page=600 --offset=450 --format=ids`
1184+
Then save STDOUT as {OFFSET_IDS}
1185+
1186+
When I run `wp post list --post_status=publish --orderby=ID --order=asc --posts_per_page=600 --offset=450 --field=ID | tr '\n' ' ' | sed 's/ $//'`
1187+
Then STDOUT should be:
1188+
"""
1189+
{OFFSET_IDS}
1190+
"""
1191+
1192+
When I run `wp post list --post_status=publish --orderby=ID --order=asc --posts_per_page=600 --offset=450 --field=ID | wc -l`
1193+
Then STDOUT should contain:
1194+
"""
1195+
600
1196+
"""
1197+
1198+
When I run `wp post list --post_status=publish --orderby=ID --order=asc --posts_per_page=600 --paged=2 --format=ids`
1199+
Then save STDOUT as {PAGED_IDS}
1200+
1201+
When I run `wp post list --post_status=publish --orderby=ID --order=asc --posts_per_page=600 --paged=2 --field=ID | tr '\n' ' ' | sed 's/ $//'`
1202+
Then STDOUT should be:
1203+
"""
1204+
{PAGED_IDS}
1205+
"""
1206+
1207+
When I run `wp post list --post_status=publish --orderby=ID --order=asc --posts_per_page=600 --paged=2 --field=ID | wc -l`
1208+
Then STDOUT should contain:
1209+
"""
1210+
600
1211+
"""
1212+
1213+
Scenario: Sticky posts are not prepended to the post list
1214+
Given a WP install
1215+
And I run `wp post create --post_title=Sticky --post_status=publish --post_date="2020-01-01 00:00:00" --porcelain`
1216+
And save STDOUT as {STICKY}
1217+
And I run `wp option update sticky_posts '[{STICKY}]' --format=json`
1218+
And I run `wp post create --post_title=Draft --post_status=draft --porcelain`
1219+
And save STDOUT as {DRAFT}
1220+
And I run `wp post create --post_title=Latest --post_status=publish --porcelain`
1221+
And save STDOUT as {LATEST}
1222+
1223+
When I run `wp post list --post_status=draft --field=ID`
1224+
Then STDOUT should be:
1225+
"""
1226+
{DRAFT}
1227+
"""
1228+
1229+
When I run `wp post list --post_status=publish --orderby=ID --order=desc --posts_per_page=1 --field=ID`
1230+
Then STDOUT should be:
1231+
"""
1232+
{LATEST}
1233+
"""
1234+
1235+
Scenario: List post meta as a field for some posts only
1236+
Given a WP install
1237+
And I run `wp post create --post_title=First --post_status=publish --porcelain`
1238+
And save STDOUT as {FIRST}
1239+
And I run `wp post create --post_title=Second --post_status=publish --porcelain`
1240+
And save STDOUT as {SECOND}
1241+
And I run `wp post meta add {SECOND} batch_meta second-value`
1242+
1243+
When I run `wp post list --post__in={FIRST},{SECOND} --orderby=ID --order=asc --fields=ID,batch_meta --format=csv`
1244+
Then STDOUT should be:
1245+
"""
1246+
ID,batch_meta
1247+
{FIRST},
1248+
{SECOND},second-value
1249+
"""
1250+
1251+
When I try `wp post list --post__in={FIRST},{SECOND} --fields=ID,missing_meta --format=csv`
1252+
Then STDERR should be:
1253+
"""
1254+
Warning: Field not found in any item: missing_meta.
1255+
"""

‎src/Post_Command.php‎

Lines changed: 76 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,11 @@
2727
*/
2828
class Post_Command extends CommandWithDBObject {
2929

30+
/**
31+
* Number of posts `wp post list` loads from the database at a time.
32+
*/
33+
const LIST_CHUNK_SIZE = 500;
34+
3035
protected $obj_type = 'post';
3136
protected $obj_fields = [
3237
'ID',
@@ -1057,20 +1062,79 @@ public function list_( $args, $assoc_args ) {
10571062
$query = new WP_Query( $query_args );
10581063
$formatter->display_items( $query->posts ?? [] );
10591064
} else {
1060-
$query = new WP_Query( $query_args );
1061-
$posts = array_map(
1062-
function ( $post ) {
1063-
/**
1064-
* @var \WP_Post $post
1065-
*/
1065+
$need_url = 'url' === $formatter->field || in_array( 'url', (array) $formatter->fields, true );
1066+
$formatter->display_items( $this->query_posts_in_chunks( $query_args, $need_url ) );
1067+
}
1068+
}
1069+
1070+
/**
1071+
* Query posts in chunks, so that they don't all have to be held in memory at once.
1072+
*
1073+
* The IDs of all matching posts are queried first. The posts are then loaded a chunk
1074+
* at a time with the same query arguments, and the object cache is cleared after each
1075+
* chunk. Formats that can be written item by item are then streamed by the formatter.
1076+
*
1077+
* Fields that WP_Post computes on access, like post meta, are read from the object
1078+
* cache. The formatter reads the requested fields of each post while it is the current
1079+
* item, before the cache of its chunk is cleared, even when it can't stream them.
1080+
*
1081+
* @param array<string, mixed> $query_args WP_Query arguments.
1082+
* @param bool $need_url Whether to add the `url` property to each post.
1083+
* @return \Generator<int, \WP_Post>
1084+
*/
1085+
private function query_posts_in_chunks( $query_args, $need_url ) {
1086+
/** @var int[] $ids */
1087+
$ids = ( new WP_Query( array_merge( $query_args, [ 'fields' => 'ids' ] ) ) )->posts;
1088+
1089+
$chunk_args = $query_args;
1090+
unset( $chunk_args['offset'], $chunk_args['paged'], $chunk_args['page'], $chunk_args['nopaging'] );
1091+
// The order is restored from $ids below. Ordering by `post__in` in SQL would
1092+
// need a FIELD() call with one argument per post, which SQLite does not allow.
1093+
$chunk_args['orderby'] = 'none';
1094+
$chunk_args['no_found_rows'] = true;
1095+
$chunk_args['ignore_sticky_posts'] = true;
1096+
1097+
foreach ( array_chunk( $ids, self::LIST_CHUNK_SIZE ) as $chunk ) {
1098+
$chunk_args['post__in'] = $chunk;
1099+
$chunk_args['posts_per_page'] = count( $chunk );
1100+
1101+
$query = new WP_Query( $chunk_args );
1102+
1103+
$posts = [];
1104+
foreach ( $query->posts ?? [] as $post ) {
1105+
if ( $post instanceof \WP_Post ) {
1106+
$posts[ $post->ID ] = $post;
1107+
}
1108+
}
1109+
1110+
foreach ( $chunk as $id ) {
1111+
if ( ! isset( $posts[ $id ] ) ) {
1112+
continue;
1113+
}
10661114

1115+
$post = $posts[ $id ];
1116+
if ( $need_url ) {
10671117
// @phpstan-ignore property.notFound
1068-
$post->url = get_permalink( $post->ID );
1069-
return $post;
1070-
},
1071-
$query->posts ?? []
1072-
);
1073-
$formatter->display_items( $posts );
1118+
$post->url = get_permalink( $post );
1119+
}
1120+
yield $post;
1121+
}
1122+
1123+
unset( $posts, $query );
1124+
self::clear_runtime_object_cache();
1125+
}
1126+
}
1127+
1128+
/**
1129+
* Free the memory held by the in-process object cache.
1130+
*
1131+
* Persistent object caches are left alone unless they can flush their in-process part only.
1132+
*/
1133+
private static function clear_runtime_object_cache() {
1134+
if ( function_exists( 'wp_cache_flush_runtime' ) && function_exists( 'wp_cache_supports' ) && wp_cache_supports( 'flush_runtime' ) ) {
1135+
wp_cache_flush_runtime();
1136+
} elseif ( ! wp_using_ext_object_cache() ) {
1137+
wp_cache_flush();
10741138
}
10751139
}
10761140

0 commit comments

Comments
 (0)