SQL drivers

Transactions and rollback

A transaction groups changes into a unit that can commit together or be rolled back. Use it when updating related records must preserve an invariant, such as stock decreasing only when a reservation is recorded. Begin, run related statements on the same connection, then commit. If a statement fails, roll back before releasing the connection. In the SQLite fixture a CHECK constraint rejects negative stock; a duplicate reservation also fails. The failure rolls back the earlier stock change. For PostgreSQL use a checked-out pg client for the whole transaction, not repeated pool.query calls. A network failure during commit can leave the outcome uncertain; reconcile with a durable request identifier before retrying. This lab does not test concurrent transactions or PostgreSQL isolation. Do not split transaction statements across pooled connections. Do not retry an uncertain commit blindly or claim rollback reverses external effects like email. Evidence: Actual local SQLite 3.49.1 via experimental node:sqlite. Source: https://node-postgres.com/features/transactions

Formal Syntax & Structure

nodejs syntaxnodejs
See example for the scoped contract

Working Example

Example Snippetnodejs
import {DatabaseSync} from 'node:sqlite';const db=new DatabaseSync(':memory:');try { db.exec('CREATE TABLE stock(id INTEGER PRIMARY KEY, qty INTEGER CHECK(qty>=0)); CREATE TABLE reservation(id INTEGER PRIMARY KEY); INSERT INTO stock VALUES(1,5); INSERT INTO reservation VALUES(1)'); function reserve(id){db.exec('BEGIN');try{db.prepare('UPDATE stock SET qty=qty-1 WHERE id=1').run();db.prepare('INSERT INTO reservation VALUES(?)').run(id);db.exec('COMMIT');}catch(error){db.exec('ROLLBACK');throw error;}} try{reserve(1);}catch{console.log('rolled back');} console.log(db.prepare('SELECT qty FROM stock').get().qty); reserve(2); console.log(db.prepare('SELECT qty FROM stock').get().qty); console.log(db.prepare('SELECT count(*) AS n FROM reservation').get().n);}finally{db.close();}
Node.js Reference