import { fileURLToPath } from "node:url"; import { dirname, resolve } from "node:path"; import Database from "better-sqlite3"; import { drizzle } from "drizzle-orm/better-sqlite3"; import { migrate } from "drizzle-orm/better-sqlite3/migrator"; import * as schema from "./schema.js"; import type { Db } from "./index.js"; // Test-only helper: a fresh, fully-migrated SQLite database with NO live-DB risk. // Every server/integration test spins one of these so suites are isolated and // deterministic — never the real parking.sqlite. Not exported from the package // root (`@parking/db`); import it from `@parking/db/testing` in test code only. // The migrations live next to this package's compiled output. From dist/testing.js // that's ../drizzle; resolve it off import.meta.url so it works regardless of the // caller's cwd (tests run from apps/server, packages/devices, etc.). const MIGRATIONS_DIR = resolve(dirname(fileURLToPath(import.meta.url)), "../drizzle"); /** * Open an in-memory SQLite (or a temp file if `url` is given), apply every Drizzle * migration in order, and return a typed Drizzle handle plus the raw better-sqlite3 * connection (so a test can assert raw rows or `.close()` it). The schema matches * production exactly because it's the SAME migration set, not a hand-rolled DDL. */ export function createTestDb(url = ":memory:"): { db: Db; sqlite: Database.Database; close: () => void } { const sqlite = new Database(url); sqlite.pragma("journal_mode = WAL"); sqlite.pragma("foreign_keys = ON"); const db = drizzle(sqlite, { schema }) as Db; migrate(db, { migrationsFolder: MIGRATIONS_DIR }); return { db, sqlite, close: () => sqlite.close() }; } /** * Open an EXISTING SQLite file raw, WITHOUT running migrations — for tests that need to * inspect a file produced elsewhere (e.g. a restored backup) exactly as written, without * mutating it. Returns the raw better-sqlite3 handle so the caller depends only on * `@parking/db/testing`, never on `better-sqlite3` directly. */ export function openRawDb(url: string): Database.Database { return new Database(url); }