import { DatabaseSync, type SQLInputValue, type StatementSync } from "node:sqlite"; type BoundValue = ArrayBuffer | ArrayBufferView | bigint | boolean | null | number | string; const databases = new Map(); function sqliteValue(value: BoundValue): SQLInputValue { if (typeof value === "boolean") return value ? 1 : 0; if (value instanceof ArrayBuffer) return new Uint8Array(value); if (ArrayBuffer.isView(value)) return new Uint8Array(value.buffer, value.byteOffset, value.byteLength); return value; } function meta(duration: number, changes: bigint | number = 0, lastRowId: bigint | number = 0) { const numericChanges = Number(changes); return { changed_db: numericChanges > 0, changes: numericChanges, duration, last_row_id: Number(lastRowId), rows_read: 0, rows_written: numericChanges, size_after: 0, }; } class NodeD1Statement { constructor( private readonly statement: StatementSync, private readonly values: BoundValue[] = [], ) {} bind(...values: BoundValue[]) { return new NodeD1Statement(this.statement, values); } private parameters() { return this.values.map(sqliteValue); } private rows() { return this.statement.all(...this.parameters()) as Record[]; } async first(column?: string) { const row = this.rows()[0] || null; if (!row || column === undefined) return row; if (!(column in row)) throw new Error(`Column ${column} is unavailable.`); return row[column]; } async run() { const started = performance.now(); const result = this.statement.run(...this.parameters()); return { success: true, results: [], meta: meta(performance.now() - started, result.changes, result.lastInsertRowid) }; } async all() { const started = performance.now(); const results = this.rows(); return { success: true, results, meta: meta(performance.now() - started) }; } async raw(options?: { columnNames?: boolean }) { const columns = this.statement.columns().map((column) => column.name); this.statement.setReturnArrays(true); let rows: unknown[][]; try { rows = this.statement.all(...this.parameters()) as unknown as unknown[][]; } finally { this.statement.setReturnArrays(false); } return options?.columnNames ? [columns, ...rows] : rows; } } class NodeD1Database { private readonly database: DatabaseSync; constructor(path: string) { this.database = new DatabaseSync(path); this.database.exec("PRAGMA foreign_keys = ON; PRAGMA journal_mode = WAL; PRAGMA busy_timeout = 5000;"); } prepare(query: string) { return new NodeD1Statement(this.database.prepare(query)); } async batch(statements: NodeD1Statement[]) { this.database.exec("BEGIN IMMEDIATE"); try { const results = []; for (const statement of statements) results.push(await statement.all()); this.database.exec("COMMIT"); return results; } catch (error) { this.database.exec("ROLLBACK"); throw error; } } async exec(query: string) { const started = performance.now(); this.database.exec(query); return { count: 1, duration: performance.now() - started }; } } export function getNodeD1Database(path: string) { let database = databases.get(path); if (!database) { database = new NodeD1Database(path) as unknown as D1Database; databases.set(path, database); } return database; }