Module

x/kysely_postgrs_js_dialect/deps.ts>Transaction#transaction

Kysely dialect for PostgreSQL using the Postgres.js client.
Latest
method Transaction.prototype.transaction
import { Transaction } from "https://dotland.deno.dev/x/kysely_postgrs_js_dialect@v0.27.4/deps.ts";

Creates a {@link TransactionBuilder} that can be used to run queries inside a transaction.

The returned {@link TransactionBuilder} can be used to configure the transaction. The {@link TransactionBuilder.execute} method can then be called to run the transaction. {@link TransactionBuilder.execute} takes a function that is run inside the transaction. If the function throws, the transaction is rolled back. Otherwise the transaction is committed.

The callback function passed to the {@link TransactionBuilder.execute | execute} method gets the transaction object as its only argument. The transaction is of type Transaction which inherits Kysely. Any query started through the transaction object is executed inside the transaction.

Examples

This example inserts two rows in a transaction. If an error is thrown inside the callback passed to the execute method, the transaction is rolled back. Otherwise it's committed.

const catto = await db.transaction().execute(async (trx) => {
  const jennifer = await trx.insertInto('person')
    .values({
      first_name: 'Jennifer',
      last_name: 'Aniston',
      age: 40,
    })
    .returning('id')
    .executeTakeFirstOrThrow()

  return await trx.insertInto('pet')
    .values({
      owner_id: jennifer.id,
      name: 'Catto',
      species: 'cat',
      is_favorite: false,
    })
    .returningAll()
    .executeTakeFirst()
})

Setting the isolation level:

await db
  .transaction()
  .setIsolationLevel('serializable')
  .execute(async (trx) => {
    await doStuff(trx)
  })

Returns

TransactionBuilder<DB>