withTransaction() function

Run fn inside a transaction on one connection.

Signature:

export declare function withTransaction<T>(pool: SqlPool, fn: (tx: SqlExecutor) => Promise<T>): Promise<T>;

Parameters

Parameter

Type

Description

pool

SqlPool

The pool to take a connection from.

fn

(tx: SqlExecutor) => Promise<T>

The work to run inside the transaction.

Returns:

Promise<T>

Whatever fn returns.

Remarks

A transaction has to be one connection: issuing BEGIN on a pool and the statements after it on whatever connection the pool hands out next is the classic way to commit nothing and report success. The connection is released whatever happens, and a failure rolls back before rethrowing.

Example

await withTransaction(pool, async tx => {
    await tx.query('CREATE TABLE ...');
});

Read this page as plain markdown — no HTML, no navigation. For pasting into an LLM, or for an agent to fetch.