import assert from "node:assert/strict"; import sqlite from "../../src/sqlite.cjs"; import * as runner from "../runner.mjs"; import { promisifyDb, open, handle, init, } from "../../src/db.mjs"; const test_promisifyDb = async t => { t.start("promisifyDb()"); const createTable = "CREATE TABLE table_ (column INTEGER NOT NULL PRIMARY KEY);"; await t.test("we can access the underlying database and statement ref", async () => { const db = await open(":memory:"); assert.ok(db.ref instanceof sqlite.Database); const stmt = await db.prepare("SELECT 1;"); assert.ok(stmt.ref instanceof sqlite.Statement); }); await t.test("we can run the wrapped fns", async () => { const db = await open(":memory:"); await db.exec(createTable); const stmt = await db.prepare("INSERT INTO table_ (column) VALUES ($column)"); await stmt.run({ $column: 3 }); await stmt.run({ $column: 1 }); await stmt.finalize(); assert.rejects( async () => await stmt.run({ $column: 2 }), { message: "SQLITE_MISUSE: Statement is already finalized", code: "SQLITE_MISUSE", }, ); const selectAll = "SELECT column FROM table_ ORDER BY column;"; const all = await db.all(selectAll); assert.deepEqual(all, [{ column: 1 }, { column: 3 }]); const contents = []; const cb = row => contents.push(row); await db.each(selectAll, cb); assert.deepEqual(contents, [{ column: 1 }, { column: 3 }]); }); }; const test_open = async t => { t.start("open()"); await t.test("we must provide a name", () => { assert.rejects( async () => await open(), assert.AssertionError, ); assert.rejects( async () => await open(undefined), assert.AssertionError, ); assert.rejects( async () => await open(null), assert.AssertionError, ); assert.rejects( async () => await open(""), assert.AssertionError, ); }); await t.test("failure to open causes a promise rejection", () => { assert.rejects( async () => await open("tests/non/existing/directory/and/file"), { message: "SQLITE_CANTOPEN: unable to open database file", code: "SQLITE_CANTOPEN", }, ); }); }; const test_init = async t => { t.start("init()"); await t.test("we only know how to deal with 1 database", async () => { const logFn = () => {}; await init(logFn); const ref1 = handle; await init(logFn); const ref2 = handle; assert.notDeepEqual(ref1, ref2); }); }; await runner.runTests([ test_promisifyDb, test_open, test_init, ]);