tSQL

Transactions

Learn how to use transactions in tSQL.

Basic usage

const result = await db.transaction().execute(async (trx) => {
  // First, create our superhero
  const batman = await trx
    .insertInto("person")
    .values({
      first_name: "Bruce",
      last_name: "Wayne",
      age: 35,
    })
    .returning("id")
    .executeTakeFirstOrThrow();

  // Then add his trusty sidekick
  const robin = await trx
    .insertInto("pet")
    .values({
      owner_id: batman.id,
      name: "Robin",
      species: "human",
      is_favorite: true, // Don't tell the other sidekicks
    })
    .returningAll()
    .executeTakeFirst();

  // Finally add his noble steed
  const batmobile = await trx
    .insertInto("pet")
    .values({
      owner_id: batman.id,
      name: "Batmobile",
      species: "car",
      is_favorite: true, // He loves it equally
    })
    .returningAll()
    .executeTakeFirst();

  return { robin, batmobile };
});

On this page