Use node:sqlite with transactions
Wrap related writes in BEGIN, COMMIT and ROLLBACK with the built-in node:sqlite module, so a failed transfer leaves no half-applied change. Node.js 24.
Moving money between two rows must either change both or neither. node:sqlite has no transaction helper, so you open one with plain SQL and roll back on any error.
import { DatabaseSync } from 'node:sqlite';
const db = new DatabaseSync(':memory:');
db.exec(`
CREATE TABLE accounts (
id INTEGER PRIMARY KEY,
balance INTEGER NOT NULL CHECK (balance >= 0)
);
INSERT INTO accounts (id, balance) VALUES (1, 100), (2, 0);
`);
function transfer(from, to, amount) {
db.exec('BEGIN');
try {
db.prepare('UPDATE accounts SET balance = balance - ? WHERE id = ?').run(amount, from);
db.prepare('UPDATE accounts SET balance = balance + ? WHERE id = ?').run(amount, to);
db.exec('COMMIT');
} catch (error) {
db.exec('ROLLBACK');
throw error;
}
}
transfer(1, 2, 60);
try {
transfer(1, 2, 60);
} catch (error) {
console.log(error.message);
}
console.log(db.prepare('SELECT id, balance FROM accounts ORDER BY id').all());CHECK constraint failed: balance >= 0
[
[Object: null prototype] { id: 1, balance: 40 },
[Object: null prototype] { id: 2, balance: 60 }
]The first transfer commits. The second one tries to take 60 from a balance of 40, the CHECK constraint throws inside the first UPDATE, and ROLLBACK discards the work. Nothing is half-applied. Rows come back as objects with a null prototype, which is why the printer labels them. DatabaseSync is synchronous by design, and it may print an ExperimentalWarning on Node.js 24.
Do not reuse this wrapper for work that awaits between statements. The connection is one shared transaction, so another request could write in the middle of yours. Keep the BEGIN to COMMIT span fully synchronous.