← Retour au cours: SQL and databases from scratch

Transactions and ACID

Vidéo bientôt disponible

Imagine a bank transfer: subtract 100 euros from account A and add them to account B. They are two UPDATE statements. What happens if the server shuts down right between them? The money would disappear. A transaction groups several statements into an indivisible unit: either all of them run, or none does. It is the guarantee that lets you trust a database to store money, orders or medical records.

ACID in four ideas

  • Atomicity: all or nothing. If something fails, everything done up to that point is undone.
  • Consistency: the transaction takes the database from one valid state to another valid one; constraints (CHECK, FOREIGN KEY) always hold.
  • Isolation: simultaneous transactions do not disturb each other; each sees the data as if it were alone, according to the chosen level.
  • Durability: once confirmed with COMMIT, the transaction survives even if the server crashes right afterwards.

BEGIN, COMMIT and ROLLBACK

By default each loose statement is its own transaction that confirms itself (autocommit). To group several, you open with BEGIN (or START TRANSACTION), run your statements and finish with COMMIT to confirm or ROLLBACK to undo. In PostgreSQL, if a statement fails inside the transaction, the whole transaction is aborted and you must ROLLBACK before continuing: you will see the message current transaction is aborted. Let us try it with an accounts table, with a constraint that prevents negative balances.

sql
CREATE TABLE accounts (
  account_id INTEGER PRIMARY KEY,
  owner      TEXT NOT NULL,
  balance    NUMERIC(12,2) NOT NULL CHECK (balance >= 0)
);

INSERT INTO accounts VALUES (1, 'Ana', 500.00), (2, 'Bruno', 100.00);

-- A correct transfer: both updates or none
BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE account_id = 1;
UPDATE accounts SET balance = balance + 100 WHERE account_id = 2;
COMMIT;

SELECT * FROM accounts ORDER BY account_id;   -- Ana 400, Bruno 200
sql
-- A transfer that fails halfway: Ana only has 400
BEGIN;
UPDATE accounts SET balance = balance + 900 WHERE account_id = 2;   -- ok
UPDATE accounts SET balance = balance - 900 WHERE account_id = 1;   -- ERROR: violates check constraint
ROLLBACK;   -- undoes the first update too

SELECT * FROM accounts ORDER BY account_id;   -- still Ana 400, Bruno 200

-- SAVEPOINT: undo only a part of the transaction
BEGIN;
UPDATE accounts SET balance = balance + 10 WHERE account_id = 2;
SAVEPOINT before_risky_step;
UPDATE accounts SET balance = 0 WHERE account_id = 2;
ROLLBACK TO SAVEPOINT before_risky_step;   -- keeps the +10, discards the zeroing
ROLLBACK;   -- we discard the demo too, so balances stay Ana 400 / Bruno 200

The same applies to the shop. Placing an order involves several steps: inserting the order, inserting its lines and reducing the stock. If the third fails, we do not want a half-made order. Wrapping the three steps in a transaction guarantees that the database never shows an incoherent intermediate state. Remember that a transaction must be short: while open it can lock rows that others need, so never leave it open waiting for the user to answer something.

sql
BEGIN;

INSERT INTO orders (order_id, customer_id, order_date, status)
VALUES (13, 6, '2024-08-01', 'pending');

INSERT INTO order_items (item_id, order_id, product_id, quantity, unit_price)
VALUES (23, 13, 2, 3, 19.90);

UPDATE products SET stock = stock - 3 WHERE product_id = 2;

SELECT product_id, stock FROM products WHERE product_id = 2;   -- 117

ROLLBACK;   -- we use ROLLBACK to leave the practice shop unchanged; in production it would be COMMIT

Isolation and concurrency

When two sessions work at the same time, problems can appear: a non-repeatable read (rereading a row and seeing another value because someone changed and committed it), a phantom read (rerunning a query and seeing new rows) or a dirty read (seeing uncommitted data; PostgreSQL never allows it). The isolation level decides which are tolerated. PostgreSQL uses READ COMMITTED by default; REPEATABLE READ gives a stable snapshot during the transaction and SERIALIZABLE behaves as if the transactions ran one after another, at the cost of possible serialization errors that the application must retry. To prevent two customers from reserving the last item at the same time, the row is locked with SELECT ... FOR UPDATE. If two transactions wait for each other, a deadlock occurs: PostgreSQL detects it and aborts one of them.

✎ Mes notes

Enregistré seulement dans ce navigateur. Connectez-vous pour le garder dans votre compte.0/5000 caractères

← PrécédenteSuivante →