Transactions and database reset
What you need to know
A transaction groups related database writes so a partial failure does not leave half of an intended change committed. A resettable fixture makes it possible to test both success and failure.
By the end, you can: group dependent changes; verify rollback and isolated reset.
Reserve stock and write a record together
// partial SQLite helper: schema from lab-fixtures/mutations-v7/db/schema.sqlexport function reserve(db,owner,book,key) { db.exec('BEGIN'); try { const result=db.prepare('UPDATE books SET quantity=quantity-1 WHERE id=? AND owner_id=? AND quantity>0').run(book,owner); if(result.changes!==1) throw new Error('Unavailable'); db.prepare('INSERT INTO reservations(id,book_id,owner_id) VALUES (?,?,?)').run(key,book,owner); db.exec('COMMIT'); } catch(error) {db.exec('ROLLBACK');throw error;}}Expected behavior: With two copies available, a new reservation leaves one copy; a repeated key fails and rolls back the decrement. This is duplicate rejection, not a complete idempotent retry protocol.
How it works
Suppose reserving a copy must decrement available quantity and create a reservation row. An atomic conditional UPDATE prevents quantity from dropping below zero; if no row changed, stop. The second insert may fail because the reservation key already exists. Roll back the first update in that case. PostgreSQL transactions use the same checked-out client for BEGIN, each statement and COMMIT or ROLLBACK; release it afterwards. A network failure during commit can leave the outcome uncertain, so reconcile using the operation’s idempotency key instead of blindly repeating it. A later successful cleanup command is not proof that the original commit failed. Preserve the original failure, discard a suspect connection according to the driver contract, and reconcile through a new verified connection. SQLite has its own locking and isolation characteristics; a passing in-memory test is not a concurrency test for PostgreSQL. Build fresh databases for each scenario and close them in finally. Revalidation or external side effects should happen only after a confirmed commit; a cache error after commit does not undo the database write.
Keep PostgreSQL transaction statements on one client
// partial server-only driver helper; reviewed pg requiredimport type {Pool} from 'pg';export async function setTitle(pool:Pool,id:string,owner:string,title:string) { const client=await pool.connect(); let broken=false; let committing=false; try { await client.query('BEGIN'); const r=await client.query('UPDATE books SET title=$1 WHERE id=$2 AND owner_id=$3',[title,id,owner]); if(r.rowCount!==1) throw new Error('Unavailable'); committing=true; await client.query('COMMIT'); } catch(e) { if(committing) broken=true; // conservative: reconcile ambiguous commit separately try {await client.query('ROLLBACK');} catch {broken=true;} throw e; } finally {client.release(broken);}}Expected behavior: An owned matching book is updated; a nonmatching owner or missing row triggers rollback. This example assumes a previously verified principal and validated title, and is not an endpoint.
Common mistake
Do not run BEGIN and COMMIT through independent pool.query calls. Do not assert rollback occurred if a connection failed before a commit result was known. Verify persisted state and distinguish retry from a new operation.
Practice and verification
Run the SQLite fixture tests. Compare quantities and reservation counts before and after duplicate rejection, wrong owner and exhausted stock. Design a separate PostgreSQL two-client test and keep it NOT RUN until a real service is authorized.
Scope: App Router, proposed Next.js 16.x, React 19 family, Cache Components disabled. Framework snippets are static or explicitly partial; actual browser, auth and generated-route checks are pending. SQLite exercises run separately in the authoring environment, not the ByteMind evaluator.
Further reading: Pg Tx · Pg Driver Tx · Sqlite Fk