Sobes.tech
Middle+

What are transactions and the properties of ACID?

sobes.tech AI

Answer from AI

A transaction is a sequence of operations on a database that is executed as a single unit. If one of the operations fails, all changes are rolled back.

The properties of ACID ensure the reliability of transactions:

  • Atomicity: The transaction either completes entirely or not at all.
  • Consistency: After the transaction, the database remains in a correct state.
  • Isolation: Parallel transactions do not affect each other; the results of one are not visible to others until completion.
  • Durability: Once a transaction is committed, its changes are saved even in case of failures.

Example in Node.js using transactions (e.g., with the pg library for PostgreSQL):

const { Client } = require('pg');
const client = new Client();

async function runTransaction() {
  await client.connect();
  try {
    await client.query('BEGIN');
    await client.query('INSERT INTO accounts(user_id, balance) VALUES($1, $2)', [1, 100]);
    await client.query('UPDATE accounts SET balance = balance - 50 WHERE user_id = $1', [2]);
    await client.query('COMMIT');
  } catch (e) {
    await client.query('ROLLBACK');
    throw e;
  } finally {
    await client.end();
  }
}