import { mkdirSync } from "node:fs"; import { dirname } from "node:path"; import { DatabaseSync } from "node:sqlite"; export function openDatabase(path: string): DatabaseSync { mkdirSync(dirname(path), { recursive: true }); const database = new DatabaseSync(path, { enableForeignKeyConstraints: true, enableDoubleQuotedStringLiterals: false, allowExtension: false, timeout: 5000, }); try { // Connection settings belong here, outside migration transactions. Every // future connection must use this function, including administrative tools. database.exec(` PRAGMA journal_mode = WAL; PRAGMA synchronous = FULL; PRAGMA trusted_schema = OFF; `); database.enableDefensive(true); if (database.prepare("PRAGMA journal_mode").get()?.journal_mode !== "wal") { throw new Error("The AppView database must support WAL on local persistent storage."); } return database; } catch (error) { database.close(); throw error; } }