test: share one node:sqlite harness for the integration tests (#392)

src/test/sqliteHarness.ts opens the schema of a new profile with its seed,
foreign keys on, and stands in for ../services/db: $N bound by name,
rowsAffected and lastInsertId, withTransaction on the same handle, getDb()
refused inside a transaction. split-offset-manual-flag.test.ts and
restore.test.ts drop their two copies of that adapter for it, and
sqliteHarness.test.ts proves its rules once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
le king fu 2026-11-07 22:31:54 -05:00
commit 79abdecc9d
4 changed files with 173 additions and 111 deletions

View file

@ -28,40 +28,16 @@
* an older file keeps the profile's lines whose category comes back. The
* categories come back with their `i18n_key`.
*
* The services run as written on a real SQLite database: `node:sqlite` (built
* into Node, no package), the schema of a new profile with its seed
* (`consolidated_schema.sql`), foreign keys on, as under sqlx. `../services/db`
* is replaced by the adapter of `split-offset-manual-flag.test.ts`, copied here
* (#392 plans a shared harness): `select` and `execute` run the statement with
* its `$N` bound by name, `execute` answers `rowsAffected` and `lastInsertId`,
* `withTransaction` hands its callback the same handle, and `getDb()` throws
* while a transaction runs, where the real lock, which is not reentrant, would
* deadlock. A second database stands for a new profile.
* The services run as written on a real SQLite database, the schema of a new
* profile with its seed (`consolidated_schema.sql`), foreign keys on, as under
* sqlx: `../services/db` is replaced by the shared harness
* (`src/test/sqliteHarness.ts`, #392). A second database stands for a new
* profile.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { readFileSync } from "fs";
import { resolve } from "path";
import { DatabaseSync, type SQLInputValue } from "node:sqlite";
import type { DatabaseSync, SQLInputValue } from "node:sqlite";
const fake = vi.hoisted(() => ({
handle: null as unknown,
inTransaction: false,
}));
vi.mock("../services/db", () => ({
getDb: vi.fn(async () => {
if (fake.inTransaction) throw new Error("getDb() inside a transaction: the real lock would deadlock");
return fake.handle;
}),
withTransaction: vi.fn(async (fn: (db: unknown) => Promise<unknown>) => {
fake.inTransaction = true;
try {
return await fn(fake.handle);
} finally {
fake.inTransaction = false;
}
}),
}));
vi.mock("../services/db", async () => (await import("../test/sqliteHarness")).dbModule());
// « Rétablir la sauvegarde » reads its file through `read_import_file`, and the
// backup taken before the categories migration writes it (#520).
@ -76,6 +52,7 @@ vi.mock("../services/logService", async (orig) => ({
logWarn,
}));
import { openProfileDb, useDb } from "../test/sqliteHarness";
import { getSplitChildren, saveSplitAdjustment } from "../services/transactionService";
import { linkTransfer, listAccountTransfers } from "../services/balance.service";
import {
@ -106,11 +83,6 @@ import { computeMigrationPlan } from "../services/categoryMappingService";
import { applyMigration } from "../services/categoryMigrationService";
import type { Profile } from "../services/profileService";
const SCHEMA = readFileSync(
resolve(import.meta.dirname, "../../src-tauri/src/database/consolidated_schema.sql"),
"utf-8",
);
/** Categories of the seed of a new profile. */
const GROCERIES = 1111; // « Épicerie régulière »
const B = 1112; // « Boucherie & poissonnerie », where the split sends −50
@ -129,37 +101,20 @@ const GROCERY_SPLIT = [
type Mode = "transactions_with_categories" | "transactions_only";
const MODES: Mode[] = ["transactions_with_categories", "transactions_only"];
/** The connection the services see: tauri-plugin-sql's `select` and `execute`, on `db`. */
function adapter(db: DatabaseSync) {
// tauri-plugin-sql binds `$1`, `$2`… by position; node:sqlite binds them by name.
const bind = (params?: unknown[]) =>
Object.fromEntries((params ?? []).map((value, i) => [`$${i + 1}`, value as SQLInputValue]));
return {
select: async (sql: string, params?: unknown[]) =>
db.prepare(sql).all(bind(params)).map((row) => ({ ...row })),
execute: async (sql: string, params?: unknown[]) => {
const result = db.prepare(sql).run(bind(params));
return { rowsAffected: Number(result.changes), lastInsertId: Number(result.lastInsertRowid) };
},
};
}
let opened: DatabaseSync[] = [];
/** The profile the backups are taken from. */
let profile: DatabaseSync;
/** A database with the schema of a new profile, foreign keys on. */
function open(): DatabaseSync {
const db = new DatabaseSync(":memory:", { enableForeignKeyConstraints: true });
db.exec(SCHEMA);
const db = openProfileDb();
opened.push(db);
return db;
}
/** Points the services at `db`. */
function use(db: DatabaseSync): DatabaseSync {
fake.handle = adapter(db);
return db;
return useDb(db);
}
/** A transaction as an import writes it, with its category; its id. */
@ -180,7 +135,6 @@ function imported(date: string, description: string, amount: number, categoryId:
*/
beforeEach(async () => {
opened = [];
fake.inTransaction = false;
invoke.mockReset();
logWarn.mockReset();
profile = use(open());

View file

@ -11,51 +11,23 @@
* keeps its offset line with it. Without that, the keyword of the parent's
* description sends the offset line alone to its category.
*
* The services run as written on a real SQLite database: `node:sqlite` (built
* into Node, no package), the schema of a new profile with its seed
* (`consolidated_schema.sql`), foreign keys on, as under sqlx. `../services/db`
* is replaced by an adapter local to this file (#392 plans a shared harness):
* `select` and `execute` run the statement with its `$N` bound by name,
* `execute` answers `rowsAffected` and `lastInsertId`, `withTransaction` hands
* its callback the same handle, and `getDb()` throws while a transaction runs,
* where the real lock, which is not reentrant, would deadlock.
* The services run as written on a real SQLite database, the schema of a new
* profile with its seed (`consolidated_schema.sql`), foreign keys on, as under
* sqlx: `../services/db` is replaced by the shared harness
* (`src/test/sqliteHarness.ts`, #392).
*/
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { readFileSync } from "fs";
import { resolve } from "path";
import { DatabaseSync, type SQLInputValue } from "node:sqlite";
import type { DatabaseSync } from "node:sqlite";
const fake = vi.hoisted(() => ({
handle: null as unknown,
inTransaction: false,
}));
vi.mock("../services/db", () => ({
getDb: vi.fn(async () => {
if (fake.inTransaction) throw new Error("getDb() inside a transaction: the real lock would deadlock");
return fake.handle;
}),
withTransaction: vi.fn(async (fn: (db: unknown) => Promise<unknown>) => {
fake.inTransaction = true;
try {
return await fn(fake.handle);
} finally {
fake.inTransaction = false;
}
}),
}));
vi.mock("../services/db", async () => (await import("../test/sqliteHarness")).dbModule());
import { openProfileDb, useDb } from "../test/sqliteHarness";
import {
autoCategorizeTransactions,
saveSplitAdjustment,
updateTransactionCategory,
} from "../services/transactionService";
const SCHEMA = readFileSync(
resolve(import.meta.dirname, "../../src-tauri/src/database/consolidated_schema.sql"),
"utf-8",
);
/** « Épicerie régulière », where the seed's `METRO` keyword sends a description that holds METRO. */
const GROCERIES = 1111;
/** « Boucherie & poissonnerie », the category the split sends −50 to. */
@ -64,28 +36,10 @@ const DESCRIPTION = "EPICERIE METRO";
/** The split of the reproduction of #454: −50 of the −120 to B, with the parent's description. */
const ENTRIES = [{ category_id: B, amount: -50, description: DESCRIPTION }];
/** The connection the services see: tauri-plugin-sql's `select` and `execute`, on `db`. */
function adapter(db: DatabaseSync) {
// tauri-plugin-sql binds `$1`, `$2`… by position; node:sqlite binds them by name.
const bind = (params?: unknown[]) =>
Object.fromEntries((params ?? []).map((value, i) => [`$${i + 1}`, value as SQLInputValue]));
return {
select: async (sql: string, params?: unknown[]) =>
db.prepare(sql).all(bind(params)).map((row) => ({ ...row })),
execute: async (sql: string, params?: unknown[]) => {
const result = db.prepare(sql).run(bind(params));
return { rowsAffected: Number(result.changes), lastInsertId: Number(result.lastInsertRowid) };
},
};
}
let db: DatabaseSync;
beforeEach(() => {
db = new DatabaseSync(":memory:", { enableForeignKeyConstraints: true });
db.exec(SCHEMA);
fake.handle = adapter(db);
fake.inTransaction = false;
db = useDb(openProfileDb());
});
afterEach(() => {

View file

@ -0,0 +1,59 @@
import { describe, it, expect, beforeEach, afterEach } from "vitest";
import type { DatabaseSync } from "node:sqlite";
import { adapter, dbModule, openProfileDb, useDb } from "./sqliteHarness";
// The semantics the tests on a real database lean on, proved once.
let db: DatabaseSync;
beforeEach(() => {
db = useDb(openProfileDb());
});
afterEach(() => {
db.close();
});
describe("sqliteHarness", () => {
it("opens the schema of a new profile, seed included", () => {
expect({ ...db.prepare("SELECT name, type FROM categories WHERE id = 1111").get() }).toEqual({
name: "Épicerie régulière",
type: "expense",
});
});
it("binds $1, $2… by position, as tauri-plugin-sql does", async () => {
const rows = await adapter(db).select("SELECT $2 AS second, $1 AS first", [1, "two"]);
expect(rows).toEqual([{ second: "two", first: 1 }]);
});
it("answers rowsAffected and lastInsertId", async () => {
const insert = await adapter(db).execute(
"INSERT INTO transactions (date, description, amount, original_description) VALUES ($1, $2, $3, $2)",
["2026-10-01", "PAIE", 1000],
);
expect(insert).toEqual({ rowsAffected: 1, lastInsertId: 1 });
const update = await adapter(db).execute("UPDATE transactions SET amount = $1", [900]);
expect(update.rowsAffected).toBe(1);
});
it("keeps foreign keys on, as sqlx does", async () => {
await expect(
adapter(db).execute(
"INSERT INTO transactions (date, description, amount, category_id, original_description) VALUES ('2026-10-01', 'X', 1, 999999, 'X')",
),
).rejects.toThrow(/FOREIGN KEY/);
});
it("hands the transaction the same handle, and refuses getDb() inside it", async () => {
const { getDb, withTransaction } = dbModule();
const outside = await getDb();
const inside = await withTransaction(async (handle) => {
await expect(getDb()).rejects.toThrow(/inside a transaction/);
return handle;
});
expect(inside).toBe(outside);
// The transaction is over: getDb() answers again.
await expect(getDb()).resolves.toBe(outside);
});
});

95
src/test/sqliteHarness.ts Normal file
View file

@ -0,0 +1,95 @@
// sqliteHarness — a real SQLite database under the services, for tests (#392).
//
// A fake `select` that returns canned rows proves nothing about a query: the
// rows are already aggregated, so a test of a report could never go red on its
// arithmetic. Under this harness the services run their SQL as written, on
// `node:sqlite` (built into Node, no package; experimental under Node 22,
// which prints a warning once per test file), with the schema of a new profile
// and its seed (`consolidated_schema.sql`), foreign keys on, as under sqlx.
// The app runs SQLite 3.46.0 (`libsqlite3-sys` 0.30.1, bundled) and Node 22
// a later one: a query may not lean on anything newer than 3.46.
//
// USE — at the head of the test module, before the imports of the code under
// test (the factory of `vi.mock` is hoisted, hence the dynamic import):
//
// vi.mock("../services/db", async () => (await import("../test/sqliteHarness")).dbModule());
// import { openProfileDb, useDb } from "../test/sqliteHarness";
//
// then, per test, `db = useDb(openProfileDb())` in `beforeEach` and
// `db.close()` in `afterEach`. Every test module gets its own copy of this
// module, so the database is shared by the mock and the test of one file,
// never across files.
//
// THE FAKE `../services/db`
// - `select` and `execute` run the statement with its `$1`, `$2`… bound by
// name: tauri-plugin-sql binds them by position, `node:sqlite` by name.
// - `execute` answers `rowsAffected` and `lastInsertId`.
// - `withTransaction` hands its callback the same handle; `getDb()` throws
// while a transaction runs, where the real lock, which is not reentrant,
// would deadlock.
//
// This module imports no value from a module that imports `../services/db`
// (no service): the factory above imports it while that module is being built.
// A test that uses it never calls `vi.resetModules()` nor `vi.doMock` on the db
// module: a second copy of this module would split the database in two.
import { readFileSync } from "fs";
import { resolve } from "path";
import { DatabaseSync, type SQLInputValue } from "node:sqlite";
/** The schema of a new profile, seed included. */
export const SCHEMA = readFileSync(
resolve(import.meta.dirname, "../../src-tauri/src/database/consolidated_schema.sql"),
"utf-8",
);
/** A database with the schema of a new profile, foreign keys on. */
export function openProfileDb(): DatabaseSync {
const db = new DatabaseSync(":memory:", { enableForeignKeyConstraints: true });
db.exec(SCHEMA);
return db;
}
/** The connection the services see: tauri-plugin-sql's `select` and `execute`, on `db`. */
export function adapter(db: DatabaseSync) {
// tauri-plugin-sql binds `$1`, `$2`… by position; node:sqlite binds them by name.
const bind = (params?: unknown[]) =>
Object.fromEntries((params ?? []).map((value, i) => [`$${i + 1}`, value as SQLInputValue]));
return {
select: async (sql: string, params?: unknown[]) =>
db.prepare(sql).all(bind(params)).map((row) => ({ ...row })),
execute: async (sql: string, params?: unknown[]) => {
const result = db.prepare(sql).run(bind(params));
return { rowsAffected: Number(result.changes), lastInsertId: Number(result.lastInsertRowid) };
},
};
}
const state = { handle: null as ReturnType<typeof adapter> | null, inTransaction: false };
/** Points the services at `db`, out of any transaction; returns `db`. */
export function useDb(db: DatabaseSync): DatabaseSync {
state.handle = adapter(db);
state.inTransaction = false;
return db;
}
/** The module `../services/db` for `vi.mock`. */
export function dbModule() {
return {
getDb: async () => {
if (state.inTransaction) throw new Error("getDb() inside a transaction: the real lock would deadlock");
if (!state.handle) throw new Error("sqliteHarness: no database, call useDb() first");
return state.handle;
},
withTransaction: async <T>(fn: (db: ReturnType<typeof adapter>) => Promise<T>): Promise<T> => {
if (!state.handle) throw new Error("sqliteHarness: no database, call useDb() first");
state.inTransaction = true;
try {
return await fn(state.handle);
} finally {
state.inTransaction = false;
}
},
};
}