From 1914cee0eb166da8b500b52b0d062e920cd6d200 Mon Sep 17 00:00:00 2001 From: nocode Date: Sun, 13 Sep 2026 12:19:10 +0200 Subject: [PATCH] feat(database): initialize sqlite connection and migrations Refs: #16 Co-Authored-By: Claude Opus 5 (1M context) --- src/database/index.js | 63 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 src/database/index.js diff --git a/src/database/index.js b/src/database/index.js new file mode 100644 index 0000000..4594a49 --- /dev/null +++ b/src/database/index.js @@ -0,0 +1,63 @@ +import { mkdirSync, readdirSync, readFileSync } from 'node:fs'; +import path from 'node:path'; +import { DatabaseSync } from 'node:sqlite'; +import { fileURLToPath } from 'node:url'; +import { env } from '../config/env.js'; +import { createLogger } from '../core/logger.js'; + +const log = createLogger('database'); +const migrationsDir = path.join(path.dirname(fileURLToPath(import.meta.url)), 'migrations'); + +let db; + +function runMigrations(database) { + database.exec(`CREATE TABLE IF NOT EXISTS schema_migrations ( + name TEXT PRIMARY KEY, + applied_at TEXT NOT NULL DEFAULT (datetime('now')) + )`); + + const applied = new Set( + database + .prepare('SELECT name FROM schema_migrations') + .all() + .map((row) => row.name), + ); + const pending = readdirSync(migrationsDir) + .filter((file) => file.endsWith('.sql') && !applied.has(file)) + .sort(); + + for (const file of pending) { + database.exec('BEGIN'); + try { + database.exec(readFileSync(path.join(migrationsDir, file), 'utf8')); + database.prepare('INSERT INTO schema_migrations (name) VALUES (?)').run(file); + database.exec('COMMIT'); + log.info(`Applied migration ${file}`); + } catch (error) { + database.exec('ROLLBACK'); + throw error; + } + } +} + +export function initDatabase(filePath = env.database.path) { + if (db) return db; + + if (filePath !== ':memory:') { + mkdirSync(path.dirname(filePath), { recursive: true }); + } + db = new DatabaseSync(filePath); + db.exec('PRAGMA journal_mode = WAL; PRAGMA foreign_keys = ON;'); + runMigrations(db); + return db; +} + +export function getDatabase() { + if (!db) throw new Error('Database not initialized. Call initDatabase() first.'); + return db; +} + +export function closeDatabase() { + db?.close(); + db = undefined; +}