We use ewallets like gpay and phonepe everyday right and I have always wondered where the money goes when the server is down in the middle of a transaction.And that's where the concept of atomicity comes in.Atomicity means all or nothing.Either all the transactions are completed or everything is rolled back.
Creating a base table
CREATE TABLE accounts (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL,
balance INT NOT NULL CHECK (balance >= 0),
last_updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
INSERT INTO accounts (name, balance) VALUES ('Christina', 1000), ('Sharon', 500);
Correct Transaction
BEGIN;
UPDATE accounts SET balance = balance - 200 WHERE name = 'Christina';
UPDATE accounts SET balance = balance + 200 WHERE name = 'Sharon';
COMMIT;
Result:
Christina = 800
Sharon = 700
Failure Test
BEGIN;
UPDATE accounts SET balance = balance - 200 WHERE name = 'Christina';
~Error occurs
UPDATE accounts SET balanc = balance + 200 WHERE name = 'Sharon';
COMMIT;
What Happened?
The transaction failed.
Balances remain:
Christina = 1000
Sharon = 500
Top comments (0)