1 file changed
+63
@@ -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;
|
||||
}
|
||||
Reference in new issue
Block a user