Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : MacLustr Vision8 * File : server/src/db.ts9 * Module : server10 * Repository : https://git.spboucher.ai/maclustr-vision11 * Project Website : https://camera.spboucher.ai12 * Created : 2026-11-3013 * Last Modified : 2026-11-3014 *15 * Author : Simon-Pierre Boucher16 * Position : Professor of Finance17 * Institution : Université du Québec en Outaouais (UQO)18 * Organization : SP Boucher19 * Website : https://spboucher.ai20 * Git : https://git.spboucher.ai21 *22 * Preferred Contact: admin@spboucher.ai23 * Technical Contact: dev@spboucher.ai24 * Security/Admin : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142// SQLite (node:sqlite) en mode WAL sur disque local, migrations transactionnelles.43import fs from 'node:fs';44import path from 'node:path';45import { DatabaseSync } from 'node:sqlite';46import type { Config } from './config.ts';4748export type DB = DatabaseSync;4950export function openDb(file: string): DB {51 fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });52 const db = new DatabaseSync(file);53 db.exec('PRAGMA journal_mode = WAL; PRAGMA synchronous = NORMAL; PRAGMA busy_timeout = 8000; PRAGMA foreign_keys = ON;');54 try {55 fs.chmodSync(file, 0o600);56 } catch {57 /* base en mémoire */58 }59 return db;60}6162export function migrate(db: DB, migrationsDir: string): string[] {63 db.exec('CREATE TABLE IF NOT EXISTS schema_migrations (version INTEGER PRIMARY KEY, name TEXT NOT NULL, applied_ms INTEGER NOT NULL)');64 const files = fs.readdirSync(migrationsDir).filter((f) => /^\d+_.+\.sql$/.test(f)).sort();65 const applied: string[] = [];66 for (const f of files) {67 const version = parseInt(f, 10);68 db.exec('BEGIN IMMEDIATE');69 try {70 const done = db.prepare('SELECT 1 AS x FROM schema_migrations WHERE version = ?').get(version);71 if (!done) {72 db.exec(fs.readFileSync(path.join(migrationsDir, f), 'utf8'));73 db.prepare('INSERT INTO schema_migrations (version, name, applied_ms) VALUES (?, ?, ?)').run(version, f, Date.now());74 applied.push(f);75 }76 db.exec('COMMIT');77 } catch (e) {78 db.exec('ROLLBACK');79 throw e;80 }81 }82 return applied;83}8485export function openAndMigrate(cfg: Config): DB {86 const db = openDb(cfg.dbPath);87 migrate(db, cfg.migrationsDir);88 return db;89}9091export function tx<T>(db: DB, fn: () => T): T {92 db.exec('BEGIN IMMEDIATE');93 try {94 const r = fn();95 db.exec('COMMIT');96 return r;97 } catch (e) {98 db.exec('ROLLBACK');99 throw e;100 }101}102103export function getSetting<T>(db: DB, key: string, fallback: T): T {104 const row = db.prepare('SELECT value FROM settings WHERE key = ?').get(key) as { value: string } | undefined;105 if (!row) return fallback;106 try {107 return JSON.parse(row.value) as T;108 } catch {109 return fallback;110 }111}112113export function setSetting(db: DB, key: string, value: unknown): void {114 db.prepare('INSERT INTO settings (key, value, updated_ms) VALUES (?, ?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_ms = excluded.updated_ms').run(115 key,116 JSON.stringify(value),117 Date.now(),118 );119}120121export function addEvent(db: DB, ev: { cameraId?: string | null; type: string; severity?: 'info' | 'warning' | 'critical'; message: string; data?: unknown; tsMs?: number }): void {122 db.prepare('INSERT INTO events (ts_ms, camera_id, type, severity, message, data) VALUES (?, ?, ?, ?, ?, ?)').run(123 ev.tsMs ?? Date.now(),124 ev.cameraId ?? null,125 ev.type,126 ev.severity ?? 'info',127 ev.message,128 JSON.stringify(ev.data ?? {}),129 );130}131132export function audit(db: DB, actor: string, ip: string | null, action: string, detail: unknown = {}): void {133 db.prepare('INSERT INTO audit_log (ts_ms, actor, ip, action, detail) VALUES (?, ?, ?, ?, ?)').run(Date.now(), actor, ip, action, JSON.stringify(detail));134}135