Files
Termix/src/backend/tests/database/repositories/test-support.ts
T
ZacharyZcR 64a80f411a make the repository layer engine-agnostic (#1127)
DatabaseContext handed every repository a raw better-sqlite3 handle alongside
drizzle, and three of them used it for retention queries built on datetime('now',
?) — a SQLite-only function. That handle is the one thing standing between the
repository layer and a second engine.

Drop it. The two time-based prunes compute their cutoff in JS against the
CURRENT_TIMESTAMP text format, which every engine writes the same way and which
compares correctly as a string; the health-history prune becomes a select of the
rows to keep followed by a NOT IN delete. All three turn async, so their two
callers await them.

Name the dialect rather than repeating a string literal, so adding an engine is
one edit instead of a search.

Tests built their schema through context.sqlite?.exec(). Optional chaining meant
removing the field type-checked cleanly and then silently created no tables, so
the fixture now owns exec() and a raw handle for direct assertions — schema setup
belongs to the test harness, not to the interface repositories consume.

No behaviour change, and no Postgres yet: this only removes the coupling that
would have to be undone first.
2026-07-28 16:59:10 +08:00

51 lines
1.4 KiB
TypeScript

import Database from "better-sqlite3";
import { drizzle } from "drizzle-orm/better-sqlite3";
import * as schema from "../../../database/db/schema.js";
import type { DatabaseContext } from "../../../database/repositories/database-context.js";
export class TestSqliteDatabase {
private sqlite: Database.Database | null = null;
private context: DatabaseContext | null = null;
async connect(): Promise<DatabaseContext> {
if (this.context) return this.context;
this.sqlite = new Database(":memory:");
this.sqlite.exec("PRAGMA foreign_keys = ON");
this.context = {
dialect: "sqlite",
drizzle: drizzle(this.sqlite, { schema }),
};
return this.context;
}
/**
* Schema setup for tests. Lives on the fixture rather than on
* DatabaseContext, which is drizzle-only so that no repository can reach for
* engine-specific SQL.
*/
/** Raw handle for assertions that read the database directly. Tests only. */
get raw(): Database.Database {
if (!this.sqlite) {
throw new Error("connect() must be called before raw access");
}
return this.sqlite;
}
exec(sql: string): void {
if (!this.sqlite) {
throw new Error("connect() must be called before exec()");
}
this.sqlite.exec(sql);
}
async close(): Promise<void> {
if (this.sqlite) {
this.sqlite.close();
this.sqlite = null;
this.context = null;
}
}
}