// Uniform async DB access for the benchmark: bun:sqlite, node:sqlite, better-sqlite3, // Postgres (postgres.js) and a "writer" client that sends writes to one writer process. // SQL is written in SQLite dialect with `?` params; the Postgres adapter renumbers them. import { request } from "node:http"; export type Stmt = [sql: string, params?: unknown[]]; export type Row = Record; export interface Db { all(sql: string, params?: unknown[]): Promise; /** Runs statements in one write transaction; returns each statement's rows. */ tx(stmts: Stmt[]): Promise; /** SQLITE_BUSY retries made by the last tx (0 for Postgres/writer). */ lastBusy: number; close(): Promise; /** Postgres only: raw client for LISTEN/NOTIFY. */ pg?: any; } export type Backend = "bun" | "node" | "better" | "pg" | "writer"; export const BUSY_TIMEOUT_MS = Number(process.env.BENCH_BUSY_TIMEOUT_MS ?? 5000); // busy_timeout must come first: with 20 hook processes opening the file at once, any // statement before it (even journal_mode) can fail at once with SQLITE_BUSY_RECOVERY. // journal_mode=WAL is persistent, so it is set once when the file is created (run.ts). const PRAGMAS = [ `PRAGMA busy_timeout = ${BUSY_TIMEOUT_MS}`, "PRAGMA synchronous = NORMAL", "PRAGMA foreign_keys = ON", ]; function isBusy(e: unknown) { const s = String((e as any)?.code ?? "") + " " + String((e as any)?.message ?? e); return /SQLITE_BUSY|database is locked/i.test(s); } /** Wraps a synchronous SQLite driver: BEGIN IMMEDIATE + retry on SQLITE_BUSY. */ function syncSqlite(exec: (sql: string) => void, all: (sql: string, p: unknown[]) => Row[], close: () => void): Db { const db: Db = { lastBusy: 0, async all(sql, params = []) { return all(sql, params); }, async tx(stmts) { db.lastBusy = 0; for (;;) { try { exec("BEGIN IMMEDIATE"); try { const out = stmts.map(([s, p]) => all(s, p ?? [])); exec("COMMIT"); return out; } catch (e) { try { exec("ROLLBACK"); } catch {} throw e; } } catch (e) { // busy_timeout already waited BUSY_TIMEOUT_MS; count it and give up after 3. if (!isBusy(e) || ++db.lastBusy >= 3) throw e; } } }, async close() { close(); }, }; return db; } export async function openSqlite(kind: "bun" | "node" | "better", path: string, readonly = false): Promise { if (kind === "bun") { const { Database } = await import("bun:sqlite" as string); const d = new Database(path, readonly ? { readonly: true } : { create: true }); for (const p of PRAGMAS) d.exec(p); return syncSqlite((s) => d.exec(s), (s, p) => d.query(s).all(...p), () => d.close()); } if (kind === "node") { const { DatabaseSync } = await import("node:sqlite"); const d = new DatabaseSync(path, { readOnly: readonly }); for (const p of PRAGMAS) d.exec(p); const cache = new Map(); const prep = (s: string) => cache.get(s) ?? (cache.set(s, d.prepare(s)), cache.get(s)); return syncSqlite((s) => d.exec(s), (s, p) => prep(s).all(...(p as any[])) as Row[], () => d.close()); } const { default: Better } = await import("better-sqlite3"); const d = new Better(path, { readonly }); for (const p of PRAGMAS) d.exec(p); const cache = new Map(); const prep = (s: string) => cache.get(s) ?? (cache.set(s, d.prepare(s)), cache.get(s)); return syncSqlite( (s) => d.exec(s), (s, p) => { const st = prep(s); return st.reader ? st.all(...p) : (st.run(...p), []); }, () => d.close(), ); } const toPg = (s: string) => { let i = 0; return s.replace(/\?/g, () => `$${++i}`); }; export async function openPg(url: string, max = 1): Promise { const { default: postgres } = await import("postgres"); const sql = postgres(url, { max, onnotice: () => {} }); return { lastBusy: 0, pg: sql, async all(s, p = []) { return (await sql.unsafe(toPg(s), p as any[])) as unknown as Row[]; }, async tx(stmts) { return (await sql.begin(async (t: any) => { const out: Row[][] = []; for (const [s, p] of stmts) out.push(await t.unsafe(toPg(s), p ?? [])); return out; })) as Row[][]; }, async close() { await sql.end({ timeout: 1 }); }, }; } export async function httpUnix(socketPath: string, path: string, body: unknown): Promise { // Bun's fetch speaks unix sockets natively and starts much faster than node:http there. if (typeof (globalThis as any).Bun !== "undefined") { const r = await fetch(`http://writer${path}`, { method: "POST", body: JSON.stringify(body), unix: socketPath } as RequestInit); const j = await r.json(); if (!r.ok) throw new Error(j?.error ?? `HTTP ${r.status}`); return j; } return new Promise((resolve, reject) => { const data = JSON.stringify(body); const req = request( { socketPath, path, method: "POST", headers: { "content-type": "application/json", "content-length": Buffer.byteLength(data) } }, (res) => { let buf = ""; res.setEncoding("utf8"); res.on("data", (c) => (buf += c)); res.on("end", () => { const j = buf ? JSON.parse(buf) : null; res.statusCode === 200 ? resolve(j) : reject(new Error(j?.error ?? `HTTP ${res.statusCode}`)); }); }, ); req.on("error", reject); req.end(data); }); } /** Writes go to the writer process over a unix socket; reads go straight to the file (WAL readers never block). */ export async function openWriterClient(socketPath: string, dbPath: string, readKind: "bun" | "node"): Promise { const reader = await openSqlite(readKind, dbPath, true); return { lastBusy: 0, all: (s, p) => reader.all(s, p), async tx(stmts) { return (await httpUnix(socketPath, "/tx", { stmts })).rows; }, close: () => reader.close(), }; } export async function openDb(backend: Backend, env = process.env): Promise { if (backend === "pg") return openPg(env.BENCH_PG_URL!); if (backend === "writer") return openWriterClient(env.BENCH_WRITER_SOCK!, env.BENCH_DB!, (env.BENCH_READ_KIND as any) ?? "bun"); return openSqlite(backend, env.BENCH_DB!); }