Skip to content

Commit 5bd5d04

Browse files
committed
Load comments and users in chunks in wp comment list and wp user list
Like `wp post list`, query the IDs of all matching comments or users first, then load the objects a chunk at a time and clear the object cache after each chunk. Combined with the formatter streaming CSV and JSON output for iterators, the memory use no longer grows with the number of items. If a displayed field is read through the object cache, like user meta or the post title of a comment, the cache is kept. Also only compute the `url` field of comments, users and terms when it is displayed. For comments it took about 40% of the time. The chunk size and the cache helper move to CommandWithDBObject. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01D26yjkN2BiqCXT6p6o1WqS
1 parent c3563e6 commit 5bd5d04

7 files changed

Lines changed: 228 additions & 38 deletions

File tree

‎features/comment.feature‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -475,3 +475,24 @@ Feature: Manage WordPress comments
475475
And I run `wp comment unspam {COMMENT_ID} --url=www.example.com`
476476
And I run `wp comment trash {COMMENT_ID} --url=www.example.com`
477477
And I run `wp comment untrash {COMMENT_ID} --url=www.example.com`
478+
479+
Scenario: List more comments than are loaded from the database at a time
480+
Given a WP install
481+
And I run `wp comment generate --count=1200 --post_id=1`
482+
And I run `wp comment list --orderby=comment_ID --order=asc --format=ids`
483+
And save STDOUT as {IDS}
484+
485+
When I run `wp comment list --orderby=comment_ID --order=asc --field=comment_ID | tr '\n' ' ' | sed 's/ $//'`
486+
Then STDOUT should be:
487+
"""
488+
{IDS}
489+
"""
490+
491+
When I run `wp comment list --fields=comment_ID,comment_post_ID --format=csv | wc -l`
492+
Then STDOUT should contain:
493+
"""
494+
1202
495+
"""
496+
497+
When I run `wp comment list --orderby=comment_ID --order=asc --number=1 --fields=comment_ID,url --format=csv`
498+
Then STDOUT should match /^comment_ID,url\n(\d+),https?:\/\/example\.com\/\?p=1#comment-\1$/

‎features/user.feature‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1035,3 +1035,30 @@ Feature: Manage WordPress users
10351035
"""
10361036
true
10371037
"""
1038+
1039+
Scenario: List more users than are loaded from the database at a time
1040+
Given a WP install
1041+
And I run `wp user generate --count=600`
1042+
And I run `wp user meta update 1 batch_meta admin-value`
1043+
And I run `wp user list --orderby=ID --order=asc --format=ids`
1044+
And save STDOUT as {IDS}
1045+
1046+
When I run `wp user list --orderby=ID --order=asc --field=ID | tr '\n' ' ' | sed 's/ $//'`
1047+
Then STDOUT should be:
1048+
"""
1049+
{IDS}
1050+
"""
1051+
1052+
When I run `wp user list --fields=ID,user_login,roles --format=csv | wc -l`
1053+
Then STDOUT should contain:
1054+
"""
1055+
602
1056+
"""
1057+
1058+
When I run `wp user list --orderby=ID --order=asc --number=2 --fields=ID,batch_meta,roles --format=csv`
1059+
Then STDOUT should be:
1060+
"""
1061+
ID,batch_meta,roles
1062+
1,admin-value,administrator
1063+
2,,subscriber
1064+
"""

‎src/Comment_Command.php‎

Lines changed: 90 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -520,6 +520,15 @@ public function list_( $args, $assoc_args ) {
520520
$assoc_args['count'] = true;
521521
}
522522

523+
$need_url = 'url' === $formatter->field || in_array( 'url', (array) $formatter->fields, true );
524+
525+
// Threaded results are nested, so they can't be loaded in chunks.
526+
if ( ! in_array( $formatter->format, [ 'count', 'ids' ], true ) && empty( $assoc_args['hierarchical'] ) ) {
527+
$fields = $formatter->field ? [ $formatter->field ] : (array) $formatter->fields;
528+
$formatter->display_items( $this->query_comments_in_chunks( $assoc_args, $fields ) );
529+
return;
530+
}
531+
523532
$query = new WP_Comment_Query();
524533
$comments = $query->query( $assoc_args );
525534

