Lesson 35 / 35
Mixed Self-Check
Test yourself across modelling, querying, migrations, transactions and security by spotting bugs in short ORM snippets.
By Rahul Agarwal · 15 years in web development
How to use this self-check
Real interviews and code reviews rarely ask 'what does include do?'. They hand you a snippet and ask what is wrong. Practise that skill here. For each snippet, ask four questions in order. How many queries does this run? Look for awaits inside loops and relations accessed without being loaded. Is every value parameterised? Look for template strings or concatenation feeding SQL text. Are related writes atomic? If two writes must both succeed, they belong in one transaction, and every query inside must use the transaction client. Does the schema change have a migration? A model edit without a migration is a runtime error waiting to happen. If you can answer all four confidently for the snippets in this course, you understand ORMs well enough to use any of the three in a real project and explain your choices in an interview.
Spot the bugs
This handler has three problems from earlier sections. Find them before reading the quiz below.
app.post('/orders', async (req, res) => {
await prisma.$transaction(async (tx) => {
const order = await tx.order.create({ data: req.body });
for (const item of req.body.items) {
await prisma.stock.update({
where: { productId: item.productId },
data: { quantity: { decrement: item.qty } },
});
}
});
res.sendStatus(201);
});The answers
Line 3 passes req.body straight into create, which is mass assignment. Line 5 uses prisma instead of tx, so stock updates run outside the transaction and are not rolled back if a later step fails. The loop also runs one update per item; for large orders, consider a single set-based update or at least accept the cost knowingly.
Quick check: In the snippet above, an exception is thrown after two of five stock updates. Which statement is correct?
- Everything is rolled back, including the two stock updates
- Nothing is rolled back, including the order
- The order insert is rolled back, but the two stock updates stay committed because they used prisma instead of tx
- Prisma retries the remaining three updates automatically
Answer
The order insert is rolled back, but the two stock updates stay committed because they used prisma instead of tx — Only queries made through tx belong to the transaction. The order (created with tx) is rolled back; the stock updates through the global client already committed.