A database transaction refers to a sequence of read/write operations that are guaranteed to either succeed or fail as a whole. This section describes the ways in which the Prisma Client API supports transactions.

Nested writes

A nested write lets you perform a single Prisma Client API call with multiple operations that touch multiple related records. For example, creating a user together with a post or updating an order together with an invoice. Prisma Client ensures that all operations succeed or fail as a whole.

The following example demonstrates a nested write with create:

// Create a new user with two posts in a
// single transaction
const newUser: User = await prisma.user.create({
data: {
email: 'alice@prisma.io',
posts: {
create: [
{ title: 'Join the Prisma Slack on https://slack.prisma.io' },
{ title: 'Follow @prisma on Twitter' },
],
},
},
})

The following example demonstrates a nested write with update:

// Change the author of a post in a single transaction
const updatedPost: Post = await prisma.post.update({
where: { id: 42 },
data: {
author: {
connect: { email: 'alice@prisma.io' },
},
},
})

Refer to the 📖 transactions guide for more examples.

Bulk operations

The following bulk operations run as transactions:

  • deleteMany
  • updateMany

Refer to the 📖 transactions guide for more examples.

The transaction API

The following example will execute multiple operations within a transaction:

const write1 = prisma.user.create()
const write2 = prisma.post.create()
const write3 = prisma.profile.create()
const [result1, result2, result3] = await prisma.$transaction([write1, write2, write3])

Note: In 2.10.0 and later, you can use .$executeRaw() and .$queryRaw() inside a transaction.

Instead of immediately awaiting the result of each operation when it's performed, the operation itself is stored in a variable first which later is submitted to the database via a method called transaction. Prisma Client will ensure that either all three create-operations or none of them succeed.

Refer to the 📖 transactions guide for more examples.

Join the conversation on GitHub

If you'd like to see transactions supported in the future, please join the discussion on GitHub.

Edit this page on GitHub