import { mkdirSync, rmSync } from 'node:fs'; import { dirname, join } from 'node:path'; import { Database } from 'bun:sqlite'; import { ensureFinancialIngestionSchemaHealthy } from '../lib/server/db/financial-ingestion-schema'; import { ensureLocalSqliteSchema } from '../lib/server/db/sqlite-schema-compat'; export const E2E_DATABASE_PATH = join(process.cwd(), 'data', 'e2e.sqlite'); export const E2E_WORKFLOW_DATA_DIR = join(process.cwd(), '.workflow-data', 'e2e'); type PrepareE2eDatabaseOptions = { databasePath?: string; workflowDataDir?: string; }; function removeFileIfPresent(path: string) { rmSync(path, { force: true }); } export function prepareE2eDatabase(options: PrepareE2eDatabaseOptions = {}) { const databasePath = options.databasePath ?? E2E_DATABASE_PATH; const workflowDataDir = options.workflowDataDir ?? E2E_WORKFLOW_DATA_DIR; mkdirSync(dirname(databasePath), { recursive: true }); removeFileIfPresent(databasePath); removeFileIfPresent(`${databasePath}-shm`); removeFileIfPresent(`${databasePath}-wal`); rmSync(workflowDataDir, { force: true, recursive: true }); const database = new Database(databasePath, { create: true }); try { database.exec('PRAGMA foreign_keys = ON;'); ensureLocalSqliteSchema(database); ensureFinancialIngestionSchemaHealthy(database, { mode: 'auto' }); } finally { database.close(); } } if (import.meta.main) { prepareE2eDatabase(); console.info(`[e2e] prepared SQLite database at ${E2E_DATABASE_PATH}`); }