127 lines
4.7 KiB
TypeScript
127 lines
4.7 KiB
TypeScript
// drizzle on Node's built-in node:sqlite (PEP-36). drizzle-orm 0.45 has no node:sqlite
|
|
// driver (only 1.0 beta/rc does), but node:sqlite's API is close to better-sqlite3's, so a
|
|
// thin client lets drizzle's better-sqlite3 *session* run on it. drizzle-orm/better-sqlite3
|
|
// itself is not imported: its driver.js loads the native better-sqlite3 package.
|
|
// Every Peppa process (web, bot, watchdog, each hook and MCP server) opens the file itself;
|
|
// WAL lets readers run next to the single writer, busy_timeout makes writers queue.
|
|
import { DatabaseSync, type StatementSync } from "node:sqlite";
|
|
import { mkdirSync } from "node:fs";
|
|
import { dirname } from "node:path";
|
|
import { probed } from "./probe.ts";
|
|
|
|
export const BUSY_TIMEOUT_MS = 5000;
|
|
const BUSY_RETRIES = 3;
|
|
|
|
const isBusy = (e: unknown) => /SQLITE_BUSY|database is locked/i.test(String((e as Error)?.message ?? e));
|
|
|
|
/** SQLITE_BUSY after busy_timeout already waited: try a few more times before giving up. */
|
|
function retryBusy<T>(fn: () => T): T {
|
|
for (let attempt = 1; ; attempt++) {
|
|
try {
|
|
return fn();
|
|
} catch (e) {
|
|
if (!isBusy(e) || attempt >= BUSY_RETRIES) throw e;
|
|
}
|
|
}
|
|
}
|
|
|
|
type Params = unknown[];
|
|
|
|
class Statement {
|
|
private stmt: StatementSync;
|
|
private rawStmt: StatementSync | null = null;
|
|
private db: DatabaseSync;
|
|
private sql: string;
|
|
constructor(db: DatabaseSync, sql: string) {
|
|
this.db = db;
|
|
this.sql = sql;
|
|
this.stmt = db.prepare(sql);
|
|
}
|
|
run(...p: Params) {
|
|
return probed(this.sql, () => retryBusy(() => this.stmt.run(...(p as never[]))));
|
|
}
|
|
all(...p: Params) {
|
|
return probed(this.sql, () => retryBusy(() => this.stmt.all(...(p as never[]))));
|
|
}
|
|
get(...p: Params) {
|
|
return probed(this.sql, () => retryBusy(() => this.stmt.get(...(p as never[]))));
|
|
}
|
|
/** The same statement returning rows as arrays (drizzle maps columns by position). */
|
|
raw() {
|
|
if (!this.rawStmt) {
|
|
this.rawStmt = this.db.prepare(this.sql);
|
|
this.rawStmt.setReturnArrays(true);
|
|
}
|
|
const s = this.rawStmt;
|
|
const sql = this.sql;
|
|
return {
|
|
all: (...p: Params) => probed(sql, () => retryBusy(() => s.all(...(p as never[])))),
|
|
get: (...p: Params) => probed(sql, () => retryBusy(() => s.get(...(p as never[])))),
|
|
};
|
|
}
|
|
}
|
|
|
|
export class SqliteClient {
|
|
readonly path: string;
|
|
private readOnly: boolean;
|
|
private conn: DatabaseSync | null = null;
|
|
private cache = new Map<string, Statement>();
|
|
constructor(path: string, opts: { readOnly?: boolean } = {}) {
|
|
this.path = path;
|
|
this.readOnly = opts.readOnly ?? false;
|
|
}
|
|
/**
|
|
* The connection, opened on first use: importing a module that creates the client (the
|
|
* web's lib/db.ts during `next build`) must not create the database file.
|
|
*/
|
|
get db(): DatabaseSync {
|
|
if (this.conn) return this.conn;
|
|
if (this.path !== ":memory:" && !this.readOnly) mkdirSync(dirname(this.path), { recursive: true });
|
|
const db = new DatabaseSync(this.path, { readOnly: this.readOnly });
|
|
// busy_timeout first: any statement before it can fail at once with SQLITE_BUSY_RECOVERY
|
|
// when many processes open the file together (bench/sqlite/README.md).
|
|
db.exec(`PRAGMA busy_timeout = ${BUSY_TIMEOUT_MS}`);
|
|
if (!this.readOnly) retryBusy(() => db.exec("PRAGMA journal_mode = WAL"));
|
|
db.exec("PRAGMA synchronous = NORMAL");
|
|
db.exec("PRAGMA foreign_keys = ON");
|
|
return (this.conn = db);
|
|
}
|
|
prepare(sql: string) {
|
|
let s = this.cache.get(sql);
|
|
if (!s) this.cache.set(sql, (s = new Statement(this.db, sql)));
|
|
return s;
|
|
}
|
|
exec(sql: string) {
|
|
retryBusy(() => this.db.exec(sql));
|
|
}
|
|
/** better-sqlite3's transaction API; the callback must be synchronous. */
|
|
transaction<T>(fn: (...a: never[]) => T) {
|
|
const run =
|
|
(begin: string) =>
|
|
(...a: never[]): T => {
|
|
retryBusy(() => this.db.exec(begin));
|
|
try {
|
|
const r = fn(...a);
|
|
if (r && typeof (r as { then?: unknown }).then === "function") {
|
|
throw new Error("SQLite transactions must be synchronous: no async callback, no await inside db.transaction()");
|
|
}
|
|
this.db.exec("COMMIT");
|
|
return r;
|
|
} catch (e) {
|
|
if (this.db.isTransaction) this.db.exec("ROLLBACK");
|
|
throw e;
|
|
}
|
|
};
|
|
return { deferred: run("BEGIN"), immediate: run("BEGIN IMMEDIATE"), exclusive: run("BEGIN EXCLUSIVE") };
|
|
}
|
|
/** Changes committed by other connections since the last call (PRAGMA data_version). */
|
|
dataVersion(): number {
|
|
return Number((this.db.prepare("PRAGMA data_version").get() as { data_version: number }).data_version);
|
|
}
|
|
close() {
|
|
if (this.conn?.isOpen) this.conn.close();
|
|
this.conn = null;
|
|
this.cache.clear();
|
|
}
|
|
}
|