method

TransactionSQL.begin

begin<T>(
): Promise<ContextCallbackResult<T>>;

Begins a new transaction.

Reserves a connection for the transaction and passes a scoped sql instance to the callback. sql.begin resolves with the callback's return value. BEGIN is sent automatically, and if anything fails, ROLLBACK is sent so the connection can be released and execution can continue.

const [user, account] = await sql.begin(async sql => {
  const [user] = await sql`
    insert into users (
      name
    ) values (
      'Murray'
    )
    returning *
  `
  const [account] = await sql`
    insert into accounts (
      user_id
    ) values (
      ${ user.user_id }
    )
    returning *
  `
  return [user, account]
})
begin<T>(
options: string,
): Promise<ContextCallbackResult<T>>;

Begins a new transaction with options.

Reserves a connection for the transaction and passes a scoped sql instance to the callback. sql.begin resolves with the callback's return value. BEGIN is sent with the given options, and if anything fails, ROLLBACK is sent so the connection can be released and execution can continue.

const [user, account] = await sql.begin("read write", async sql => {
  const [user] = await sql`
    insert into users (
      name
    ) values (
      'Murray'
    )
    returning *
  `
  const [account] = await sql`
    insert into accounts (
      user_id
    ) values (
      ${ user.user_id }
    )
    returning *
  `
  return [user, account]
})

Referenced types

type TransactionContextCallback<T> = ContextCallback<T, TransactionSQL>

Callback function type for transaction contexts

type ContextCallbackResult<T> = T extends PromiseLike<any>[] ? AwaitPromisesArray<T> : Awaited<T>