Hoppa till innehåll

Kysely Transactions

Det här innehållet är inte tillgängligt på ditt språk än.

Short and simple examples of how to use transactions.

Simple transaction

Schema

import { Generated } from 'kysely'
declare global {
interface DB {
person: PersonTable
pet: PetTable
}
interface PersonTable {
id: Generated<string>
first_name: string
last_name: string | null
created_at: Generated<Date>
age: number
}
interface PetTable {
id: Generated<string>
name: string
owner_id: string
species: 'cat' | 'dog'
is_favorite: boolean
}
}

Querying

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()
})

Result

/* execute() has been called multiple times. */
---- #1 ----
INSERT INTO
"person" ("first_name", "last_name", "age")
VALUES
($1, $2, $3)
RETURNING
"id"
-- Parameters
-- [1] Jennifer
-- [2] Aniston
-- [3] 40
---- #2 ----
INSERT INTO
"pet" ("name", "species", "is_favorite")
VALUES
($1, $2, $3)
RETURNING
*
-- Parameters
-- [1] Catto
-- [2] cat
-- [3] false