Skip to content

withClient

withClient<T>(pool: pg.Pool, fn: (client: pg.PoolClient) => Promise<T>): Promise<T>

Check out one connection from the pool, run the callback, then release it — even if the callback throws. Returns whatever the callback returns.

import connect, { withClient } from '@smplcty/db';
const pool = connect();
const rows = await withClient(pool, async (client) => {
const { rows } = await client.query('select 1 as n');
return rows;
});

Every query inside fn runs on the same physical connection, so session state (SET LOCAL, set_config, custom GUCs) and transaction state apply consistently across the body. Two separate pool.query(...) calls may land on different connections and lose that relationship.