
Join the Conversation!
Subscribing gives you access to the comments so you can share your ideas, ask questions, and connect with others.
In this lesson, we will learn how to use transactions to ensure data integrity. Transactions let us group multiple operations together and ensure that they all succeed or fail together.
For example, if we might develop a system where changing the price or some other data in a product removes the reviews for that product. Or at least a toggle to allow that option on change in the user interface. We may need this when we've changed a product so much that the reviews are no longer relevant.
So we have two operations that need to happen together. We need to update the product and delete the reviews. If either of these operations fails, we want to roll back the other operation. For example- if the product update fails, we don't want to delete the reviews. If the review deletion fails, we don't want to update the product.
We can use a transaction to ensure that both operations succeed or fail together. If either operation fails, the transaction will be rolled back and the database will be left in the state it was in before the transaction started.
Let's see how we this works with our javascript code.
Let's first define the :
//
const updatedProduct = await prisma.$transaction(async (prisma) => {});
Inside the transaction, we can perform multiple operations.
Let's write two different simple operations. One to update the product and another to delete the reviews.
//
const updatedProduct = await prisma.$transaction(async (prisma) => {
const product = await prisma.product.update({
where: { id: 1 },
data: { price: 200 },
});
const deletedReviews = await prisma.review.deleteMany({
where: { productId: 1 },
});
return product;
});
If either of these operations fails, the transaction will be rolled back and the database will be left in the state it was in before the transaction started.
This is useful when we need to 'batch' operations together and ensure that they all succeed or fail together.
We can trigger a rollback by throwing an error inside the transaction.
Let's imagine our products had a stock field to keep track of how many items are in stock. We want to ensure that the stock is never negative for a purchase to go through.
//
const updatedProduct = await prisma.$transaction(async (prisma) => {
const product = await prisma.product.update({
where: { id: 1 },
data: { stock: { decrement: 1 } },
});
if (product.stock < 0) {
// throwing this error
// will cause the transaction to rollback
// and revert the stock decrement
throw new Error("Not enough stock, cancelling purchase");
}
// update the user's purchases
// to confirm a purchase
const purchases = await prisma.purchase.create({
data: {
userId: 1,
productId: 1,
},
});
return product;
});
"Please login to view comments"
Subscribing gives you access to the comments so you can share your ideas, ask questions, and connect with others.