Versie 0.2.0
This commit is contained in:
commit
e77d8fd373
495 files changed
+81026
No files matched your search
@@ -0,0 +1,73 @@
|
||||
// Generated, do not edit. sha256:95f28c26a77b79beac5f8c6818bd25243362641c1d8549949427a847e4f810f9
|
||||
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 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;
|
||||
}
|
||||
Reference in new issue
Block a user