Jobley / website · jobley.ai / tools / d1-local.mjs
| 1 | // A small stand-in for a D1 binding on top of Node's built-in SQLite, for the unit tests and |
| 2 | // tools/dev-server.mjs. It covers what src/ uses: prepare().bind().first()/all()/run(), batch(), exec(). |
| 3 | import { DatabaseSync } from 'node:sqlite'; |
| 4 | import { readdirSync, readFileSync } from 'node:fs'; |
| 5 | import { join } from 'node:path'; |
| 6 | |
| 7 | class Statement { |
| 8 | constructor(db, sql, args = []) { this.db = db; this.sql = sql; this.args = args; } |
| 9 | bind(...args) { return new Statement(this.db, this.sql, args.map((a) => (a === undefined ? null : typeof a === 'boolean' ? Number(a) : a))); } |
| 10 | // D1's ?1, ?2 numbered parameters repeat a value; expand them to plain positional ones. |
| 11 | prepared() { |
| 12 | if (!/\?\d/.test(this.sql)) return [this.db.prepare(this.sql), this.args]; |
| 13 | const args = []; |
| 14 | const sql = this.sql.replace(/\?(\d+)/g, (_, n) => { args.push(this.args[Number(n) - 1]); return '?'; }); |
| 15 | return [this.db.prepare(sql), args]; |
| 16 | } |
| 17 | async first(column) { |
| 18 | const [stmt, args] = this.prepared(); |
| 19 | const row = stmt.get(...args); |
| 20 | if (!row) return null; |
| 21 | return column ? row[column] : { ...row }; |
| 22 | } |
| 23 | async all() { |
| 24 | const [stmt, args] = this.prepared(); |
| 25 | return { success: true, results: stmt.all(...args).map((r) => ({ ...r })), meta: {} }; |
| 26 | } |
| 27 | async run() { |
| 28 | const [stmt, args] = this.prepared(); |
| 29 | const info = stmt.run(...args); |
| 30 | return { success: true, results: [], meta: { changes: Number(info.changes), last_row_id: Number(info.lastInsertRowid) } }; |
| 31 | } |
| 32 | } |
| 33 | |
| 34 | export function openD1(file = ':memory:') { |
| 35 | const db = new DatabaseSync(file); |
| 36 | db.exec('PRAGMA foreign_keys = ON'); |
| 37 | return { |
| 38 | raw: db, |
| 39 | prepare: (sql) => new Statement(db, sql), |
| 40 | async exec(sql) { db.exec(sql); return { count: 1 }; }, |
| 41 | async batch(statements) { |
| 42 | db.exec('BEGIN'); |
| 43 | try { |
| 44 | const out = []; |
| 45 | for (const s of statements) out.push(/^\s*select/i.test(s.sql) ? await s.all() : await s.run()); |
| 46 | db.exec('COMMIT'); |
| 47 | return out; |
| 48 | } catch (err) { |
| 49 | db.exec('ROLLBACK'); |
| 50 | throw err; |
| 51 | } |
| 52 | }, |
| 53 | }; |
| 54 | } |
| 55 | |
| 56 | export function migrate(d1, dir) { |
| 57 | for (const name of readdirSync(dir).filter((n) => n.endsWith('.sql')).sort()) d1.raw.exec(readFileSync(join(dir, name), 'utf8')); |
| 58 | return d1; |
| 59 | } |