Partial order insertion lacks atomicity
Your task
Review this Node.js order-placement handler.
async function placeOrder(pool, userId, items, total) {
const { rows } = await pool.query(
'INSERT INTO orders (user_id, total) VALUES ($1, $2) RETURNING id',
[userId, total]
);
const orderId = rows[0].id;
for (const it of items) {
await pool.query(
'INSERT INTO order_items (order_id, sku, qty) VALUES ($1, $2, $3)',
[orderId, it.sku, it.qty]
);
}
await pool.query(
'UPDATE inventory SET stock = stock - $1 WHERE sku = $2',
[items[0].qty, items[0].sku]
);
return orderId;
}It covers
- Atomicity
- Partial write
- Multi step