Transactions
A transaction is a group of SQL statements that commit as a unit or roll back as a unit. Either the charge and the stock decrement both happen, or neither does.
Detailed Explanation
Databases give you ACID. Atomicity is the one you feel first: BEGIN, work, COMMIT or ROLLBACK. Autocommit mode treats each statement as its own transaction. That is fine for a single SELECT and wrong for "insert order then insert lines".
In DB-API, conn.commit() and conn.rollback() are explicit. with conn: in sqlite3 commits if the block succeeds and rolls back if it raises. SQLAlchemy's Session begins a transaction implicitly and commits on session.commit(). Django wraps each request in a transaction when ATOMIC_REQUESTS is on, or you use with transaction.atomic():.
A rollback does not undo Python objects. An in-memory order.cents = 0 stays 0 after the database rolls back unless you refresh or discard the object. SQLAlchemy expires attributes on rollback; Django may still have stale in-memory fields. Re-read if you continue to use the instance.
Nested transactions are savepoints. A failing inner atomic block can roll back to a savepoint and let the outer block continue. Not every engine treats nested BEGIN the same; sqlite has limits. Know whether your helper is a real inner transaction or a no-op.
Keep transactions short. Do not hold a transaction open while you call a payment HTTP API. Lock time is a scarce resource. Do the remote call, then start a short transaction to record the result, or use an outbox table.
Isolation is a separate entry. READ COMMITTED vs SERIALIZABLE changes which anomalies you can see. Transactions without the right isolation still commit atomically; they just might commit a race.
Code Examples
import sqlite3
conn = sqlite3.connect(":memory:")
conn.execute("create table accounts (id text, cents int)")
conn.execute("insert into accounts values ('a', 100), ('b', 0)")
try:
conn.execute("update accounts set cents = cents - 40 where id = 'a'")
conn.execute("update accounts set cents = cents + 40 where id = 'b'")
conn.commit()
except Exception:
conn.rollback()
raise
print(conn.execute("select cents from accounts where id = 'a'").fetchone())# SQLAlchemy: one unit of work
# with Session(engine) as session:
# session.add(order)
# session.commit()Common Gotchas
Two statements, autocommit, a crash in the middle
you charged and did not record. Wrap them.
HTTP inside a transaction
you hold locks while the network is slow. Split the work.
In-memory objects after rollback
they lie. Refresh or recreate.
`commit` on a connection you did not `begin`
some drivers no-op, some autocommit each statement. Set the mode on purpose.