import { DatabaseSync } from "node:sqlite"; import fs from "node:fs"; import path from "node:path"; import { schemaStatements } from "./schema"; export function openDatabase(filename?: string): DatabaseSync { const databaseFile = filename ?? process.env.VCFTA_DATABASE_PATH ?? path.resolve(process.cwd(), ".data/flight-deck.sqlite"); if (databaseFile !== ":memory:") { fs.mkdirSync(path.dirname(databaseFile), { recursive: true }); } const database = new DatabaseSync(databaseFile); database.exec("PRAGMA foreign_keys = ON"); database.exec("PRAGMA journal_mode = WAL"); for (const statement of schemaStatements) { database.prepare(statement).run(); } const occurrenceColumns = new Set( ( database.prepare("PRAGMA table_info(flight_occurrences)").all() as Array<{ name: string; }> ).map((column) => column.name), ); const localTimeColumns = [ "scheduled_departure_local", "estimated_departure_local", "actual_departure_local", "scheduled_arrival_local", "estimated_arrival_local", "actual_arrival_local", ]; for (const column of localTimeColumns) { if (!occurrenceColumns.has(column)) { database.exec(`ALTER TABLE flight_occurrences ADD COLUMN ${column} TEXT`); } } return database; }