import { Database } from 'bun:sqlite' import { randomUUID } from 'node:crypto' import { existsSync, unlinkSync } from 'node:fs' import { tmpdir } from 'node:os' import { resolve } from 'node:path' import { afterAll } from 'bun:test' import { initDatabase, resetDbSingleton } from '../../db/sqlite' const _tempDbs: string[] = [] /** * Create a fresh database instance for testing. * Automatically cleans up temp files in afterAll. */ export function freshDb(): Database { try { resetDbSingleton() } catch { // ignore cleanup errors } const path = resolve( tmpdir(), `rcs-test-${randomUUID().replace(/-/g, '').slice(0, 8)}.db`, ) const db = initDatabase(path) _tempDbs.push(path) return db } afterAll(() => { for (const path of _tempDbs) { for (const suffix of ['', '-wal', '-shm']) { try { if (existsSync(path + suffix)) { unlinkSync(path + suffix) } } catch { // ignore cleanup errors } } } _tempDbs.length = 0 })