bkr

tutorial

SQLite and tests

Build a small data layer with the built-in sqlite module, test it with bkr test, and persist it to disk.

1. Write a database module

sqlite loads the system SQLite shared library (3.31+) at startup. In-memory databases need no filesystem permissions. Create todos.ts:

import { Database } from "sqlite";

export function openTodos(path = ":memory:") {
  const db = new Database(path);
  db.exec(`
    CREATE TABLE IF NOT EXISTS todos (
      id INTEGER PRIMARY KEY,
      title TEXT NOT NULL,
      done INTEGER NOT NULL DEFAULT 0
    )
  `);

  const insert = db.prepare("INSERT INTO todos (title) VALUES (:title)");
  const byId = db.prepare("SELECT id, title, done FROM todos WHERE id = ?");
  const listAll = db.prepare("SELECT id, title, done FROM todos ORDER BY id");

  const addBatch = db.transaction((titles: string[]) => {
    for (const title of titles) insert.run({ title });
  });

  return {
    db,
    add(title: string) {
      const { lastInsertRowid } = insert.run({ title });
      return byId.get(lastInsertRowid);
    },
    addBatch,
    all() {
      return listAll.all();
    },
    [Symbol.dispose]() {
      db.close();
    },
  };
}

db.close() finalizes every prepared statement on that connection. Adding Symbol.dispose lets callers bind the store with using so it closes when the block exits.

2. Write tests

Create todos.test.ts:

import { test, describe, assertEquals, assertThrows } from "test";
import { openTodos } from "./todos.ts";

describe("todos", () => {
  test("inserts and queries rows", () => {
    using store = openTodos();
    const item = store.add("Write docs");
    assertEquals(item, { id: 1, title: "Write docs", done: 0 });
  });

  test("rolls back failed transactions", () => {
    using store = openTodos();
    assertThrows(() => {
      store.addBatch(["First", null as unknown as string]);
    });
    assertEquals(store.all(), []);
  });
});

3. Run the test suite

Run bkr test on the file. Omit the path to discover all *.test.*, *_test.*, and *.spec.* files under the current directory:

bkr test todos.test.ts
todos.test.ts
  ✓ todos > inserts and queries rows (0.45 ms)
  ✓ todos > rolls back failed transactions (0.31 ms)

2 passed (1.82 ms)

Use --filter=rolls to run matching tests only, or --watch to rerun in a fresh process when files change.

4. Persist to disk

Create app.ts and pass a file path to openTodos:

import { openTodos } from "./todos.ts";

using store = openTodos("./data/todos.db");
store.add("Ship release");
console.log(store.all());

File-backed databases check read and write permissions for the database file plus its -journal, -wal, and -shm sidecars. Grant both on the directory holding the database:

mkdir -p ./data
bkr --allow-read=./data --allow-write=./data app.ts

Next