ATOMICITY
Let me explain the transaction working using accounts table
First, we have an accounts table with balance for each user.
Alice = 1000
Bob = 500
since, we are doing money transfer.. we need to deduct from one and add to another.
Now we start transaction to transfer 200 from Alice to Bob.
BEGIN;
UPDATE accounts
SET balance = balance - 200
WHERE name = 'Alice';
UPDATE accounts
SET balance = balance + 200
WHERE name = 'Bob';
COMMIT;
since, both debit and credit should happen together.. so we use transaction.
After successful transaction:
Alice = 800
Bob = 700
since, 200 is deducted from Alice and added to Bob.
Now we try with an error in between.
BEGIN;
UPDATE accounts
SET balance = balance - 200
WHERE name = 'Alice';
error happens here
UPDATE accounts
SET balance = balance + 2000o
WHERE name = 'Bob';
ROLLBACK;
since, second query has error.. so transaction fails.
After this failed transaction:
Alice = 1000
Bob = 500
since, even though money was deducted first.. rollback will undo it.. so no change happens.
Now we try another error case.
BEGIN;
UPDATE accounts
SET balance = balance - 200
WHERE name = 'Alice';
wrong table
SELECT * FROM wrong_table;
ROLLBACK;
since, error occurs again.. so full transaction is cancelled.
Final result:
Alice = 1000
Bob = 500
since, database does not allow partial updates.
THE FLOW IS:
since, transaction follows all-or-nothing rule..
either both debit and credit will happen
or none will happen
so,
money will not be lost
no duplicate transaction
no wrong balance
This is why payment apps use transactions to keep data safe.
Comments
Post a Comment