Skip to content

sqlstore: replace LIKE queries with range queries for index-friendly#1091

Open
tovmeod wants to merge 1 commit intotulir:mainfrom
tovmeod:optimize-like-to-range-queries
Open

sqlstore: replace LIKE queries with range queries for index-friendly#1091
tovmeod wants to merge 1 commit intotulir:mainfrom
tovmeod:optimize-like-to-range-queries

Conversation

@tovmeod
Copy link
Copy Markdown

@tovmeod tovmeod commented Mar 1, 2026

sqlstore: replace LIKE queries with range queries for index-friendly PN-to-LID migration

The MigratePNToLID and deleteAll* functions used LIKE patterns (e.g. their_id LIKE $2 || ':%') which PostgreSQL cannot optimize with btree indexes when the pattern is parameterized. This caused sequential scans on large tables (sender_keys 1.7M rows/2GB, sessions 248K rows/2.4GB) on every new sender during message decryption.

Replace LIKE with equivalent range queries using ASCII ordering:
their_id >= $2 || ':' AND their_id < $2 || ';'
(':' is ASCII 58, ';' is ASCII 59, so this matches exactly the same rows as LIKE 'phone:%')

This allows PostgreSQL to use the existing btree primary key indexes for efficient range scans instead of sequential table scans.

Also fix DeleteIdentity to use deleteIdentityQuery (exact match) instead of deleteAllIdentitiesQuery (was doing a LIKE match on a single address, which happened to work but was semantically wrong).

…PN-to-LID migration

The MigratePNToLID and deleteAll* functions used LIKE patterns (e.g.
`their_id LIKE $2 || ':%'`) which PostgreSQL cannot optimize with btree
indexes when the pattern is parameterized. This caused sequential scans
on large tables (sender_keys 1.7M rows/2GB, sessions 248K rows/2.4GB)
on every new sender during message decryption.

Replace LIKE with equivalent range queries using ASCII ordering:
  `their_id >= $2 || ':' AND their_id < $2 || ';'`
(':' is ASCII 58, ';' is ASCII 59, so this matches exactly the same
rows as LIKE 'phone:%')

This allows PostgreSQL to use the existing btree primary key indexes
for efficient range scans instead of sequential table scans.

Also fix DeleteIdentity to use deleteIdentityQuery (exact match)
instead of deleteAllIdentitiesQuery (was doing a LIKE match on a
single address, which happened to work but was semantically wrong).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant