Existing rows are updated in place rather than deleted and reinserted. This is the busiest write path in the feature, and a delete/insert cycle on the same rows consumes meta_id values permanently and fragments the primary key, for no benefit — wp_postmeta has no unique key on (post_id, meta_key), so the rows to update have to be identified first either way.
private function write_last_sent_at_chunk( array $chunk ): void {
global $wpdb;
$post_ids = array_keys( $chunk );
/**
* The statements below interpolate a placeholder list whose length
* depends on the number of tokens. The interpolated strings are built
* from literals only — never from token data — and every value still
* travels through `$wpdb->prepare()`, which is why the sniffs are
* suppressed rather than the queries being restructured.
*/
// phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
$select = $wpdb->prepare(
sprintf(
"SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key = %%s AND post_id IN ( %s )",
implode( ', ', array_fill( 0, count( $post_ids ), '%d' ) )
),
array_merge( array( self::LAST_SENT_AT_META_KEY ), $post_ids )
);
// Checked before the read, not after: a null here would leave
// `last_result` holding whatever ran previously.
if ( ! is_string( $select ) || '' === $select ) {
$this->warn_last_sent_at_not_recorded( $post_ids, 'Could not build the query to read existing stamps, skipping chunk.' );
return;
}
// Run the statement rather than using `get_col()`, whose empty array
// means both "nothing matched" and "the read failed". Taking a failed
// read as "no rows exist" would insert duplicates that `wp_postmeta`
// has no unique key to prevent. `last_error` alone cannot be trusted
// either: `wpdb::query()` returns false before it clears the previous
// error when the `query` filter empties the statement.
$rows = $wpdb->query( $select );
if ( false === $rows ) {
$this->warn_last_sent_at_not_recorded(
$post_ids,
sprintf(
'Could not read existing stamps, skipping chunk. %s',
'' !== $wpdb->last_error ? $wpdb->last_error : 'The query did not run.'
)
);
return;
}
$existing = array_map( 'intval', wp_list_pluck( (array) $wpdb->last_result, 'post_id' ) );
// Tokens sent at the same moment share an UPDATE, so this is usually
// one query, without giving a token another's send time when a request
// spans a second boundary.
$by_timestamp = array();
foreach ( $chunk as $post_id => $timestamp ) {
$by_timestamp[ $timestamp ][] = $post_id;
}
foreach ( $by_timestamp as $timestamp => $ids ) {
$update_ids = array_values( array_intersect( $ids, $existing ) );
$insert_ids = array_values( array_diff( $ids, $existing ) );
if ( ! empty( $update_ids ) ) {
// Advance-only. Each request captures its timestamp when it
// dispatches and writes it on shutdown, so a slow request can
// reach this after a later one has already written a newer
// value. `Y-m-d H:i:s` compares lexicographically in date
// order, and a zero-row match returns 0 rather than false.
$update = $wpdb->prepare(
sprintf(
"UPDATE {$wpdb->postmeta} SET meta_value = %%s WHERE meta_key = %%s AND meta_value < %%s AND post_id IN ( %s )",
implode( ', ', array_fill( 0, count( $update_ids ), '%d' ) )
),
array_merge( array( $timestamp, self::LAST_SENT_AT_META_KEY, $timestamp ), $update_ids )
);
if ( ! is_string( $update ) || '' === $update ) {
$this->warn_last_sent_at_not_recorded( $update_ids, 'Could not build the update statement.' );
} elseif ( false === $wpdb->query( $update ) ) {
$this->warn_last_sent_at_not_recorded( $update_ids, $wpdb->last_error );
}
}
if ( ! empty( $insert_ids ) ) {
$insert_args = array();
foreach ( $insert_ids as $post_id ) {
$insert_args[] = $post_id;
$insert_args[] = self::LAST_SENT_AT_META_KEY;
$insert_args[] = $timestamp;
}
$insert = $wpdb->prepare(
sprintf(
"INSERT INTO {$wpdb->postmeta} ( post_id, meta_key, meta_value ) VALUES %s",
implode( ', ', array_fill( 0, count( $insert_ids ), '( %d, %s, %s )' ) )
),
$insert_args
);
if ( ! is_string( $insert ) || '' === $insert ) {
$this->warn_last_sent_at_not_recorded( $insert_ids, 'Could not build the insert statement.' );
} elseif ( false === $wpdb->query( $insert ) ) {
$this->warn_last_sent_at_not_recorded( $insert_ids, $wpdb->last_error );
}
}
}
// phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
// The rows were written behind the meta API's back, so the cached meta
// for these posts is now stale and must be dropped.
wp_cache_delete_multiple( $post_ids, 'post_meta' );
}