hi!
To Perform a successful transfer between two accounts and commit the transaction,
first creating a table accounts,
CREATE TABLE accounts (id SERIAL PRIMARY KEY,name TEXT NOT NULL,balance INT NOT NULL CHECK (balance >= 0),last_updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP);
the table contains attributes id as peimary key, name,balance >=0,last_updated.next to insert values to the table accounts
INSERT INTO accounts (name, balance) VALUES ('Alice', 1000),('Bob', 500);
To ensuring that the changes are reflected in the database.
BEGIN;
UPDATE accounts SET balance = balance - 300 WHERE name = 'Alice';
UPDATE accounts SET balance = balance + 300 WHERE name = 'Bob';
COMMIT;
here the amount deduction and the amount added is done successfully.
After simulating a system restart or database crash to check whether the reconnect to the database account balance is successful.And to verify whether the committed changes persist even after the restart.
SELECT name, balance FROM accounts;
how the system guarantees durability and consider what could happen if a failure occurs just before or just after a commit, and how the database ensures that committed data is not lost.
For this PostgreSQL uses a mechanism called Write-Ahead Logging (WAL).
Before changes are applied to disk,the database describes the change in log file (the WAL).
When COMMIT, the database ensures this log is stored to the disk.
*if a failure occurs just after-the data will be in wal because commit is executed
*if a failure occurs just before-the is treated as incomplete. Upon restart, the database identifies this as an uncommitted transaction and performs a Rollback.
Top comments (0)