Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : MacLustr Social Engine & Remote Navigator8 * File : services/control-api/src/db.ts9 * Module : services10 * Repository : https://git.spboucher.ai/maclustr-social11 * Project Website : https://social.spboucher.ai12 * Created : 2026-12-0113 * Last Modified : 2026-12-0114 *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 */4142import pg from 'pg';43import { readdirSync, readFileSync } from 'node:fs';44import { join } from 'node:path';45pg.types.setTypeParser(20, (v) => Number(v)); // bigint → number (fencing tokens, counters stay < 2^53)46pg.types.setTypeParser(1700, (v) => Number(v));4748export type Tx = { query: <R extends pg.QueryResultRow = any>(text: string, params?: unknown[]) => Promise<pg.QueryResult<R>> };49export class Db implements Tx {50 pool: pg.Pool;51 constructor(url: string, max = 8) { this.pool = new pg.Pool({ connectionString: url, max }); this.pool.on('error', () => {}); }52 query<R extends pg.QueryResultRow = any>(text: string, params?: unknown[]) { return this.pool.query<R>(text, params as any[]); }53 async one<R extends pg.QueryResultRow = any>(text: string, params?: unknown[]): Promise<R | undefined> { return (await this.query<R>(text, params)).rows[0]; }54 async tx<T>(fn: (tx: Tx) => Promise<T>, isolation: 'read committed' | 'serializable' = 'read committed'): Promise<T> {55 for (let attempt = 0; ; attempt++) {56 const c = await this.pool.connect();57 try {58 await c.query(`BEGIN ISOLATION LEVEL ${isolation}`);59 const r = await fn({ query: (t, p) => c.query(t, p as any[]) });60 await c.query('COMMIT');61 return r;62 } catch (e: any) {63 await c.query('ROLLBACK').catch(() => {});64 if ((e?.code === '40001' || e?.code === '40P01') && attempt < 4) continue; // serialization failure / deadlock: safe to retry, nothing left the DB65 throw e;66 } finally { c.release(); }67 }68 }69 end() { return this.pool.end(); }70}7172export async function migrate(db: Db, dir: string, direction: 'up' | 'down' = 'up', log: (s: string) => void = () => {}) {73 await db.query('CREATE TABLE IF NOT EXISTS schema_migrations (name text PRIMARY KEY, applied_at timestamptz NOT NULL DEFAULT now())');74 const files = readdirSync(dir).filter((f) => f.endsWith(`.${direction}.sql`)).sort();75 const done = new Set((await db.query('SELECT name FROM schema_migrations')).rows.map((r) => r.name));76 if (direction === 'up') {77 for (const f of files) {78 const name = f.replace('.up.sql', '');79 if (done.has(name)) continue;80 await db.tx(async (tx) => { await tx.query(readFileSync(join(dir, f), 'utf8')); await tx.query('INSERT INTO schema_migrations(name) VALUES ($1)', [name]); });81 log(`appliquée : ${name}`);82 }83 } else {84 const last = [...done].sort().pop();85 if (!last) return;86 await db.tx(async (tx) => { await tx.query(readFileSync(join(dir, `${last}.down.sql`), 'utf8')); await tx.query('DELETE FROM schema_migrations WHERE name=$1', [last]); });87 log(`annulée : ${last}`);88 }89}90