Good Code
The good version treats the status change and audit event as one unit of work.
Lesson 07
Wrap multi-step writes in a transaction so related changes succeed or fail together.
BEGIN;
UPDATE code_reviews
SET status = 'approved',
approved_at = now()
WHERE id = $1
AND status = 'submitted';
INSERT INTO review_events (review_id, event_type, created_at)
VALUES ($1, 'approved', now());
COMMIT;UPDATE code_reviews
SET status = 'approved',
approved_at = now()
WHERE id = $1;
INSERT INTO review_events (review_id, event_type, created_at)
VALUES ($1, 'approved', now());The good version treats the status change and audit event as one unit of work.
The bad version can approve a review without recording the event if the second statement fails. It also approves without checking the expected starting state.