Aller au contenu

Postgres Utilities

Shared utilities for PostgreSQL connection management, transactions, and reliability.

Transaction helpers

safePgTransaction (TypeORM path)

Wraps DataSource.transaction() with automatic commit/rollback based on callback outcome.

Location: safe-pg-transaction.postgres.ts

Behavior: - Callback returns a value → commit - Callback returns { ok: false } (Result error) → rollback (throws Transaction aborted) - Callback throws → rollback + rethrow if it's a query/pool error - isDryRun: true → intentional rollback without error logging

Rollback hooks: setOnRollback(fn) registers async cleanup functions that run after a rollback via Promise.allSettled. Each success/failure is logged individually.

Nesting: Pass { parent } to reuse an existing EntityManager without opening a new transaction.

Logging: A default Logger('safePgTransaction') is always available, even when options.logger is omitted. Rollback callbacks are logged. Error in transaction is reserved for infra failures after the callback succeeded (e.g. connection drop during COMMIT). Callback throws and controlled rollbacks (Err / dry-run) are not logged as TX errors — the caller owns that failure.

const result = await safePgTransaction(async (transac, setOnRollback) => {
  setOnRollback(async () => { /* compensate external side-effect */ })
  const row = await transac.query(/* ... */)
  if (!row) return Err('not-found' as const)
  return Ok(row)
})

When to use: Legacy investor flows still on TypeORM (Customer.save, pessimistic locks, freeze/unfreeze). ~70 call sites; setOnRollback is used in primary-purchase, checkout, gift-card, KYC sync, etc.

Keep rollback/commit behavior in sync with ky_safePgTransaction (../kysely/ky-safe-pg-transaction.ts) — update both when changing either.

ky_safePgTransaction (Kysely path)

Wraps db.transaction().execute() with the same Result-based commit/rollback pattern as safePgTransaction.

Location: ../kysely/ky-safe-pg-transaction.ts

Parity with TypeORM version: - setOnRollback + Promise.allSettled on rollback - Default Logger('ky_safePgTransaction') + infra error logging (skipped on callback throws, Err, dry-run) - Controlled rollback (Err / dry-run) vs infra failure (rethrow) - parent nesting via KyTransactionContext (transac + setOnRollback)

When to use: Transactions 100 % Kysely (espace-fi modules, investor repos once outer tx is migrated). Admin/scripts flows use this path; KYC flows stay on safePgTransaction until Customer is migrated.

Keep rollback/commit behavior in sync with safePgTransaction (safe-pg-transaction.postgres.ts) — update both when changing either.

Investor repos (TypeORM → Kysely migration)

While some callers still run inside safePgTransaction (e.g. KYC + Customer.save), a migrated table can expose two explicit repo methods — the service picks the one matching its parent tx:

Parent tx Repo method Write path
ky_safePgTransaction insertOneWithKysely({ trx, row }) trx.insertInto(…) + ky_parseOneRow
safePgTransaction insertOneWithTypeorm({ transac, row }) transac.query(INSERT … RETURNING) + ky_parseOneRow

Same Zod schemas on both methods. Add the TypeORM method only when grep shows a caller still in safePgTransaction. Reads use getKysely() alone.

Pool error handling

attachPgPoolErrorHandler

Registers pool.on('error') and client.on('error') listeners to prevent unhandled exceptions when idle connections die (e.g. Neon closing connections, network issues).

Location: attach-pg-pool-error-handler.ts

Behavior: - pool.on('error'): Logs idle client errors — the pool removes the dead client and creates a new one on next acquire - pool.on('connect') → client.on('error'): Logs checked-out client errors - Uses a WeakSet for idempotent attachment — safe to call multiple times on the same pool

Where attached (three pools):

Pool Attached in Label
TypeORM master typeorm-config.service.ts → getInitializedDataSource() typeorm-master
Kysely __new/lib/kysely/database.ts kysely-master
Better Auth lib/better-auth/better-auth.factory.ts better-auth

TypeORM attachment happens inside getInitializedDataSource(), which is called by dataSourceFactory during Nest bootstrap. This ensures the pool is protected before onModuleInit runs, covering the startup window.

Other utilities

File Purpose
postgres.get-connection-string.ts Builds PG connection string from env config
prepareParameterizedQuery.ts Builds parameterized SQL with explicit cast declarations (cast: 'jsonb', cast: 'uuid')
pg-return.ts Helpers for query return types

Troubleshooting

Silent process crashes: If the API exits without clear error logs, check whether a new pool was introduced without calling attachPgPoolErrorHandler. Idle connection drops on an unprotected pool emit unhandled error events that crash Node.

Transaction rollback not visible: Ensure the service passes a Logger to safePgTransaction / ky_safePgTransaction, or rely on the default logger. Look for Error in transaction and onRollback call function succeeded/failed log entries.

Pool timeout: Both transaction helpers map pg timeout errors to isQueryError = true and rethrow, making them distinguishable from business-logic rollbacks.