Transaction: An atomic group of statements that must all succeed or all fail.
(e.g. bank money transfer)
- A single statement (without begin/commit) is a transaction
- Failure: e.g. Incorrect statements, power outages, resource not available
- Transaction in psycopg: Opening a connection starts a transaction
Use try/except block to commit on success / rollback on error
Transaction Problems & Isolation Levels
Use Isolation Level: begin; set transaction isolation level <level-name>;
Dirty Read: Reading partial (uncommitted) result from another transaction
- Read Committed: Only committed results are seen in a trans~
(Default in Postgres)
- Lock: A trans~ locks writes to the rows it’s operating on
Non-repeatable Reads: Reads can change between start and end of a transaction
(because of other committed transactions).
- Repeatable Read: One trans~ can’t see changes by other trans~ from start to end.
Serialization Anomaly: When two uncommitted transactions produce inconsistent results
(When T1+T2 ≠ T1→T2 or T2→T1)
- Serializable: Can commit only if result is consistent with committed trans~
- Have large performance overhead