perf(sqlite): swap node:sqlite for better-sqlite3 + cache prepared stmts
Replaces the experimental `node:sqlite` builtin with the stable
`better-sqlite3` wrapper across the two hot SQLite users — the
OneBot message-store and the bridge identity-service. While the API
surface is essentially identical (sync, prepared-statement-driven,
`Database`/`Statement` shape), better-sqlite3 (a) doesn't carry the
"ExperimentalWarning: SQLite is an experimental feature" baggage
that ships with `node:sqlite`, (b) has a more mature C++ binding
that consistently outperforms the builtin by ~30-50%, and (c)
encourages reusing `Statement` objects by design — exactly the win
the second half of this commit is after.
Why both at once
----------------
Caching prepared statements (was P1 in the RoadMap-#5 analysis) is
the largest single optimization opportunity on the SQLite path. The
old shape was the textbook SQLite anti-pattern:
// every call re-parsed the SQL
this.db.prepare(BIG_SQL_STRING).run(...);
Each `prepare(sql)` runs the full SQL parser + planner — for simple
inserts/updates/selects that dominates wall-clock cost. Doing both
the driver swap AND the statement caching in one commit lets the
benchmark numbers attribute the combined effect honestly; splitting
them would have double-charged the same disruption budget.
What changed code-wise
----------------------
**messageStore** — 8 distinct SQL templates, all now `readonly`
fields prepared once in the constructor:
- stmtStoreEvent — INSERT/UPDATE event row + JSON payload
- stmtStoreMeta — INSERT/UPDATE meta-only row
- stmtFindEvent — single-row SELECT by message_hash
- stmtFindMeta — single-row SELECT (full meta columns)
- stmtResolveReplyGroup, stmtResolveReplyPrivate
— 2 variants for the reply-id lookup
- stmtListEventsAnchored, stmtListEventsLatest
— 2 variants for /get_history_msg
**identity-service** — 25+ distinct statements. Used a Map-based
`pstmt(sql)` memoization helper rather than enumerating all 25 as
named fields (call sites stay readable; Map lookup is O(1) hash +
string-eq, negligible next to the SQL parse it replaces). The
helper short-circuits to the cached `Statement` on second-and-later
calls.
API differences from node:sqlite (handled in this commit):
- `import { DatabaseSync } from 'node:sqlite'`
→ `import Database from 'better-sqlite3'`
- `new DatabaseSync(path)` → `new Database(path)`
- `db.exec('PRAGMA journal_mode = WAL')`
→ `db.pragma('journal_mode = WAL')`
- `db.exec('BEGIN' / 'COMMIT' / 'ROLLBACK')` — kept as-is; both
drivers accept raw `exec()` for transaction control. The
`db.transaction()` higher-order wrapper is more idiomatic
but the existing manual control already works and changing
it would invalidate the `transaction()` helper's matched
try/catch shape.
vite build wiring:
- `node:sqlite` removed from the externals list
- `better-sqlite3` added — must stay external because it has a
native binding (`require('./build/Release/better_sqlite3.node')`)
that Vite can't bundle. Vendoring the prebuilt `.node` into
`packages/runtime/native/` is a follow-up packaging task; the
workspace `pnpm install` already places the binding under
`node_modules` so dev + tests work today.
Bench results (RoadMap #5 baseline → after)
-------------------------------------------
@snowluma/bridge — recv pipeline (with SQLite identity writes):
group_member_join 17.5 μs/op → 4.7 μs/op (~3.7x faster)
group_message text 0.42→0.42 μs (no path change)
group_message mixed 0.67→0.67 μs (no path change)
@snowluma/onebot — send pipeline:
messageStore.storeMeta 17.0 μs/op → 10.9 μs/op (~1.6x)
messageStore.storeEvent 23.2 μs/op → 18.2 μs/op (~1.3x)
messageStore.findMeta hit 5.4 μs/op → 1.3 μs/op (~4x)
messageStore.findMeta miss 3.7 μs/op → 0.7 μs/op (~5x)
messageStore.findEvent 3.8 μs/op → 1.7 μs/op (~2.3x)
Read paths gained the most because they're parse-bound (small SQL
+ short execution → the parser was most of the cost). Writes gained
less because the fsync/journal overhead on each commit still
dominates the parse savings. Combined send hot path (storeMeta +
storeEvent, called on every outbound message + the /get_msg-fix
self-event store) drops from ~40 μs to ~29 μs — about a 27%
reduction per message sent.
Verification
------------
- pnpm -r typecheck: all 11 projects clean
- @snowluma/onebot test suite: 250/250
- @snowluma/core test suite: 302/302
- Combined: 552/552 (unchanged baseline)
- Vite build (with stubbed native binary): clean, 2.84 MB / 223 KB
gzip (matches pre-Phase-2 envelope after removing the better-
sqlite3 inline-bundle attempt — externalizing it shaves the
~30 KB regression we saw mid-flight)
Follow-up (next commits in this series)
---------------------------------------
- Skip rememberGroupMemberIdentity DB write when the (uid, uin,
nickname, card) tuple is unchanged in the in-memory cache.
- Drop the `Buffer.from(pkt.body)` allocation in msg-push context.
- Synchronous fast-path for elementsToJson when no async resolver
is wired.
- Vendor `better-sqlite3` prebuilt `.node` into the runtime/native
layout for the production package step.
This commit is contained in:
7 files changed
+440
-98
No files matched your search
@@ -119,9 +119,11 @@
|
||||
"dependencies": {
|
||||
"@snowluma/common": "workspace:*",
|
||||
"@snowluma/proto-defs": "workspace:*",
|
||||
"@snowluma/proton": "workspace:*"
|
||||
"@snowluma/proton": "workspace:*",
|
||||
"better-sqlite3": "^11.7.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/better-sqlite3": "^7.6.13",
|
||||
"@types/node": "^24.12.2",
|
||||
"typescript": "catalog:",
|
||||
"vite": "catalog:",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { DatabaseSync } from 'node:sqlite';
|
||||
import Database from 'better-sqlite3';
|
||||
|
||||
import type {
|
||||
FriendInfo, GroupMemberInfo, QQGroupInfo,
|
||||
@@ -109,7 +109,14 @@ export class IdentityService {
|
||||
private readonly uidByUin = new Map<number, string>();
|
||||
|
||||
// ─── Persistence + fetcher ───
|
||||
private readonly db: DatabaseSync | null;
|
||||
private readonly db: Database.Database | null;
|
||||
// Prepared-statement cache. Every `.prepare(sql)` call in this
|
||||
// service re-parses the SQL — that's the SQLite anti-pattern
|
||||
// RoadMap #5 is fixing. We memoize by the SQL string itself so the
|
||||
// call sites stay readable (no need to enumerate 20+ named fields
|
||||
// upfront); the Map lookup is O(1) hash + string-eq, which is
|
||||
// negligible next to the SQL parse it replaces.
|
||||
private readonly stmtCache_ = new Map<string, Database.Statement>();
|
||||
private inTransaction = false;
|
||||
private fetcher: IdentityFetcher | null = null;
|
||||
private readonly log: Logger;
|
||||
@@ -127,13 +134,23 @@ export class IdentityService {
|
||||
}
|
||||
|
||||
fs.mkdirSync(path.dirname(dbPath), { recursive: true });
|
||||
this.db = new DatabaseSync(dbPath);
|
||||
this.db.exec('PRAGMA journal_mode = WAL');
|
||||
this.db.exec('PRAGMA synchronous = NORMAL');
|
||||
this.db = new Database(dbPath);
|
||||
this.db.pragma('journal_mode = WAL');
|
||||
this.db.pragma('synchronous = NORMAL');
|
||||
this.initSchema();
|
||||
this.loadSnapshot();
|
||||
}
|
||||
|
||||
/** Cached `prepare(sql)`. First call per unique SQL parses; later
|
||||
* calls reuse the same `Statement` object. See `stmtCache_`. */
|
||||
private pstmt(sql: string): Database.Statement {
|
||||
let cached = this.stmtCache_.get(sql);
|
||||
if (cached !== undefined) return cached;
|
||||
cached = this.db!.prepare(sql);
|
||||
this.stmtCache_.set(sql, cached);
|
||||
return cached;
|
||||
}
|
||||
|
||||
static openForUin(uin: string, dataRoot = 'data'): IdentityService {
|
||||
return new IdentityService(uin, path.join(dataRoot, uin, 'snowluma_identity.db'));
|
||||
}
|
||||
@@ -238,7 +255,7 @@ export class IdentityService {
|
||||
|
||||
if (!this.db) return null;
|
||||
if (groupId !== undefined) {
|
||||
const row = this.db.prepare(
|
||||
const row = this.pstmt(
|
||||
`SELECT uin FROM group_members
|
||||
WHERE group_id = ? AND uid = ? AND uin IS NOT NULL
|
||||
ORDER BY active DESC, updated_at DESC
|
||||
@@ -248,7 +265,7 @@ export class IdentityService {
|
||||
if (uin !== null) return uin;
|
||||
}
|
||||
|
||||
const row = this.db.prepare(
|
||||
const row = this.pstmt(
|
||||
'SELECT uin FROM users WHERE uid = ? AND uin IS NOT NULL LIMIT 1',
|
||||
).get(normalized) as { uin: number | null } | undefined;
|
||||
return normalizeUin(row?.uin);
|
||||
@@ -267,7 +284,7 @@ export class IdentityService {
|
||||
|
||||
if (!this.db) return null;
|
||||
if (groupId !== undefined) {
|
||||
const row = this.db.prepare(
|
||||
const row = this.pstmt(
|
||||
`SELECT uid FROM group_members
|
||||
WHERE group_id = ? AND uin = ? AND uid IS NOT NULL
|
||||
ORDER BY active DESC, updated_at DESC
|
||||
@@ -277,7 +294,7 @@ export class IdentityService {
|
||||
if (uid) return uid;
|
||||
}
|
||||
|
||||
const row = this.db.prepare(
|
||||
const row = this.pstmt(
|
||||
'SELECT uid FROM users WHERE uin = ? AND uid IS NOT NULL LIMIT 1',
|
||||
).get(normalized) as { uid: string | null } | undefined;
|
||||
return normalizeUid(row?.uid) || null;
|
||||
@@ -289,7 +306,7 @@ export class IdentityService {
|
||||
this.friends_ = friends;
|
||||
for (const friend of friends) this.rememberUidUin(friend.uid, friend.uin);
|
||||
this.runWrite('friends', () => this.transaction(() => {
|
||||
this.db!.prepare('UPDATE users SET is_friend = 0, updated_at = ? WHERE is_friend = 1')
|
||||
this.pstmt('UPDATE users SET is_friend = 0, updated_at = ? WHERE is_friend = 1')
|
||||
.run(nowSeconds());
|
||||
for (const friend of friends) {
|
||||
this.upsertUser({
|
||||
@@ -307,7 +324,7 @@ export class IdentityService {
|
||||
rememberGroups(groups: QQGroupInfo[]): void {
|
||||
this.setGroupsInMemory(groups);
|
||||
this.runWrite('groups', () => this.transaction(() => {
|
||||
this.db!.prepare('UPDATE groups SET active = 0, updated_at = ? WHERE active = 1')
|
||||
this.pstmt('UPDATE groups SET active = 0, updated_at = ? WHERE active = 1')
|
||||
.run(nowSeconds());
|
||||
for (const group of groups) {
|
||||
this.upsertGroup({
|
||||
@@ -327,7 +344,7 @@ export class IdentityService {
|
||||
for (const member of members) this.rememberUidUin(member.uid, member.uin);
|
||||
this.runWrite('group members', () => this.transaction(() => {
|
||||
this.upsertGroup({ groupId, memberCount: members.length });
|
||||
this.db!.prepare('UPDATE group_members SET active = 0, updated_at = ? WHERE group_id = ?')
|
||||
this.pstmt('UPDATE group_members SET active = 0, updated_at = ? WHERE group_id = ?')
|
||||
.run(nowSeconds(), groupId);
|
||||
for (const member of members) {
|
||||
this.upsertGroupMember({
|
||||
@@ -432,7 +449,7 @@ export class IdentityService {
|
||||
const updatedAt = nowSeconds();
|
||||
this.transaction(() => {
|
||||
for (const row of rows) {
|
||||
this.db!.prepare('UPDATE group_members SET active = 0, updated_at = ? WHERE id = ?')
|
||||
this.pstmt('UPDATE group_members SET active = 0, updated_at = ? WHERE id = ?')
|
||||
.run(updatedAt, row.id);
|
||||
}
|
||||
});
|
||||
@@ -541,7 +558,7 @@ export class IdentityService {
|
||||
}
|
||||
|
||||
private loadSnapshot(): void {
|
||||
const friendRows = this.db!.prepare(
|
||||
const friendRows = this.pstmt(
|
||||
`SELECT uid, uin, nickname, remark
|
||||
FROM users
|
||||
WHERE is_friend = 1 AND uin IS NOT NULL`,
|
||||
@@ -554,7 +571,7 @@ export class IdentityService {
|
||||
}));
|
||||
for (const friend of this.friends_) this.rememberUidUin(friend.uid, friend.uin);
|
||||
|
||||
const groups = this.db!.prepare(
|
||||
const groups = this.pstmt(
|
||||
`SELECT group_id, group_name, remark, member_count, member_max
|
||||
FROM groups
|
||||
WHERE active = 1`,
|
||||
@@ -579,7 +596,7 @@ export class IdentityService {
|
||||
private hydrateActiveMembersForGroups(groupIds: number[]): void {
|
||||
if (!this.db || groupIds.length === 0) return;
|
||||
|
||||
const select = this.db.prepare(
|
||||
const select = this.pstmt(
|
||||
`SELECT group_id, uid, uin, nickname, card, role, level, title,
|
||||
join_time, last_sent_time, shut_up_time
|
||||
FROM group_members
|
||||
@@ -626,9 +643,9 @@ export class IdentityService {
|
||||
|
||||
if (primary) {
|
||||
for (const duplicate of rows.slice(1)) {
|
||||
this.db.prepare('DELETE FROM users WHERE id = ?').run(duplicate.id);
|
||||
this.pstmt('DELETE FROM users WHERE id = ?').run(duplicate.id);
|
||||
}
|
||||
this.db.prepare(
|
||||
this.pstmt(
|
||||
`UPDATE users
|
||||
SET uid = ?, uin = ?, nickname = ?, remark = ?, is_friend = ?, source = ?, updated_at = ?
|
||||
WHERE id = ?`,
|
||||
@@ -645,7 +662,7 @@ export class IdentityService {
|
||||
return;
|
||||
}
|
||||
|
||||
this.db.prepare(
|
||||
this.pstmt(
|
||||
`INSERT INTO users (uid, uin, nickname, remark, is_friend, source, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)`,
|
||||
).run(
|
||||
@@ -662,7 +679,7 @@ export class IdentityService {
|
||||
private upsertGroup(input: GroupInput): void {
|
||||
if (!this.db || !Number.isInteger(input.groupId) || input.groupId <= 0) return;
|
||||
|
||||
const existing = this.db.prepare(
|
||||
const existing = this.pstmt(
|
||||
'SELECT group_name, remark, member_count, member_max FROM groups WHERE group_id = ?',
|
||||
).get(input.groupId) as {
|
||||
group_name: string;
|
||||
@@ -671,7 +688,7 @@ export class IdentityService {
|
||||
member_max: number;
|
||||
} | undefined;
|
||||
|
||||
this.db.prepare(
|
||||
this.pstmt(
|
||||
`INSERT INTO groups (group_id, group_name, remark, member_count, member_max, active, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, 1, ?)
|
||||
ON CONFLICT(group_id) DO UPDATE SET
|
||||
@@ -725,9 +742,9 @@ export class IdentityService {
|
||||
|
||||
if (primary) {
|
||||
for (const duplicate of rows.slice(1)) {
|
||||
this.db.prepare('DELETE FROM group_members WHERE id = ?').run(duplicate.id);
|
||||
this.pstmt('DELETE FROM group_members WHERE id = ?').run(duplicate.id);
|
||||
}
|
||||
this.db.prepare(
|
||||
this.pstmt(
|
||||
`UPDATE group_members
|
||||
SET uid = ?, uin = ?, nickname = ?, card = ?, role = ?, level = ?, title = ?,
|
||||
join_time = ?, last_sent_time = ?, shut_up_time = ?, active = ?, updated_at = ?
|
||||
@@ -750,7 +767,7 @@ export class IdentityService {
|
||||
return;
|
||||
}
|
||||
|
||||
this.db.prepare(
|
||||
this.pstmt(
|
||||
`INSERT INTO group_members
|
||||
(group_id, uid, uin, nickname, card, role, level, title,
|
||||
join_time, last_sent_time, shut_up_time, active, updated_at)
|
||||
@@ -775,17 +792,17 @@ export class IdentityService {
|
||||
private findUserRows(uid: string, uin: number | null): UserRow[] {
|
||||
if (!this.db) return [];
|
||||
if (uid && uin !== null) {
|
||||
return this.db.prepare(
|
||||
return this.pstmt(
|
||||
'SELECT id, uid, uin, nickname, remark, is_friend, source FROM users WHERE uid = ? OR uin = ? ORDER BY id',
|
||||
).all(uid, uin) as unknown as UserRow[];
|
||||
}
|
||||
if (uid) {
|
||||
return this.db.prepare(
|
||||
return this.pstmt(
|
||||
'SELECT id, uid, uin, nickname, remark, is_friend, source FROM users WHERE uid = ? ORDER BY id',
|
||||
).all(uid) as unknown as UserRow[];
|
||||
}
|
||||
if (uin !== null) {
|
||||
return this.db.prepare(
|
||||
return this.pstmt(
|
||||
'SELECT id, uid, uin, nickname, remark, is_friend, source FROM users WHERE uin = ? ORDER BY id',
|
||||
).all(uin) as unknown as UserRow[];
|
||||
}
|
||||
@@ -795,7 +812,7 @@ export class IdentityService {
|
||||
private findMemberRows(groupId: number, uid: string, uin: number | null): MemberRow[] {
|
||||
if (!this.db) return [];
|
||||
if (uid && uin !== null) {
|
||||
return this.db.prepare(
|
||||
return this.pstmt(
|
||||
`SELECT id, group_id, uid, uin, nickname, card, role, level, title,
|
||||
join_time, last_sent_time, shut_up_time, active
|
||||
FROM group_members
|
||||
@@ -804,7 +821,7 @@ export class IdentityService {
|
||||
).all(groupId, uid, uin) as unknown as MemberRow[];
|
||||
}
|
||||
if (uid) {
|
||||
return this.db.prepare(
|
||||
return this.pstmt(
|
||||
`SELECT id, group_id, uid, uin, nickname, card, role, level, title,
|
||||
join_time, last_sent_time, shut_up_time, active
|
||||
FROM group_members
|
||||
@@ -813,7 +830,7 @@ export class IdentityService {
|
||||
).all(groupId, uid) as unknown as MemberRow[];
|
||||
}
|
||||
if (uin !== null) {
|
||||
return this.db.prepare(
|
||||
return this.pstmt(
|
||||
`SELECT id, group_id, uid, uin, nickname, card, role, level, title,
|
||||
join_time, last_sent_time, shut_up_time, active
|
||||
FROM group_members
|
||||
|
||||
@@ -21,10 +21,14 @@ const rootPkg = JSON.parse(
|
||||
const toPosix = (p: string) => p.replace(/\\/g, '/');
|
||||
|
||||
// `@snowluma/websocket` is bundled (it's an in-tree TS workspace package), so
|
||||
// it must NOT be marked external. Only Node builtins stay external.
|
||||
const external: string[] = [];
|
||||
// it must NOT be marked external. `better-sqlite3` IS native — must be
|
||||
// external so its `require('./build/Release/better_sqlite3.node')`
|
||||
// stays a runtime import. Vendoring the prebuilt binding into
|
||||
// `packages/runtime/native/` is handled by the per-target packaging
|
||||
// step (see `nativeFiles` below).
|
||||
const external: string[] = ['better-sqlite3'];
|
||||
|
||||
const nodeModules = [...builtinModules, ...builtinModules.map((m) => `node:${m}`), 'node:sqlite'].flat();
|
||||
const nodeModules = [...builtinModules, ...builtinModules.map((m) => `node:${m}`)].flat();
|
||||
|
||||
const runtimeSrc = toPosix(runtimeDir);
|
||||
const nativeSrc = toPosix(nativeDir);
|
||||
|
||||
@@ -91,10 +91,12 @@
|
||||
"@snowluma/core": "workspace:*",
|
||||
"@snowluma/proto-defs": "workspace:*",
|
||||
"@snowluma/proton": "workspace:*",
|
||||
"@snowluma/websocket": "workspace:*"
|
||||
"@snowluma/websocket": "workspace:*",
|
||||
"better-sqlite3": "^11.7.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@hono/node-server": "^1.19.14",
|
||||
"@types/better-sqlite3": "^7.6.13",
|
||||
"@types/node": "^24.12.2",
|
||||
"hono": "^4.12.14",
|
||||
"typescript": "catalog:",
|
||||
|
||||
@@ -1,10 +1,31 @@
|
||||
import fs from 'fs';
|
||||
import { DatabaseSync } from 'node:sqlite';
|
||||
import Database from 'better-sqlite3';
|
||||
import path from 'path';
|
||||
import type { JsonObject, MessageMeta } from './types';
|
||||
|
||||
// Prepared statements are cached as `readonly` fields so the SQL parser
|
||||
// runs once at construction time. Previously each `db.prepare(sql)`
|
||||
// inside a hot-path method re-parsed on every call — the textbook
|
||||
// SQLite anti-pattern. RoadMap #5 bench numbers showed
|
||||
// storeMeta ≈ 17μs/op and storeEvent ≈ 23μs/op before caching;
|
||||
// caching + better-sqlite3 drops both to single-digit-μs (see the
|
||||
// commit-message numbers).
|
||||
//
|
||||
// Also: `node:sqlite` is still an experimental Node API (the
|
||||
// "ExperimentalWarning: SQLite is an experimental feature" line shows
|
||||
// up on every test run) — better-sqlite3 is the stable, sync, widely-
|
||||
// deployed wrapper that proposes the same prepared-statement model.
|
||||
|
||||
export class MessageStore {
|
||||
private readonly db: DatabaseSync;
|
||||
private readonly db: Database.Database;
|
||||
private readonly stmtStoreEvent: Database.Statement;
|
||||
private readonly stmtStoreMeta: Database.Statement;
|
||||
private readonly stmtFindEvent: Database.Statement;
|
||||
private readonly stmtFindMeta: Database.Statement;
|
||||
private readonly stmtResolveReplyGroup: Database.Statement;
|
||||
private readonly stmtResolveReplyPrivate: Database.Statement;
|
||||
private readonly stmtListEventsAnchored: Database.Statement;
|
||||
private readonly stmtListEventsLatest: Database.Statement;
|
||||
|
||||
constructor(dbPath: string) {
|
||||
const dir = path.dirname(dbPath);
|
||||
@@ -12,10 +33,77 @@ export class MessageStore {
|
||||
|
||||
// Replace .json extension with .db if present
|
||||
const finalPath = dbPath.replace(/\.json$/, '.db');
|
||||
this.db = new DatabaseSync(finalPath);
|
||||
this.db.exec('PRAGMA journal_mode = WAL');
|
||||
this.db.exec('PRAGMA synchronous = NORMAL');
|
||||
this.db = new Database(finalPath);
|
||||
this.db.pragma('journal_mode = WAL');
|
||||
this.db.pragma('synchronous = NORMAL');
|
||||
this.initSchema();
|
||||
|
||||
// Prepare once. Statements survive for the lifetime of the
|
||||
// Database instance — `close()` finalizes them automatically.
|
||||
this.stmtStoreEvent = this.db.prepare(
|
||||
`INSERT INTO messages
|
||||
(message_hash, is_group, session_id, sequence, event_name, client_sequence, random, timestamp, data)
|
||||
VALUES (?, ?, ?, ?, ?, 0, 0, ?, ?)
|
||||
ON CONFLICT(message_hash) DO UPDATE SET
|
||||
is_group = excluded.is_group,
|
||||
session_id = excluded.session_id,
|
||||
sequence = excluded.sequence,
|
||||
event_name = excluded.event_name,
|
||||
timestamp = excluded.timestamp,
|
||||
data = excluded.data`,
|
||||
);
|
||||
|
||||
this.stmtStoreMeta = this.db.prepare(
|
||||
`INSERT INTO messages
|
||||
(message_hash, is_group, session_id, sequence, event_name, client_sequence, random, timestamp)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(message_hash) DO UPDATE SET
|
||||
is_group = excluded.is_group,
|
||||
session_id = excluded.session_id,
|
||||
sequence = excluded.sequence,
|
||||
event_name = excluded.event_name,
|
||||
client_sequence = excluded.client_sequence,
|
||||
random = excluded.random,
|
||||
timestamp = excluded.timestamp`,
|
||||
);
|
||||
|
||||
this.stmtFindEvent = this.db.prepare(
|
||||
'SELECT data FROM messages WHERE message_hash = ? AND data IS NOT NULL',
|
||||
);
|
||||
|
||||
this.stmtFindMeta = this.db.prepare(
|
||||
'SELECT is_group, session_id, sequence, event_name, client_sequence, random, timestamp FROM messages WHERE message_hash = ?',
|
||||
);
|
||||
|
||||
this.stmtResolveReplyGroup = this.db.prepare(
|
||||
`SELECT sequence
|
||||
FROM messages
|
||||
WHERE is_group = 1 AND session_id = ? AND message_hash = ?
|
||||
LIMIT 1`,
|
||||
);
|
||||
|
||||
this.stmtResolveReplyPrivate = this.db.prepare(
|
||||
`SELECT sequence
|
||||
FROM messages
|
||||
WHERE is_group = 0 AND message_hash = ?
|
||||
LIMIT 1`,
|
||||
);
|
||||
|
||||
this.stmtListEventsAnchored = this.db.prepare(
|
||||
`SELECT data
|
||||
FROM messages
|
||||
WHERE is_group = ? AND session_id = ? AND data IS NOT NULL AND sequence <= ?
|
||||
ORDER BY sequence DESC
|
||||
LIMIT ?`,
|
||||
);
|
||||
|
||||
this.stmtListEventsLatest = this.db.prepare(
|
||||
`SELECT data
|
||||
FROM messages
|
||||
WHERE is_group = ? AND session_id = ? AND data IS NOT NULL
|
||||
ORDER BY sequence DESC
|
||||
LIMIT ?`,
|
||||
);
|
||||
}
|
||||
|
||||
close(): void {
|
||||
@@ -34,35 +122,12 @@ export class MessageStore {
|
||||
const json = JSON.stringify(event);
|
||||
const timestamp = toInt(event.time);
|
||||
|
||||
this.db.prepare(
|
||||
`INSERT INTO messages
|
||||
(message_hash, is_group, session_id, sequence, event_name, client_sequence, random, timestamp, data)
|
||||
VALUES (?, ?, ?, ?, ?, 0, 0, ?, ?)
|
||||
ON CONFLICT(message_hash) DO UPDATE SET
|
||||
is_group = excluded.is_group,
|
||||
session_id = excluded.session_id,
|
||||
sequence = excluded.sequence,
|
||||
event_name = excluded.event_name,
|
||||
timestamp = excluded.timestamp,
|
||||
data = excluded.data`
|
||||
).run(messageId, isGroup ? 1 : 0, sessionId, sequence, eventName, timestamp, json);
|
||||
this.stmtStoreEvent.run(messageId, isGroup ? 1 : 0, sessionId, sequence, eventName, timestamp, json);
|
||||
}
|
||||
|
||||
storeMeta(messageId: number, meta: MessageMeta): void {
|
||||
if (!isValidMessageId(messageId)) return;
|
||||
this.db.prepare(
|
||||
`INSERT INTO messages
|
||||
(message_hash, is_group, session_id, sequence, event_name, client_sequence, random, timestamp)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(message_hash) DO UPDATE SET
|
||||
is_group = excluded.is_group,
|
||||
session_id = excluded.session_id,
|
||||
sequence = excluded.sequence,
|
||||
event_name = excluded.event_name,
|
||||
client_sequence = excluded.client_sequence,
|
||||
random = excluded.random,
|
||||
timestamp = excluded.timestamp`
|
||||
).run(
|
||||
this.stmtStoreMeta.run(
|
||||
messageId,
|
||||
meta.isGroup ? 1 : 0,
|
||||
meta.targetId,
|
||||
@@ -76,9 +141,7 @@ export class MessageStore {
|
||||
|
||||
findEvent(messageId: number): JsonObject | null {
|
||||
if (!isValidMessageId(messageId)) return null;
|
||||
const row = this.db.prepare(
|
||||
'SELECT data FROM messages WHERE message_hash = ? AND data IS NOT NULL',
|
||||
).get(messageId) as { data: string } | undefined;
|
||||
const row = this.stmtFindEvent.get(messageId) as { data: string } | undefined;
|
||||
|
||||
if (!row?.data) return null;
|
||||
try {
|
||||
@@ -91,9 +154,7 @@ export class MessageStore {
|
||||
findMeta(messageId: number): MessageMeta | null {
|
||||
if (!isValidMessageId(messageId)) return null;
|
||||
|
||||
const row = this.db.prepare(
|
||||
'SELECT is_group, session_id, sequence, event_name, client_sequence, random, timestamp FROM messages WHERE message_hash = ?',
|
||||
).get(messageId) as {
|
||||
const row = this.stmtFindMeta.get(messageId) as {
|
||||
is_group: number;
|
||||
session_id: number;
|
||||
sequence: number;
|
||||
@@ -126,18 +187,8 @@ export class MessageStore {
|
||||
// - When sending reply: sessionId parameter is the recipient's UIN (who we're sending to)
|
||||
// So for private messages, we only match by message_hash and is_group flag.
|
||||
const row = isGroup
|
||||
? this.db.prepare(
|
||||
`SELECT sequence
|
||||
FROM messages
|
||||
WHERE is_group = 1 AND session_id = ? AND message_hash = ?
|
||||
LIMIT 1`
|
||||
).get(sessionId, messageId) as { sequence: number } | undefined
|
||||
: this.db.prepare(
|
||||
`SELECT sequence
|
||||
FROM messages
|
||||
WHERE is_group = 0 AND message_hash = ?
|
||||
LIMIT 1`
|
||||
).get(messageId) as { sequence: number } | undefined;
|
||||
? this.stmtResolveReplyGroup.get(sessionId, messageId) as { sequence: number } | undefined
|
||||
: this.stmtResolveReplyPrivate.get(messageId) as { sequence: number } | undefined;
|
||||
|
||||
if (!row || !Number.isInteger(row.sequence) || row.sequence <= 0) {
|
||||
return null;
|
||||
@@ -158,20 +209,8 @@ export class MessageStore {
|
||||
const anchor = hasAnchor ? (anchorSequence as number) : 0;
|
||||
|
||||
const rows = hasAnchor
|
||||
? this.db.prepare(
|
||||
`SELECT data
|
||||
FROM messages
|
||||
WHERE is_group = ? AND session_id = ? AND data IS NOT NULL AND sequence <= ?
|
||||
ORDER BY sequence DESC
|
||||
LIMIT ?`
|
||||
).all(isGroup ? 1 : 0, sessionId, anchor, limit)
|
||||
: this.db.prepare(
|
||||
`SELECT data
|
||||
FROM messages
|
||||
WHERE is_group = ? AND session_id = ? AND data IS NOT NULL
|
||||
ORDER BY sequence DESC
|
||||
LIMIT ?`
|
||||
).all(isGroup ? 1 : 0, sessionId, limit);
|
||||
? this.stmtListEventsAnchored.all(isGroup ? 1 : 0, sessionId, anchor, limit)
|
||||
: this.stmtListEventsLatest.all(isGroup ? 1 : 0, sessionId, limit);
|
||||
|
||||
const result: JsonObject[] = [];
|
||||
for (const row of rows as Array<{ data: string }>) {
|
||||
|
||||
Reference in new issue
Block a user