Data consistency

SQLite transaction and conditional update

A transaction groups changes so they commit together or are rolled back together. For inventory, decrementing stock and recording an order must agree. Optimistic concurrency detects an intervening update by requiring the previously read version to match at write time. Do not treat a read followed by a separate unchecked write as safe concurrency control. Do not catch a constraint error and commit partial work by accident. Local atomicity does not extend to an unrelated service. Source: https://nodejs.org/download/release/v22.16.0/docs/api/sqlite.html Local examples do not establish third-party integration support.

Formal Syntax & Structure

nodejs syntaxnodejs
BEGIN; UPDATE ... WHERE ...; COMMIT; -- or ROLLBACK on failure

Working Example

Example Snippetnodejs
import {DatabaseSync} from 'node:sqlite';const db=new DatabaseSync(':memory:');try{ db.exec("CREATE TABLE stock(n INTEGER CHECK(n>=0)); INSERT INTO stock VALUES(5); CREATE TABLE orders(id TEXT PRIMARY KEY NOT NULL); INSERT INTO orders VALUES('o1')"); db.exec('BEGIN');try{  db.exec('UPDATE stock SET n=n-2');  db.prepare('INSERT INTO orders VALUES(?)').run('o1');  db.exec('COMMIT'); }catch(e){db.exec('ROLLBACK');console.log('rolled back');} console.log(db.prepare('SELECT n FROM stock').get().n); console.log(db.prepare('SELECT count(*) AS n FROM orders').get().n);}finally{db.close();}
Node.js Reference