import { mkdirSync, existsSync } from "node:fs"; import { dirname } from "node:path"; import { Database } from "bun:sqlite"; import { setMetaValue } from "./meta"; const SCHEMA_VERSION = "4"; export function openDatabase(path: string, createParent: boolean): Database { if (createParent) { mkdirSync(dirname(path), { recursive: true }); } else if (!existsSync(path)) { throw new Error("index database does not exist"); } const database = new Database(path, { create: true, strict: true }); initializeWritable(database); return database; } export function openReadonlyDatabase(path: string): Database { if (!existsSync(path)) { throw new Error("index database does not exist"); } const database = new Database(path, { readonly: true, strict: true }); initializeReadonly(database); return database; } function initializeWritable(database: Database): void { database.exec(` PRAGMA foreign_keys = ON; PRAGMA journal_mode = WAL; PRAGMA synchronous = NORMAL; PRAGMA busy_timeout = 30000; CREATE TABLE IF NOT EXISTS schema_meta ( key TEXT PRIMARY KEY, value TEXT NOT NULL ); CREATE TABLE IF NOT EXISTS commands ( name TEXT PRIMARY KEY, command_path TEXT NOT NULL, path_order INTEGER NOT NULL, indexed_at INTEGER NOT NULL ); CREATE TABLE IF NOT EXISTS command_metadata ( command_name TEXT PRIMARY KEY REFERENCES commands(name) ON DELETE CASCADE, description TEXT NOT NULL, source TEXT NOT NULL, updated_at INTEGER NOT NULL ); CREATE TABLE IF NOT EXISTS seed_metadata ( command_name TEXT PRIMARY KEY, description TEXT, source TEXT NOT NULL, updated_at INTEGER NOT NULL ); CREATE TABLE IF NOT EXISTS command_embeddings ( command_name TEXT PRIMARY KEY REFERENCES commands(name) ON DELETE CASCADE, embedder_fingerprint TEXT NOT NULL, description_hash TEXT NOT NULL, vector_json TEXT NOT NULL, updated_at INTEGER NOT NULL ); `); const row = database .query("SELECT value FROM schema_meta WHERE key = 'schema_version'") .get() as { value: string } | null; if (!row) { setMetaValue(database, "schema_version", SCHEMA_VERSION); return; } validateSchemaRow(row); } function initializeReadonly(database: Database): void { database.exec(` PRAGMA busy_timeout = 30000; `); const row = database .query("SELECT value FROM schema_meta WHERE key = 'schema_version'") .get() as { value: string } | null; if (!row) { throw new Error("index database is missing schema metadata"); } validateSchemaRow(row); } function validateSchemaRow(row: { value: string }): void { if (row.value !== SCHEMA_VERSION) { throw new Error(`schema version ${row.value} does not match this binary's schema ${SCHEMA_VERSION}`); } }