109 lines · 5.3 KB
import { beforeEach, expect, mock, test } from "bun:test";
import { Database } from "bun:sqlite";
import { applyCombinedSchema } from "./test-schema.test-helper";

const db = new Database(":memory:");
applyCombinedSchema(db);

type Statement = { sql: string; params: unknown[] };
const exec = (sql: string, params: unknown[]) => db.query(sql).run(...(params as never[]));
mock.module("./db", () => ({
  first: async (sql: string, ...params: unknown[]) => db.query(sql).get(...(params as never[])) ?? null,
  all: async (sql: string, ...params: unknown[]) => db.query(sql).all(...(params as never[])),
  run: async (sql: string, ...params: unknown[]) => ({
    meta: { changes: exec(sql, params).changes },
  }),
  batch: async (statements: Statement[]) => statements.map((statement) => exec(statement.sql, statement.params)),
  stmt: (sql: string, ...params: unknown[]): Statement => ({ sql, params }),
}));
// Every repo and account object shares the one test database (it still has every table), so seeds stay in one place.
const scoped = {
  first: async (sql: string, ...params: unknown[]) => db.query(sql).get(...(params as never[])) ?? null,
  all: async (sql: string, ...params: unknown[]) => db.query(sql).all(...(params as never[])),
  run: async (sql: string, ...params: unknown[]) => ({
    meta: {
      changes: db.query(sql).run(...(params as never[])).changes,
      last_row_id: 0,
    },
  }),
  batch: async (statements: Array<{ sql: string; params: unknown[] }>) =>
    statements.map((statement) => ({
      meta: {
        changes: db.query(statement.sql).run(...(statement.params as never[])).changes,
        last_row_id: 0,
      },
    })),
};
mock.module("./scoped-db", () => ({
  repoDb: (scopeId: string) => ({ scopeId, ...scoped }),
  accountDb: (scopeId: string) => ({ scopeId, ...scoped }),
  stmt: (sql: string, ...params: unknown[]) => ({ sql, params }),