Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : KA Maps Engine8 * File : studio/server/db.ts9 * Module : studio10 * Repository : https://git.spboucher.ai/ka-maps-engine11 * Created : 2026-12-0112 * Last Modified : 2026-12-0113 *14 * Author : Simon-Pierre Boucher15 * Position : Professor of Finance16 * Institution : Université du Québec en Outaouais (UQO)17 * Organization : SP Boucher18 * Website : https://spboucher.ai19 * Git : https://git.spboucher.ai20 *21 * Preferred Contact: support@spboucher.ai22 * Development : dev@spboucher.ai23 * Support : support@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// Accès PostgreSQL du Studio : connexion, transactions, migrations.43import { readdir, readFile } from 'node:fs/promises';44import { dirname, join } from 'node:path';45import { fileURLToPath } from 'node:url';46import pg from 'pg';4748export type Db = { pool: pg.Pool; schema: string };49export type Tx = pg.PoolClient;5051// Les dates et les entiers 64 bits restent lisibles côté JSON.52pg.types.setTypeParser(20, (v) => Number(v));5354export function connect(url: string, schema = 'studio'): Db {55 if (!/^[a-z_][a-z0-9_]{0,30}$/.test(schema)) throw new Error('nom de schéma invalide');56 const pool = new pg.Pool({ connectionString: url, max: 10, idleTimeoutMillis: 30_000 });57 pool.on('error', (e) => console.error(`pg : ${e.message}`));58 return { pool, schema };59}6061export async function tx<T>(db: Db, fn: (c: Tx) => Promise<T>): Promise<T> {62 const c = await db.pool.connect();63 try {64 await c.query('BEGIN');65 const r = await fn(c);66 await c.query('COMMIT');67 return r;68 } catch (e) {69 await c.query('ROLLBACK').catch(() => {});70 throw e;71 } finally {72 c.release();73 }74}7576/** Applique les fichiers sql/NNN_*.sql manquants. Les fichiers nomment le schéma `studio` ; un77 * autre nom (essais) est substitué à l'application. */78export async function migrate(db: Db): Promise<string[]> {79 const dir = join(dirname(fileURLToPath(import.meta.url)), '..', 'sql');80 const files = (await readdir(dir)).filter((f) => /^\d{3}_.*\.sql$/.test(f)).sort();81 const s = db.schema;82 const ns = await db.pool.query('SELECT 1 FROM pg_namespace WHERE nspname = $1', [s]);83 if (!ns.rows[0]) await db.pool.query(`CREATE SCHEMA ${s}`);84 const has = await db.pool.query(`SELECT to_regclass('${s}.migration') AS t`);85 const done = new Set<string>(has.rows[0].t ? (await db.pool.query(`SELECT name FROM ${s}.migration`)).rows.map((r) => r.name) : []);86 const applied: string[] = [];87 for (const f of files) {88 if (done.has(f)) continue;89 const sql = (await readFile(join(dir, f), 'utf8')).replace(/\bstudio\./g, `${s}.`).replace(/\bSCHEMA studio\b/g, `SCHEMA ${s}`);90 await tx(db, async (c) => {91 await c.query(sql);92 await c.query(`INSERT INTO ${s}.migration (name) VALUES ($1)`, [f]);93 });94 applied.push(f);95 }96 return applied;97}9899export class HttpError extends Error {100 status: number;101 detail: unknown;102 constructor(status: number, message: string, detail?: unknown) {103 super(message);104 this.status = status;105 this.detail = detail;106 }107}108109export type Actor = { id: string | null; name: string; ip?: string | null };110111export async function audit(c: Tx | pg.Pool, schema: string, actor: Actor, action: string, target: string | null, detail: unknown = {}) {112 await c.query(`INSERT INTO ${schema}.audit (admin_id, admin_name, action, target, detail, ip) VALUES ($1, $2, $3, $4, $5, $6)`, [actor.id, actor.name, action, target, JSON.stringify(detail), actor.ip ?? null]);113}114115export async function bumpRevision(c: Tx, schema: string) {116 await c.query(`UPDATE ${schema}.state SET value = value + 1 WHERE key = 'revision'`);117}118