84 lines
2.3 KiB
JavaScript
84 lines
2.3 KiB
JavaScript
// Generated, do not edit. sha256:232164f95c0eb5137f0c20ab218bdb9ffd81d26142889e12d2caf11dfbc181a3
|
|
import { DatabaseSync } from 'node:sqlite';
|
|
|
|
export const BUSY_TIMEOUT_MS = 5000;
|
|
|
|
let db = null;
|
|
|
|
export function openDatabase(pad) {
|
|
if (db) throw new Error('A database connection is already open; close it first with closeDatabase().');
|
|
db = new DatabaseSync(pad, { enableForeignKeyConstraints: true });
|
|
db.exec(`PRAGMA journal_mode = WAL`);
|
|
db.exec(`PRAGMA synchronous = NORMAL`);
|
|
db.exec(`PRAGMA busy_timeout = ${BUSY_TIMEOUT_MS}`);
|
|
return db;
|
|
}
|
|
|
|
export function database() { return db; }
|
|
|
|
export function withOtherDatabase(pad, fn) {
|
|
const vorige = db;
|
|
db = null;
|
|
try {
|
|
openDatabase(pad);
|
|
const uit = fn();
|
|
if (uit && typeof uit.then === 'function') throw new Error('withOtherDatabase: fn must be synchronous.');
|
|
return uit;
|
|
} finally {
|
|
closeDatabase();
|
|
db = vorige;
|
|
}
|
|
}
|
|
|
|
export function peekDatabase(pad, fn) {
|
|
const peek = new DatabaseSync(pad, { readOnly: true });
|
|
const all = (sql, params = []) => peek.prepare(sql).all(...bind(params)).map(rij => ({ ...rij }));
|
|
try {
|
|
return fn({ all, one: (sql, params = []) => all(sql, params)[0] ?? null });
|
|
} finally {
|
|
peek.close();
|
|
}
|
|
}
|
|
|
|
export function closeDatabase() {
|
|
if (!db) return;
|
|
db.close();
|
|
db = null;
|
|
}
|
|
|
|
export function pragmaStand() {
|
|
const lees = (naam, veld) => database().prepare(`PRAGMA ${naam}`).get()[veld];
|
|
return {
|
|
foreignKeys: lees('foreign_keys', 'foreign_keys') === 1,
|
|
journalMode: lees('journal_mode', 'journal_mode'),
|
|
synchronous: lees('synchronous', 'synchronous'),
|
|
busyTimeout: lees('busy_timeout', 'timeout'),
|
|
};
|
|
}
|
|
|
|
const bind = params => params.map(v => {
|
|
if (v === undefined) return null;
|
|
if (typeof v === 'boolean') return v ? 1n : 0n;
|
|
if (typeof v === 'number' && Number.isInteger(v)) return BigInt(v);
|
|
return v;
|
|
});
|
|
|
|
export function run(sql, params) {
|
|
if (params === undefined) db.exec(sql);
|
|
else db.prepare(sql).run(...bind(params));
|
|
}
|
|
|
|
export function all(sql, params = []) {
|
|
return db.prepare(sql).all(...bind(params)).map(rij => ({ ...rij }));
|
|
}
|
|
|
|
export function one(sql, params = []) {
|
|
const rijen = all(sql, params);
|
|
return rijen.length ? rijen[0] : null;
|
|
}
|
|
|
|
export function lastId() {
|
|
const r = one(`SELECT last_insert_rowid() AS id`);
|
|
return r ? r.id : null;
|
|
}
|