@@ -541,7 +550,7 @@ public function list_( $args, $assoc_args ) {
541550
$items = wp_list_pluck( $comments, 'comment_ID' );
542551

543552
$comments = $items;
544-
} elseif ( is_array( $comments ) ) {
553+
} elseif ( is_array( $comments ) && $need_url ) {
545554
$comments = array_map(
546555
function ( $comment ) {
547556
/**
@@ -558,6 +567,86 @@ function ( $comment ) {
558567
}
559568
}
560569

570+
/**
571+
* Query comments in chunks, so that they don't all have to be held in memory at once.
572+
*
573+
* The IDs of all matching comments are queried first. The comments are then loaded
574+
* a chunk at a time, and the object cache is cleared after each chunk. Formats that
575+
* can be written item by item are then streamed by the formatter.
576+
*
577+
* Fields that WP_Comment reads from the comment's post are read from the object
578+
* cache. If any of them are displayed, the cache is kept, because the formatter may
579+
* only read them once all comments have been loaded.
580+
*
581+
* @param array<string, mixed> $query_args WP_Comment_Query arguments.
582+
* @param string[] $fields Fields that will be displayed.
583+
* @return \Generator<int, \WP_Comment>
584+
*/
585+
private function query_comments_in_chunks( $query_args, $fields ) {
586+
$need_url = in_array( 'url', $fields, true );
587+
$clear_cache = true;
588+
foreach ( $fields as $field ) {
589+
if ( 'url' !== $field && ! property_exists( 'WP_Comment', $field ) && ! property_exists( 'WP_Comment', 'comment_' . $field ) ) {
590+
$clear_cache = false;
591+
}
592+
}
593+
594+
$result = ( new WP_Comment_Query() )->query(
595+
array_merge(
596+
$query_args,
597+
[
598+
'fields' => 'ids',
599+
'count' => false,
600+
]
601+
)
602+
);
603+
604+
$ids = [];
605+
foreach ( is_array( $result ) ? $result : [] as $id ) {
606+
if ( is_numeric( $id ) ) {
607+
$ids[] = (int) $id;
608+
}
609+
}
610+
611+
$chunk_args = $query_args;
612+
unset( $chunk_args['number'], $chunk_args['offset'], $chunk_args['paged'] );
613+
// The order is restored from $ids below. Ordering by `comment__in` in SQL would
614+
// need a FIELD() call with one argument per comment, which SQLite does not allow.
615+
$chunk_args['orderby'] = 'none';
616+
$chunk_args['fields'] = '';
617+
$chunk_args['count'] = false;
618+
$chunk_args['no_found_rows'] = true;
619+
620+
foreach ( array_chunk( $ids, self::LIST_CHUNK_SIZE ) as $chunk ) {
621+
$chunk_args['comment__in'] = $chunk;
622+
623+
$comments = [];
624+
foreach ( (array) ( new WP_Comment_Query() )->query( $chunk_args ) as $comment ) {
625+
if ( $comment instanceof \WP_Comment ) {
626+
$comments[ (int) $comment->comment_ID ] = $comment;
627+
}
628+
}
629+
630+
foreach ( $chunk as $id ) {
631+
if ( ! isset( $comments[ (int) $id ] ) ) {
632+
continue;
633+
}
634+
635+
$comment = $comments[ (int) $id ];
636+
if ( $need_url ) {
637+
// @phpstan-ignore property.notFound
638+
$comment->url = get_comment_link( $comment );
639+
}
640+
yield $comment;
641+
}
642+
643+
unset( $comments );
644+
if ( $clear_cache ) {
645+
self::clear_runtime_object_cache();
646+
}
647+
}
648+
}
649+
561650
/**
562651
* Deletes a comment.
563652
*

‎src/Post_Command.php‎

Lines changed: 0 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -27,11 +27,6 @@
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-
3530
protected $obj_type = 'post';
3631
protected $obj_fields = [
3732
'ID',
@@ -1135,19 +1130,6 @@ private function query_posts_in_chunks( $query_args, $fields ) {
11351130
}
11361131
}
11371132

1138-
/**
1139-
* Free the memory held by the in-process object cache.
1140-
*
1141-
* Persistent object caches are left alone unless they can flush their in-process part only.
1142-
*/
1143-
private static function clear_runtime_object_cache() {
1144-
if ( function_exists( 'wp_cache_flush_runtime' ) && function_exists( 'wp_cache_supports' ) && wp_cache_supports( 'flush_runtime' ) ) {
1145-
wp_cache_flush_runtime();
1146-
} elseif ( ! wp_using_ext_object_cache() ) {
1147-
wp_cache_flush();
1148-
}
1149-
}
1150-
11511133
/**
11521134
* Generates some posts.
11531135
*

‎src/Term_Command.php‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -161,13 +161,17 @@ public function list_( $args, $assoc_args ) {
161161
}
162162
}
163163

164+
$need_url = 'url' === $formatter->field || in_array( 'url', (array) $formatter->fields, true );
165+
164166
$terms = array_map(
165-
function ( $term ) {
167+
function ( $term ) use ( $need_url ) {
166168
$term->count = (int) $term->count;
167169
$term->parent = (int) $term->parent;
168170

171+
if ( $need_url ) {
169172
// @phpstan-ignore property.notFound
170173
$term->url = get_term_link( $term );
174+
}
171175
return $term;
172176
},
173177
$terms

‎src/User_Command.php‎

Lines changed: 66 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -172,33 +172,81 @@ public function list_( $args, $assoc_args ) {
172172
}
173173
}
174174

175-
$users = get_users( $assoc_args );
176-
177175
if ( 'ids' === $formatter->format ) {
178-
echo implode( ' ', $users );
176+
echo implode( ' ', get_users( $assoc_args ) );
179177
} elseif ( 'count' === $formatter->format ) {
180-
$formatter->display_items( $users );
178+
$formatter->display_items( get_users( $assoc_args ) );
181179
} else {
182-
$iterator = Utils\iterator_map(
183-
$users,
184-
function ( $user ) {
185-
if ( ! is_object( $user ) ) {
186-
return $user;
187-
}
180+
$fields = $formatter->field ? [ $formatter->field ] : (array) $formatter->fields;
181+
$formatter->display_items( $this->query_users_in_chunks( $assoc_args, $fields ) );
182+
}
183+
}
184+
185+
/**
186+
* Query users in chunks, so that they don't all have to be held in memory at once.
187+
*
188+
* The IDs of all matching users are queried first. The users and their meta are then
189+
* loaded a chunk at a time, and the object cache is cleared after each chunk. Formats
190+
* that can be written item by item are then streamed by the formatter.
191+
*
192+
* User meta is read from the object cache. If any meta is displayed, the cache is
193+
* kept, because the formatter may only read it once all users have been loaded.
194+
*
195+
* @param array $query_args WP_User_Query arguments.
196+
* @param string[] $fields Fields that will be displayed.
197+
* @return \Generator<int, \WP_User>
198+
*/
199+
private function query_users_in_chunks( $query_args, $fields ) {
200+
$columns = [ 'ID', 'user_login', 'user_pass', 'user_nicename', 'user_email', 'user_url', 'user_registered', 'user_activation_key', 'user_status', 'display_name' ];
201+
$need_url = in_array( 'url', $fields, true );
202+
$clear_cache = true;
203+
foreach ( $fields as $field ) {
204+
if (
205+
! in_array( $field, [ 'url', 'roles' ], true )
206+
&& ! in_array( $field, $columns, true )
207+
&& ! in_array( 'user_' . $field, $columns, true )
208+
&& ! property_exists( 'WP_User', $field )
209+
) {
210+
$clear_cache = false;
211+
}
212+
}
188213

189-
/**
190-
* @var \WP_User $user
191-
*/
214+
$ids = array_map( 'intval', (array) get_users( array_merge( $query_args, [ 'fields' => 'ids' ] ) ) );
192215

193-
// @phpstan-ignore assign.propertyType
194-
$user->roles = implode( ',', $user->roles );
216+
$chunk_args = $query_args;
217+
unset( $chunk_args['number'], $chunk_args['offset'], $chunk_args['paged'] );
218+
// The order is restored from $ids below.
219+
$chunk_args['fields'] = 'all_with_meta';
220+
221+
foreach ( array_chunk( $ids, self::LIST_CHUNK_SIZE ) as $chunk ) {
222+
$chunk_args['include'] = $chunk;
223+
224+
$users = [];
225+
foreach ( get_users( $chunk_args ) as $user ) {
226+
if ( $user instanceof \WP_User ) {
227+
$users[ $user->ID ] = $user;
228+
}
229+
}
230+
231+
foreach ( $chunk as $id ) {
232+
if ( ! isset( $users[ $id ] ) ) {
233+
continue;
234+
}
235+
236+
$user = $users[ $id ];
237+
// @phpstan-ignore assign.propertyType
238+
$user->roles = implode( ',', $user->roles );
239+
if ( $need_url ) {
195240
// @phpstan-ignore property.notFound
196241
$user->url = get_author_posts_url( $user->ID, $user->user_nicename );
197-
return $user;
198242
}
199-
);
243+
yield $user;
244+
}
200245

201-
$formatter->display_items( $iterator );
246+
unset( $users );
247+
if ( $clear_cache ) {
248+
self::clear_runtime_object_cache();
249+
}
202250
}
203251
}
204252

‎src/WP_CLI/CommandWithDBObject.php‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,11 @@
1414
*/
1515
abstract class CommandWithDBObject extends WP_CLI_Command {
1616

17+
/**
18+
* Number of objects that list commands load from the database at a time.
19+
*/
20+
const LIST_CHUNK_SIZE = 500;
21+
1722
/**
1823
* @var string $object_type WordPress' expected name for the object.
1924
*/
@@ -184,4 +189,18 @@ protected function get_formatter( &$assoc_args ) {
184189
}
185190
return new Formatter( $assoc_args, $fields, $this->obj_type );
186191
}
192+
193+
/**
194+
* Free the memory held by the in-process object cache.
195+
*
196+
* List commands call this after each chunk of objects. Persistent object
197+
* caches are left alone unless they can flush their in-process part only.
198+
*/
199+
protected static function clear_runtime_object_cache() {
200+
if ( function_exists( 'wp_cache_flush_runtime' ) && function_exists( 'wp_cache_supports' ) && wp_cache_supports( 'flush_runtime' ) ) {
201+
wp_cache_flush_runtime();
202+
} elseif ( ! wp_using_ext_object_cache() ) {
203+
wp_cache_flush();
204+
}
205+
}
187206
}

0 commit comments

Comments
 (0)