Cache prepared statements per database connection

This commit is contained in:
2026-10-05 15:24:17 -04:00
parent 239eceb779
commit 2af768011a
4 changed files with 70 additions and 2 deletions
+15
View File
@@ -391,6 +391,21 @@ export function db(): Database.Database {
throw err;
}
// Cache only runtime queries, after migrations have finished. Statements
// belong to this connection, so reopening the DB starts with an empty cache.
// Callers share statement options (e.g. raw()); use consistent options for
// identical SQL and pass values to run/get/all rather than binding permanently.
const statements = new Map<string, Database.Statement>();
const prepare = handle.prepare.bind(handle);
handle.prepare = ((sql: string) => {
let statement = statements.get(sql);
if (!statement) {
statement = prepare(sql);
statements.set(sql, statement);
}
return statement;
}) as typeof handle.prepare;
_db = handle;
return _db;
}