techtools

db.ts

TypeScript · 144 рядків

1// Тонка оболонка PostgreSQL (з proto/flow, R-12.15): :name-параметри, транзакція з тайм-аутами й повтором при 40P01/40001.
2//
3//   • запити з іменованими параметрами :name (::cast не чіпається) — SQL читається як є;
4//   • транзакція з тайм-аутами блокування й оператора, повтор при взаємному блокуванні / серіалізації;
5//   • dryRun — та сама транзакція з ROLLBACK замість COMMIT (попередній перегляд на сторінці);
6//   • trace — час і текст кожного оператора (лише коли сторінка просить ?trace=1; прогін цього не платить).
7import pg from 'pg';
8
9pg.types.setTypeParser(20, (v) => Number(v));     // bigint → number (id < 2^53)
10pg.types.setTypeParser(1082, (v) => v);           // date — рядком
11pg.types.setTypeParser(1114, (v) => v);           // timestamp — рядком
12pg.types.setTypeParser(1184, (v) => v);           // timestamptz — рядком
13
14export type Row = Record<string, any>;
15export type Params = Record<string, unknown>;
16export type Isolation = 'read committed' | 'repeatable read' | 'serializable';
17export interface TxOptions { isolation?: Isolation; readOnly?: boolean; dryRun?: boolean }
18export interface Statement { sql: string; ms: number; rows: number }
19
20/** Доступ до бази для операції. */
21export interface Sql {
22  query<T = Row>(text: string, params?: Params): Promise<T[]>;
23  one<T = Row>(text: string, params?: Params): Promise<T>;
24  /** Окрема транзакція; лише поза транзакцією (операції з tx: 'none', напр. консолідація). */
25  transaction<T>(fn: (sql: Sql) => Promise<T>, options?: TxOptions): Promise<T>;
26}
27
28// ---------- :name → $n ----------
29
30const compiled = new Map<string, { text: string; names: string[] }>();
31
32export function compile(text: string): { text: string; names: string[] } {
33  let c = compiled.get(text);
34  if (!c) {
35    const names: string[] = [];
36    const out = text.replace(/(?<![:\w]):([a-zA-Z_]\w*)/g, (_, name: string) => {
37      let i = names.indexOf(name);
38      if (i < 0) i = names.push(name) - 1;
39      return `$${i + 1}`;
40    });
41    c = { text: out, names };
42    compiled.set(text, c);
43  }
44  return c;
45}
46
47function bind(text: string, params: Params = {}): [string, unknown[]] {
48  const c = compile(text);
49  return [c.text, c.names.map((n) => {
50    if (!(n in params)) throw new Error(`SQL-параметр :${n} не передано`);
51    return params[n] ?? null;
52  })];
53}
54
55// ---------- виконання ----------
56
57class ClientSql implements Sql {
58  private readonly client: pg.Pool | pg.PoolClient;
59  private readonly db: Database;
60  private readonly trace: Statement[] | null;
61  private readonly inTx: boolean;
62
63  constructor(client: pg.Pool | pg.PoolClient, db: Database, trace: Statement[] | null, inTx: boolean) {
64    this.client = client;
65    this.db = db;
66    this.trace = trace;
67    this.inTx = inTx;
68  }
69
70  async query<T = Row>(text: string, params?: Params): Promise<T[]> {
71    const [q, v] = bind(text, params);
72    if (!this.trace) return (await this.client.query(q, v)).rows;
73    const t = performance.now();
74    const r = await this.client.query(q, v);
75    this.trace.push({ sql: text.trim(), ms: performance.now() - t, rows: r.rowCount ?? r.rows.length });
76    return r.rows;
77  }
78
79  async one<T = Row>(text: string, params?: Params): Promise<T> {
80    const rows = await this.query<T>(text, params);
81    if (!rows.length) throw new Error('Запит мав повернути рядок');
82    return rows[0];
83  }
84
85  transaction<T>(fn: (sql: Sql) => Promise<T>, options?: TxOptions): Promise<T> {
86    if (this.inTx) throw new Error('Вкладені транзакції не підтримуються');
87    return this.db.transaction((sql) => fn(sql), options, this.trace);
88  }
89}
90
91const RETRYABLE = new Set(['40P01', '40001']);   // взаємне блокування, серіалізація
92const RETRIES = 5;
93
94export class Database {
95  readonly pool: pg.Pool;
96
97  constructor(pool: pg.Pool) {
98    this.pool = pool;
99  }
100
101  static async connect(url: string, max = 20): Promise<Database> {
102    const pool = new pg.Pool({ connectionString: url, max });
103    await pool.query('SELECT 1');
104    return new Database(pool);
105  }
106
107  /** Без транзакції: кожен запит окремо (читання, обслуговування). */
108  sql(trace: Statement[] | null = null): Sql {
109    return new ClientSql(this.pool, this, trace, false);
110  }
111
112  /**
113   * Транзакція. fn отримує traced (пише в trace) і plain (той самий клієнт, без trace — для знімків стану на сторінку).
114   * fn може виконатися кілька разів (повтор при 40P01/40001), тому весь стан операції має жити всередині fn.
115   */
116  async transaction<T>(fn: (sql: Sql, plain: Sql) => Promise<T>, options: TxOptions = {}, trace: Statement[] | null = null): Promise<T> {
117    const begin = `BEGIN ISOLATION LEVEL ${(options.isolation ?? 'read committed').toUpperCase()}${options.readOnly ? ' READ ONLY' : ''};`
118      + ` SET LOCAL lock_timeout = '5s'; SET LOCAL statement_timeout = '120s'`;
119    for (let attempt = 1; ; attempt++) {
120      const client = await this.pool.connect();
121      try {
122        await client.query(begin);
123        const result = await fn(new ClientSql(client, this, trace, true), new ClientSql(client, this, null, true));
124        await client.query(options.dryRun ? 'ROLLBACK' : 'COMMIT');
125        return result;
126      } catch (e) {
127        await client.query('ROLLBACK').catch(() => {});
128        if (attempt < RETRIES && RETRYABLE.has((e as { code?: string }).code ?? '')) {
129          if (trace) trace.length = 0;
130          await new Promise((r) => setTimeout(r, 5 * 2 ** attempt * (0.5 + Math.random())));
131          continue;
132        }
133        throw e;
134      } finally {
135        client.release();
136      }
137    }
138  }
139
140  async close(): Promise<void> {
141    await this.pool.end();
142  }
143}
144