method
SavepointSQL.transaction
Begins a new transaction. Alias of begin.
Reserves a connection for the transaction and passes a scoped sql instance to the callback. sql.transaction 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.transaction(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]
})options: string,
Begins a new transaction with options. Alias of begin.
Reserves a connection for the transaction and passes a scoped sql instance to the callback. sql.transaction 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.transaction("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>