DEV Community

Tharunya K R
Tharunya K R

Posted on

Atomicity

Atomicity means it either happen completely or it does not happen anything
If there is no error it give the correct result
If there is an error it rollback(cancel) return to the initial state
Testing error will happen to check the atomicity

Example :
Create an table

CREATE TABLE accounts (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL,
balance INT NOT NULL CHECK (balance >= 0)
);
Sample Data
INSERT INTO accounts (name, balance)
VALUES
('Alice', 1000),
('Bob', 500);

Correct Transaction :

BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE name = 'Alice';
UPDATE accounts SET balance = balance + 100 WHERE name = 'Bob';
COMMIT;

Result :
Alice : 900
Bob : 600

Testing Atomicity :

BEGIN; UPDATE accounts SET balance = balance - 100 WHERE name = 'Alice';
UPDATE accounts SET balancee = balance + 100 WHERE name = 'Bob';
COMMIT;

Here error happens ibstead of balance it shows balancee
So Rollback happens it cancel every transaction and it return the initial state.

Top comments (0)