const Database = require('better-sqlite3'); const schema = require('./schema'); const {getEnv, SQLITE } = require('@nexusai/shared'); let db; // Declare db variable in a scope accessible to all functions function getDB() { if (!db) { const path = getEnv('SQLITE_PATH', SQLITE.DEFAULT_PATH); db = new Database(path); db.pragma('journal_mode = WAL'); db.pragma('foreign_keys = ON'); db.exec(schema); try{ db.exec(`ALTER TABLE sessions ADD COLUMN name TEXT`) } catch {} try { db.exec(`ALTER TABLE sessions ADD COLUMN project_id INTEGER REFERENCES projects(id)`); } catch {} try { db.exec(`CREATE INDEX IF NOT EXISTS idx_sessions_project ON sessions(project_id)`); } catch {} try { db.exec(`ALTER TABLE projects ADD COLUMN isolated INTEGER NOT NULL DEFAULT 0`); } catch {} try { db.exec(`ALTER TABLE projects ADD COLUMN notes TEXT`); // ← add this } catch {} try { db.exec(`ALTER TABLE projects ADD COLUMN system_prompt TEXT`); } catch {} // Sync FTS index with any existing episodes data db.exec(`INSERT OR REPLACE INTO episodes_fts(rowid, user_message, ai_response) SELECT id, user_message, ai_response FROM episodes`); console.log(`Connected to SQLite database at ${path}`); } return db; } module.exports = { getDB };