Transactions
Chapter 35: Transactions Overview
Section titled “Chapter 35: Transactions Overview”ACID Properties and Transaction Control
Section titled “ACID Properties and Transaction Control”35.1 Understanding Transactions
Section titled “35.1 Understanding Transactions”A transaction is a sequence of database operations that are treated as a single unit of work.
ACID Properties ========================================================================
┌─────────────────────────────────────────────────────────────────────┐ │ ACID Properties │ │ │ │ Atomicity: │ │ ────────── │ │ All operations succeed or all fail together │ │ - No partial updates │ │ - "All or nothing" │ │ │ │ Consistency: │ │ ─────────── │ │ Database moves from one valid state to another │ │ - Constraints maintained │ │ - Cascades properly applied │ │ │ │ Isolation: │ │ ────────── │ │ Concurrent transactions don't interfere │ │ - Each sees consistent view │ │ - Depends on isolation level │ │ │ │ Durability: │ │ ─────────── │ │ Committed data is永久 stored │ │ - Survives system crash │ │ - WAL ensures durability │ │ │ └─────────────────────────────────────────────────────────────────────┘35.2 Basic Transaction Commands
Section titled “35.2 Basic Transaction Commands”-- Explicit transactionBEGIN;
INSERT INTO accounts (account_id, balance) VALUES (1, 1000);INSERT INTO accounts (account_id, balance) VALUES (2, 500);
COMMIT; -- Make changes permanent
-- Or rollbackBEGIN;INSERT INTO accounts (account_id, balance) VALUES (3, 100);ROLLBACK; -- Discard changes
-- Using SAVEPOINTsBEGIN;INSERT INTO users (username, email) VALUES ('user1', 'user1@example.com');SAVEPOINT sp1;
INSERT INTO users (username, email) VALUES ('user2', 'user2@example.com');-- Problem occurred, go back to savepointROLLBACK TO SAVEPOINT sp1;
-- Release savepoint (not needed after rollback)COMMIT;35.3 Transaction Modes
Section titled “35.3 Transaction Modes”-- Read-only transactionBEGIN TRANSACTION READ ONLY;SELECT * FROM users; -- Can readINSERT INTO users VALUES ('test', 'test@test.com'); -- Will failCOMMIT;
-- Read-write transaction (default)BEGIN TRANSACTION READ WRITE;
-- Deferrable (waits for lock)BEGIN TRANSACTION ISOLATION LEVEL SERIALIZABLEDEFERRABLE;
-- PostgreSQL extensionsBEGIN;SET TRANSACTION ISOLATION LEVEL REPEATABLE READ;-- Do workCOMMIT;35.4 Implicit Transactions (Auto-commit)
Section titled “35.4 Implicit Transactions (Auto-commit)”-- Default autocommit behavior-- Each statement is its own transaction
-- Turn off autocommit (psql specific)\set AUTOCOMMIT off
-- Now need explicit BEGIN/COMMITBEGIN;INSERT INTO test (name) VALUES ('test1');INSERT INTO test (name) VALUES ('test2');COMMIT;
-- Or set in sessionSET default_transaction_deferrable = ON;35.5 Transaction in Functions
Section titled “35.5 Transaction in Functions”-- Function with explicit transaction controlCREATE OR REPLACE FUNCTION transfer_funds( p_from_account INTEGER, p_to_account INTEGER, p_amount NUMERIC) RETURNS BOOLEAN AS $$BEGIN -- Check if transaction already started IF current_setting('transaction_deferred') = 'on' THEN -- Already in a transaction END IF;
-- Deduct from source UPDATE accounts SET balance = balance - p_amount WHERE account_id = p_from_account;
IF NOT FOUND THEN RETURN FALSE; END IF;
-- Add to destination UPDATE accounts SET balance = balance + p_amount WHERE account_id = p_to_account;
RETURN TRUE;END;$$ LANGUAGE plpgsql;
-- Call with transactionBEGIN;SELECT transfer_funds(1, 2, 100);COMMIT;Summary
Section titled “Summary”| Command | Description |
|---|---|
| BEGIN | Start transaction |
| COMMIT | Save changes |
| ROLLBACK | Discard changes |
| SAVEPOINT | Create restore point |
| RELEASE SAVEPOINT | Remove savepoint |