Switch from @snowluma/sqlite to node:sqlite (sync)

Remove the in-tree @snowluma/sqlite wrapper and vendored better-sqlite3 prebuilts; migrate consumers to node:sqlite's synchronous API. Replaced imports and types (Database/Statement -> DatabaseSync/StatementSync), updated PRAGMA calls to use exec, and adjusted code in onebot (media/message/reaction stores) and protocol (identity service). Vite config no longer bundles sqlite native binaries and references to the sqlite workspace were removed. Also delete the packages/sqlite package and its native prebuild artifacts, and add a couple of unrelated AST improvements in proton: use a module-level shared wrapper cache and add an inheritance cache to avoid repeated scans. Minor import reordering/cleanup applied where needed.
This commit is contained in:
手瓜一十雪 committed 2026-05-27 20:02:40 +08:00
1 parent 5924346823
commit f2b7ef0056
23 files changed
+58 -603

No files matched your search

-1
View File
@@ -46,7 +46,6 @@
"@snowluma/protocol": "workspace:*",
"@snowluma/proto-defs": "workspace:*",
"@snowluma/proton": "workspace:*",
"@snowluma/sqlite": "workspace:*",
"@snowluma/websocket": "workspace:*"
},
"devDependencies": {
+9 -23
View File
@@ -1,10 +1,10 @@
import { defineConfig, PluginOption, UserConfig } from 'vite';
import { fileURLToPath } from 'url';
import fs from 'fs';
import path from 'path';
import { builtinModules } from 'module';
import cp from 'vite-plugin-cp';
import protobufVitePlugin from '@snowluma/proton/vite';
import fs from 'fs';
import { builtinModules } from 'module';
import path from 'path';
import { fileURLToPath } from 'url';
import { defineConfig, PluginOption, UserConfig } from 'vite';
import cp from 'vite-plugin-cp';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const repoRoot = path.resolve(__dirname, '..', '..');
@@ -20,11 +20,9 @@ const rootPkg = JSON.parse(
// vite-plugin-cp consumes globs through globby; on Windows we must use POSIX-style separators.
const toPosix = (p: string) => p.replace(/\\/g, '/');
// `@snowluma/websocket` and `@snowluma/sqlite` are bundled — they're
// in-tree TS workspace wrappers that route their native `.node`
// addons through `dist/native/`. Only Node builtins stay external;
// the actual `better-sqlite3` JS wrapper is pulled in via the
// `@snowluma/sqlite` re-export and bundled into `index.mjs`.
// `@snowluma/websocket` is bundled — it's an
// in-tree TS workspace wrapper that routes its native `.node`
// addon through `dist/native/`. Only Node builtins stay external.
const external: string[] = [];
const nodeModules = [...builtinModules, ...builtinModules.map((m) => `node:${m}`)].flat();
@@ -46,20 +44,8 @@ const runtimeDistFiles = ['package.json',
// Native binaries shipped for the selected target:
// * `snowluma-*.{dll,node,so}` – NTQQ hook (Windows + Linux).
// * `websocket-*.node` – RFC 6455 framing/mask addon (all platforms).
// * `better-sqlite3-v<abi>-*.node` – SQLite native binding consumed
// by @snowluma/sqlite. Two ABIs
// vendored side-by-side
// (v127 = Node 22 LTS, v137 =
// Node 24) so the runtime can
// pick whichever matches the
// host's `process.versions.modules`.
// Vendored via
// `tools/fetch-sqlite-prebuilts.mjs`
// from WiseLibs's prebuild releases.
const SQLITE_ABIS = ['v127', 'v137'];
const nativeFiles = [
`websocket-${targetTriple}.node`,
...SQLITE_ABIS.map((abi) => `better-sqlite3-${abi}-${targetTriple}.node`),
...(targetPlatform === 'win32'
? [`snowluma-${targetTriple}.dll`, `snowluma-${targetTriple}.node`]
: []),
-1
View File
@@ -91,7 +91,6 @@
"@snowluma/proto-defs": "workspace:*",
"@snowluma/proton": "workspace:*",
"@snowluma/protocol": "workspace:*",
"@snowluma/sqlite": "workspace:*",
"@snowluma/websocket": "workspace:*"
},
"devDependencies": {
+12 -12
View File
@@ -1,6 +1,6 @@
import type { MessageElement } from '@snowluma/protocol/events';
import Database, { type Database as DatabaseType, type Statement } from '@snowluma/sqlite';
import fs from 'fs';
import { DatabaseSync, type StatementSync } from 'node:sqlite';
import path from 'path';
export interface CachedImage {
@@ -62,17 +62,17 @@ const TYPE_VIDEO = 'video';
const DEFAULT_KEEP_ENTRIES = 4096;
export class MediaStore {
private readonly db: DatabaseType;
private readonly db: DatabaseSync;
private readonly maxEntriesPerType: number;
// Prepared statements (pay the parsing cost once at startup).
private readonly upsertEntry: Statement;
private readonly upsertKey: Statement;
private readonly findEntryByKey: Statement;
private readonly findEntryByPrimary: Statement;
private readonly evictByType: Statement;
private readonly purgeOrphanKeys: Statement;
private readonly countByType: Statement;
private readonly upsertEntry: StatementSync;
private readonly upsertKey: StatementSync;
private readonly findEntryByKey: StatementSync;
private readonly findEntryByPrimary: StatementSync;
private readonly evictByType: StatementSync;
private readonly purgeOrphanKeys: StatementSync;
private readonly countByType: StatementSync;
constructor(dbPath: string, maxEntriesPerType = DEFAULT_KEEP_ENTRIES) {
this.maxEntriesPerType = Math.max(64, maxEntriesPerType);
@@ -80,9 +80,9 @@ export class MediaStore {
const dir = path.dirname(dbPath);
fs.mkdirSync(dir, { recursive: true });
this.db = new Database(dbPath);
this.db.pragma('journal_mode = WAL');
this.db.pragma('synchronous = NORMAL');
this.db = new DatabaseSync(dbPath);
this.db.exec('PRAGMA journal_mode = WAL');
this.db.exec('PRAGMA synchronous = NORMAL');
this.initSchema();
this.upsertEntry = this.db.prepare(
+13 -13
View File
@@ -1,18 +1,18 @@
import Database, { type Database as DatabaseType, type Statement } from '@snowluma/sqlite';
import fs from 'fs';
import { DatabaseSync, type StatementSync } from 'node:sqlite';
import path from 'path';
import type { JsonObject, MessageMeta } from './types';
export class MessageStore {
private readonly db: DatabaseType;
private readonly stmtStoreEvent: Statement;
private readonly stmtStoreMeta: Statement;
private readonly stmtFindEvent: Statement;
private readonly stmtFindMeta: Statement;
private readonly stmtResolveReplyGroup: Statement;
private readonly stmtResolveReplyPrivate: Statement;
private readonly stmtListEventsAnchored: Statement;
private readonly stmtListEventsLatest: Statement;
private readonly db: DatabaseSync;
private readonly stmtStoreEvent: StatementSync;
private readonly stmtStoreMeta: StatementSync;
private readonly stmtFindEvent: StatementSync;
private readonly stmtFindMeta: StatementSync;
private readonly stmtResolveReplyGroup: StatementSync;
private readonly stmtResolveReplyPrivate: StatementSync;
private readonly stmtListEventsAnchored: StatementSync;
private readonly stmtListEventsLatest: StatementSync;
constructor(dbPath: string) {
const dir = path.dirname(dbPath);
@@ -20,9 +20,9 @@ export class MessageStore {
// Replace .json extension with .db if present
const finalPath = dbPath.replace(/\.json$/, '.db');
this.db = new Database(finalPath);
this.db.pragma('journal_mode = WAL');
this.db.pragma('synchronous = NORMAL');
this.db = new DatabaseSync(finalPath);
this.db.exec('PRAGMA journal_mode = WAL');
this.db.exec('PRAGMA synchronous = NORMAL');
this.initSchema();
// Prepare once. Statements survive for the lifetime of the
+10 -10
View File
@@ -1,21 +1,21 @@
import Database, { type Database as DatabaseType, type Statement } from '@snowluma/sqlite';
import fs from 'fs';
import { DatabaseSync, type StatementSync } from 'node:sqlite';
import path from 'path';
export class ReactionStore {
private readonly db: DatabaseType;
private readonly stmtUpsert: Statement;
private readonly stmtRemove: Statement;
private readonly stmtList: Statement;
private readonly stmtCount: Statement;
private readonly stmtCountByEmoji: Statement;
private readonly db: DatabaseSync;
private readonly stmtUpsert: StatementSync;
private readonly stmtRemove: StatementSync;
private readonly stmtList: StatementSync;
private readonly stmtCount: StatementSync;
private readonly stmtCountByEmoji: StatementSync;
constructor(dbPath: string) {
const dir = path.dirname(dbPath);
fs.mkdirSync(dir, { recursive: true });
this.db = new Database(dbPath);
this.db.pragma('journal_mode = WAL');
this.db.pragma('synchronous = NORMAL');
this.db = new DatabaseSync(dbPath);
this.db.exec('PRAGMA journal_mode = WAL');
this.db.exec('PRAGMA synchronous = NORMAL');
this.initSchema();
this.stmtUpsert = this.db.prepare(
+1 -2
View File
@@ -368,8 +368,7 @@
"dependencies": {
"@snowluma/common": "workspace:*",
"@snowluma/proto-defs": "workspace:*",
"@snowluma/proton": "workspace:*",
"@snowluma/sqlite": "workspace:*"
"@snowluma/proton": "workspace:*"
},
"devDependencies": {
"@types/node": "^24.12.2",
+13 -11
View File
@@ -1,12 +1,14 @@
import fs from 'fs';
import { DatabaseSync, type StatementSync } from 'node:sqlite';
import path from 'path';
import Database, { type Database as DatabaseType, type Statement } from '@snowluma/sqlite';
import type {
FriendInfo, GroupMemberInfo, QQGroupInfo,
UserProfileInfo, GroupRequestInfo,
} from './qq-info';
import { createLogger, type Logger } from '@snowluma/common/logger';
import type {
FriendInfo, GroupMemberInfo,
GroupRequestInfo,
QQGroupInfo,
UserProfileInfo,
} from './qq-info';
const moduleLogger = createLogger('Identity');
@@ -109,14 +111,14 @@ export class IdentityService {
private readonly uidByUin = new Map<number, string>();
// ─── Persistence + fetcher ───
private readonly db: DatabaseType | null;
private readonly db: DatabaseSync | 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, Statement>();
private readonly stmtCache_ = new Map<string, StatementSync>();
private inTransaction = false;
private fetcher: IdentityFetcher | null = null;
private readonly log: Logger;
@@ -134,16 +136,16 @@ export class IdentityService {
}
fs.mkdirSync(path.dirname(dbPath), { recursive: true });
this.db = new Database(dbPath);
this.db.pragma('journal_mode = WAL');
this.db.pragma('synchronous = NORMAL');
this.db = new DatabaseSync(dbPath);
this.db.exec('PRAGMA journal_mode = WAL');
this.db.exec('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): Statement {
private pstmt(sql: string): StatementSync {
let cached = this.stmtCache_.get(sql);
if (cached !== undefined) return cached;
cached = this.db!.prepare(sql);
-24
View File
@@ -1,24 +0,0 @@
{
"name": "@snowluma/sqlite",
"version": "1.9.2",
"private": true,
"type": "module",
"description": "SnowLuma SQLite wrapper. Exposes the `better-sqlite3` Database constructor + Statement type, but loads the native `.node` binding from `dist/native/sqlite/<platform>-<arch>/` at runtime instead of going through `bindings('better_sqlite3.node')` + `node_modules/.../build/Release/`. The vendored prebuilds under `packages/runtime/native/sqlite/` get copied into the dist tree by `vite-plugin-cp` during the @snowluma/core build, mirroring how `websocket-*.node` and `ffmpegAddon.*.node` are handled. The end result: production artifacts ship as a single self-contained dist/ directory with no `dist/node_modules/` and no install step at runtime.",
"main": "./src/index.ts",
"types": "./src/index.ts",
"exports": {
".": {
"types": "./src/index.ts",
"default": "./src/index.ts"
}
},
"scripts": {
"typecheck": "tsc --noEmit"
},
"devDependencies": {
"@types/better-sqlite3": "^7.6.13",
"@types/node": "^24.12.2",
"better-sqlite3": "12.10.0",
"typescript": "catalog:"
}
}
-84
View File
@@ -1,84 +0,0 @@
import BetterSqlite3 from 'better-sqlite3';
import { existsSync } from 'node:fs';
import { createRequire } from 'node:module';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
// Re-export the public types/classes consumers need. `Database` and
// `Statement` come straight from better-sqlite3 — we only intercept
// the constructor at call time, not the class shape.
export type { Database, Options, RunResult, Statement } from 'better-sqlite3';
function triplet(): string {
return `${process.platform}-${process.arch}`;
}
function abi(): string {
// `process.versions.modules` is the NODE_MODULE_VERSION the running
// Node binary expects — e.g. "127" for Node 22, "137" for Node 24.
// Stays in sync with whatever the host actually does at load time.
return `v${process.versions.modules}`;
}
function locateBinding(): string {
const tri = triplet();
const fileName = `better-sqlite3-${abi()}-${tri}.node`;
// Two candidate locations, tried in order:
// 1. Production: dist/native/better-sqlite3-<triplet>.node
// — `import.meta.url` resolves to dist/ at runtime (the wrapper
// is bundled into index.mjs alongside it).
// 2. Dev: <repo>/packages/runtime/native/better-sqlite3-<triplet>.node
// — `import.meta.url` resolves to packages/sqlite/src/index.ts;
// walk up to repo root + into runtime/native.
const here = dirname(fileURLToPath(import.meta.url));
const distCandidate = join(here, 'native', fileName);
if (existsSync(distCandidate)) return distCandidate;
// From packages/sqlite/src ⇢ go up to packages/, then into
// runtime/native. (Two `..` segments, not three — `src` → `sqlite/`
// → `packages/`, then descend into `runtime/native`.)
const devCandidate = resolve(here, '..', '..', 'runtime', 'native', fileName);
if (existsSync(devCandidate)) return devCandidate;
throw new Error(
`@snowluma/sqlite: could not locate ${fileName}. ` +
`Tried:\n ${distCandidate}\n ${devCandidate}\n` +
`Run \`node tools/fetch-sqlite-prebuilts.mjs\` to vendor the missing platform binary.`,
);
}
// Load the native addon once at module import — keeping it module-
// scoped so the require() cost is paid exactly once per process.
let addon: unknown | null = null;
function loadAddon(): unknown {
if (addon) return addon;
const bindingPath = locateBinding();
// better-sqlite3 expects the addon to be loaded via the CJS
// require() mechanism (N-API init runs through it). createRequire
// is the ESM-safe way to do that with an absolute path.
const req = createRequire(import.meta.url);
addon = req(bindingPath);
return addon;
}
// Drop-in `Database` factory. Matches the better-sqlite3 default-
// export signature exactly: `new Database(filename[, options])` →
// `Database` instance.
//
// We can't just `class extends BetterSqlite3` because better-sqlite3's
// default export is a function that returns the instance (the `new
// Database(...)` shape works through that function's `new.target`
// check). Wrapping at the function-call boundary keeps that contract
// intact.
type BetterSqlite3Type = typeof BetterSqlite3;
type DatabaseInstance = InstanceType<BetterSqlite3Type>;
type DatabaseOptions = ConstructorParameters<BetterSqlite3Type>[1];
type BetterSqlite3Constructor = new (filename?: string | Buffer, options?: DatabaseOptions) => DatabaseInstance;
const Database = function Database(filename?: string | Buffer, options?: DatabaseOptions): DatabaseInstance {
const opts = { ...(options ?? {}), nativeBinding: loadAddon() } as DatabaseOptions;
// better-sqlite3 的默认导出同时支持函数调用和 new 调用;这里只需要构造器形态。
return new (BetterSqlite3 as unknown as BetterSqlite3Constructor)(filename, opts);
} as unknown as BetterSqlite3Type;
export default Database;
-13
View File
@@ -1,13 +0,0 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"types": ["node"],
"noEmit": true
},
"include": [
"src/**/*"
],
"exclude": [
"node_modules"
]
}