SPB Git

Repository Public

db.ts 4.0 KB 93 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : MacLustr SMS Gateway8 * File             : backend/src/db.ts9 * Module           : backend10 * Repository       : https://git.spboucher.ai/maclustr-sms11 * Project Website  : https://sms.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 */4142import postgres from "postgres"43import { readdirSync, readFileSync } from "node:fs"44import { join } from "node:path"45import { config } from "./config.ts"4647export type Sql = postgres.Sql<{}>48export type Tx = postgres.TransactionSql<{}> | Sql49export let sql: Sql5051export function connect(url = config.databaseUrl) {52  sql = postgres(url, { max: 12, idle_timeout: 30, onnotice: () => {}, types: { bigint: postgres.BigInt } })53  return sql54}5556/** Migrations versionnées : chaque fichier NNN_nom.sql est appliqué une fois, dans une transaction. */57export async function migrate(dir = config.migrationsDir) {58  await sql`create table if not exists schema_migrations (version text primary key, applied_at timestamptz not null default now())`59  const done = new Set((await sql`select version from schema_migrations`).map(r => r.version as string))60  const files = readdirSync(dir).filter(f => /^\d+_.+\.sql$/.test(f)).sort()61  const applied: string[] = []62  for (const f of files) {63    if (done.has(f)) continue64    const body = readFileSync(join(dir, f), "utf8")65    await sql.begin(async tx => {66      await tx.unsafe(body)67      await tx`insert into schema_migrations(version) values (${f})`68    })69    applied.push(f)70  }71  return applied72}7374const settingsCache = new Map<string, { v: unknown; at: number }>()75export async function getSetting<T>(key: string, fallback: T): Promise<T> {76  const c = settingsCache.get(key)77  if (c && Date.now() - c.at < 2000) return c.v as T78  const [r] = await sql`select value from system_settings where key = ${key}`79  const v = r ? (r.value as T) : fallback80  settingsCache.set(key, { v, at: Date.now() })81  return v82}83export async function setSetting(key: string, value: unknown) {84  await sql`insert into system_settings(key, value) values (${key}, ${sql.json(value as any)})85            on conflict (key) do update set value = excluded.value, updated_at = now()`86  settingsCache.delete(key)87}8889export async function audit(a: { actorType: string; actorId?: string | null; action: string; targetType?: string; targetId?: string | null; detail?: Record<string, unknown>; ip?: string | null }, tx: Tx = sql) {90  await tx`insert into audit_logs(actor_type, actor_id, action, target_type, target_id, detail, ip)91           values (${a.actorType}, ${a.actorId ?? null}, ${a.action}, ${a.targetType ?? null}, ${a.targetId ?? null}, ${tx.json((a.detail ?? {}) as any)}, ${a.ip ?? null})`92}93
Files main
Menu

Theme