Skip to content

Commit 8ce0822

Browse files
committed
Collaboration: Merge MAX and COUNT into a single snapshot query
get_updates_after_cursor() ran a MAX(id) query on every call, followed by a separate COUNT(*) query only when updates existed (max_id > cursor). Both scan the same index range and can be combined into a single SELECT that returns both values unconditionally. Adds a null guard on the get_row() result to handle DB failures safely. Saves 1 query per room when updates exist.
1 parent 0a7c6be commit 8ce0822

1 file changed

Lines changed: 16 additions & 14 deletions

File tree

src/wp-includes/collaboration/class-wp-collaboration-table-storage.php

Lines changed: 16 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -140,9 +140,9 @@ public function get_update_count( string $room ): int {
140140
/**
141141
* Retrieves updates from a room after a given cursor.
142142
*
143-
* Uses a snapshot approach: captures MAX(id) first, then fetches rows
144-
* WHERE id > cursor AND id <= max_id. Updates arriving after the snapshot
145-
* are deferred to the next poll, never lost.
143+
* Uses a snapshot approach: captures MAX(id) and COUNT(*) in a single
144+
* query, then fetches rows WHERE id > cursor AND id <= max_id. Updates
145+
* arriving after the snapshot are deferred to the next poll, never lost.
146146
*
147147
* @since 7.0.0
148148
*
@@ -155,29 +155,31 @@ public function get_update_count( string $room ): int {
155155
public function get_updates_after_cursor( string $room, int $cursor ): array {
156156
global $wpdb;
157157

158-
// Snapshot the current max ID for this room.
159-
$max_id = (int) $wpdb->get_var(
158+
// Snapshot the current max ID and total row count in a single query.
159+
$snapshot = $wpdb->get_row(
160160
$wpdb->prepare(
161-
"SELECT COALESCE( MAX( id ), 0 ) FROM {$wpdb->collaboration} WHERE room = %s",
161+
"SELECT COALESCE( MAX( id ), 0 ) AS max_id, COUNT(*) AS total FROM {$wpdb->collaboration} WHERE room = %s",
162162
$room
163163
)
164164
);
165165

166+
if ( ! $snapshot ) {
167+
$this->room_cursors[ $room ] = 0;
168+
$this->room_update_counts[ $room ] = 0;
169+
return array();
170+
}
171+
172+
$max_id = (int) $snapshot->max_id;
173+
$total = (int) $snapshot->total;
174+
166175
$this->room_cursors[ $room ] = $max_id;
167176

168177
if ( 0 === $max_id || $max_id <= $cursor ) {
169178
$this->room_update_counts[ $room ] = 0;
170179
return array();
171180
}
172181

173-
// Count total rows for this room (used by compaction threshold logic).
174-
$this->room_update_counts[ $room ] = (int) $wpdb->get_var(
175-
$wpdb->prepare(
176-
"SELECT COUNT(*) FROM {$wpdb->collaboration} WHERE room = %s AND id <= %d",
177-
$room,
178-
$max_id
179-
)
180-
);
182+
$this->room_update_counts[ $room ] = $total;
181183

182184
// Fetch updates after the cursor up to the snapshot boundary.
183185
$rows = $wpdb->get_results(

0 commit comments

Comments
 (0)