perf(state): probe empty FTS index with EXISTS instead of COUNT(*)

_fts_external_index_empty_with_messages runs on every writable open via
the _init_schema fts_storage_version stamp condition. COUNT(*) is a full
b-tree scan on both messages and messages_fts_docsize (~100ms per open
on a 2M-row DB, measured); the function only ever compares against
zero, so EXISTS(SELECT 1 ...) gives the identical boolean in O(1).
This commit is contained in:
kshitijk4poor
2026-08-02 19:55:22 +05:30
committed by kshitij
parent b2d5995fc6
commit 2febb5823c
+12 -7
View File
@@ -366,16 +366,21 @@ class SessionSearchMixin:
never match.
"""
try:
n_msg = conn.execute("SELECT COUNT(*) FROM messages").fetchone()[0]
if int(n_msg) <= 0:
has_msg = conn.execute(
"SELECT EXISTS(SELECT 1 FROM messages)"
).fetchone()[0]
if not has_msg:
return False
# docsize is the authoritative "is this rowid indexed" surface for
# external-content FTS5; COUNT(*) on the virtual table itself is
# not reliable across SQLite builds.
n_fts = conn.execute(
"SELECT COUNT(*) FROM messages_fts_docsize"
# external-content FTS5; probing the virtual table itself is
# not reliable across SQLite builds. EXISTS instead of COUNT(*):
# this runs on every writable open via the _init_schema stamp
# condition, and COUNT(*) is a full b-tree scan (~100ms on a
# 2M-row table) while EXISTS is O(1).
has_fts = conn.execute(
"SELECT EXISTS(SELECT 1 FROM messages_fts_docsize)"
).fetchone()[0]
return int(n_fts) == 0
return not has_fts
except sqlite3.OperationalError:
# Table absent / FTS disabled mid-init — not this failure class.
return False