// A small stand-in for a D1 binding on top of Node's built-in SQLite, for the unit tests and // tools/dev-server.mjs. It covers what src/ uses: prepare().bind().first()/all()/run(), batch(), exec(). import { DatabaseSync } from 'node:sqlite'; import { readdirSync, readFileSync } from 'node:fs'; import { join } from 'node:path'; class Statement { constructor(db, sql, args = []) { this.db = db; this.sql = sql; this.args = args; } bind(...args) { return new Statement(this.db, this.sql, args.map((a) => (a === undefined ? null : typeof a === 'boolean' ? Number(a) : a))); } // D1's ?1, ?2 numbered parameters repeat a value; expand them to plain positional ones. prepared() { if (!/\?\d/.test(this.sql)) return [this.db.prepare(this.sql), this.args]; const args = []; const sql = this.sql.replace(/\?(\d+)/g, (_, n) => { args.push(this.args[Number(n) - 1]); return '?'; }); return [this.db.prepare(sql), args]; } async first(column) { const [stmt, args] = this.prepared(); const row = stmt.get(...args); if (!row) return null; return column ? row[column] : { ...row }; } async all() { const [stmt, args] = this.prepared(); return { success: true, results: stmt.all(...args).map((r) => ({ ...r })), meta: {} }; } async run() { const [stmt, args] = this.prepared(); const info = stmt.run(...args); return { success: true, results: [], meta: { changes: Number(info.changes), last_row_id: Number(info.lastInsertRowid) } }; } } export function openD1(file = ':memory:') { const db = new DatabaseSync(file); db.exec('PRAGMA foreign_keys = ON'); return { raw: db, prepare: (sql) => new Statement(db, sql), async exec(sql) { db.exec(sql); return { count: 1 }; }, async batch(statements) { db.exec('BEGIN'); try { const out = []; for (const s of statements) out.push(/^\s*select/i.test(s.sql) ? await s.all() : await s.run()); db.exec('COMMIT'); return out; } catch (err) { db.exec('ROLLBACK'); throw err; } }, }; } export function migrate(d1, dir) { for (const name of readdirSync(dir).filter((n) => n.endsWith('.sql')).sort()) d1.raw.exec(readFileSync(join(dir, name), 'utf8')); return d1; }