DEV Community

Anjana R.K.
Anjana R.K.

Posted on

Atomicity - Design a Reliable Wallet Transfer System with ACID Guarantees

hi!
to Design a transaction that transfers money from one account to another using the accounts 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);
Enter fullscreen mode Exit fullscreen mode

create a table with attributes id,name,balance to check balance in account,and last_update .then insert values to the table using insert.
INSERT INTO accounts (name, balance) VALUES ('Alice', 1000),('Bob', 500);

BEGIN;
UPDATE accounts 
SET balance = balance - 200 
WHERE name = 'Alice';
UPDATE accounts 
SET balance = balance + 200 
WHERE name = 'Bob';
COMMIT;
Enter fullscreen mode Exit fullscreen mode

the balance from sender in deducted using update and again using update the balance of reciever is added then the transaction is commited to get the updated result.

BEGIN;
UPDATE accounts 
SET balance = balance - 100 
WHERE name = 'Alice';
UPDATE accounts 
SET balances = balance + 100 
WHERE name = 'Bob';
ROLLBACK;
Enter fullscreen mode Exit fullscreen mode

here to show Failed Transaction: Breaking the Credit Operation
first the query 1:updating the account by debiting succeeds
the next query 2:updating the accounts by crediting but here the column name is wrong ,so it fails.Due to the failure of query 2 it roolback.
Creating Failed Transaction for Constraint Violation

BEGIN;
UPDATE accounts 
SET balance = balance - 2000 
WHERE name = 'Alice';
ROLLBACK;
Enter fullscreen mode Exit fullscreen mode

here the debited amount is more than the available balance so,this will trigger the check constraint violation immediatelyand the system will not allow the next step.

Top comments (0)