Transactions — ensure multiple operations succeed or fail together.
PostgreSQL with pg:
1async function transferMoney(fromId, toId, amount) {2 const client = await pool.connect();3 try {4 await client.query("BEGIN");56 await client.query(7 "UPDATE accounts SET balance = balance - $1 WHERE id = $2",8 [amount, fromId]9 );1011 await client.query(12 "UPDATE accounts SET balance = balance + $1 WHERE id = $2",13 [amount, toId]14 );1516 await client.query("COMMIT");17 } catch (err) {18 await client.query("ROLLBACK");19 throw err;20 } finally {21 client.release();22 }23}
Using Knex.js:
1await knex.transaction(async (trx) => {2 await trx("accounts").where("id", fromId).decrement("balance", amount);3 await trx("accounts").where("id", toId).increment("balance", amount);4});
Key points: