Junior — Middle
How is transaction integrity and reliability ensured in PostgreSQL?
sobes.tech AI
Answer from AI
In PostgreSQL, the integrity and reliability of transaction execution are ensured by supporting ACID properties (Atomicity, Consistency, Isolation, Durability):
- Atomicity: a transaction is executed completely or not at all. If an error occurs, all changes are rolled back.
- Consistency: after the transaction, the database remains in a correct state, adhering to all constraints and rules.
- Isolation: concurrent transactions do not affect each other, achieved through isolation levels and locks.
- Durability: once a transaction is committed, its changes are saved even in case of failures, thanks to write-ahead logging.
PostgreSQL uses MVCC (Multi-Version Concurrency Control) to manage concurrency and transaction isolation, allowing efficient handling of simultaneous operations without read locks.
Example of a transaction in Python with psycopg2:
import psycopg2
conn = psycopg2.connect(...)
try:
with conn:
with conn.cursor() as cur:
cur.execute("INSERT INTO users(name) VALUES(%s)", ('Alice',))
# other operations
except Exception as e:
print(f"Transaction error: {e}")
finally:
conn.close()
In this example, if an error occurs, all changes within the transaction block are rolled back.