Database Transactions and ACID · Lesson 48 of 112

Database Transactions in Application Code

What you will learn

  • The with connection: pattern in Python's sqlite3
  • How to make a failure roll back automatically
  • How to retry when the database is busy
  • A short checklist for transactions in real programs

1. The with pattern

Writing BEGIN, COMMIT and ROLLBACK by hand invites mistakes. In Python's sqlite3, using the connection as a context manager does it for you: when the with block ends normally it commits; if an error escapes it rolls back.

import sqlite3

con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE accounts (name TEXT PRIMARY KEY, balance INTEGER NOT NULL CHECK (balance >= 0))")
con.execute("INSERT INTO accounts VALUES ('Rina', 500), ('Sam', 100)")
con.commit()

def transfer(con, src, dst, amount):
    with con:
        con.execute("UPDATE accounts SET balance = balance - ? WHERE name = ?", (amount, src))
        con.execute("UPDATE accounts SET balance = balance + ? WHERE name = ?", (amount, dst))

def show():
    print(con.execute("SELECT name, balance FROM accounts ORDER BY name").fetchall())

transfer(con, "Rina", "Sam", 200)
show()
try:
    transfer(con, "Rina", "Sam", 900)
except sqlite3.IntegrityError as e:
    print("failed:", e)
show()
[('Rina', 300), ('Sam', 300)]
failed: CHECK constraint failed: balance >= 0
[('Rina', 300), ('Sam', 300)]

The first transfer committed. The second raised an error inside the block, so the with rolled back and the balances stayed as they were. The error still reaches your code, so you can show a message.

What the with block does, in SQL. This lesson runs on the sample database you chose in lesson 4.1 (use the Example data picker at the top). The with block sends BEGIN, then COMMIT or ROLLBACK for you. In a SQL cell you write them yourself. The savers table is a small one of its own; Reset data starts again.

CREATE TABLE savers (name TEXT PRIMARY KEY, balance INTEGER NOT NULL CHECK (balance >= 0));
INSERT INTO savers VALUES ('Rina', 500), ('Sam', 100);
BEGIN;
UPDATE savers SET balance = balance - 200 WHERE name = 'Rina';
UPDATE savers SET balance = balance + 200 WHERE name = 'Sam';
COMMIT;
SELECT * FROM savers ORDER BY name;
name  balance
----  -------
Rina      300
Sam       300
(2 rows)

The second transfer tries to move 900. The first step breaks the CHECK rule, so it is refused, and the program must end the transaction:

BEGIN;
(done)
UPDATE savers SET balance = balance - 900 WHERE name = 'Rina';
IntegrityError: CHECK constraint failed: balance >= 0
ROLLBACK;
SELECT * FROM savers ORDER BY name;
name  balance
----  -------
Rina      300
Sam       300
(2 rows)
CREATE TABLE savers (name TEXT PRIMARY KEY, balance INTEGER NOT NULL CHECK (balance >= 0));
INSERT INTO savers VALUES ('Rina', 500), ('Sam', 100);
BEGIN;
UPDATE savers SET balance = balance - 200 WHERE name = 'Rina';
UPDATE savers SET balance = balance + 200 WHERE name = 'Sam';
COMMIT;
SELECT * FROM savers ORDER BY name;
name  balance
----  -------
Rina      300
Sam       300
(2 rows)

The second transfer tries to move 900. The first step breaks the CHECK rule, so it is refused, and the program must end the transaction:

BEGIN;
(done)
UPDATE savers SET balance = balance - 900 WHERE name = 'Rina';
IntegrityError: CHECK constraint failed: balance >= 0
ROLLBACK;
SELECT * FROM savers ORDER BY name;
name  balance
----  -------
Rina      300
Sam       300
(2 rows)
CREATE TABLE savers (name TEXT PRIMARY KEY, balance INTEGER NOT NULL CHECK (balance >= 0));
INSERT INTO savers VALUES ('Rina', 500), ('Sam', 100);
BEGIN;
UPDATE savers SET balance = balance - 200 WHERE name = 'Rina';
UPDATE savers SET balance = balance + 200 WHERE name = 'Sam';
COMMIT;
SELECT * FROM savers ORDER BY name;
name  balance
----  -------
Rina      300
Sam       300
(2 rows)

The second transfer tries to move 900. The first step breaks the CHECK rule, so it is refused, and the program must end the transaction:

BEGIN;
(done)
UPDATE savers SET balance = balance - 900 WHERE name = 'Rina';
IntegrityError: CHECK constraint failed: balance >= 0
ROLLBACK;
SELECT * FROM savers ORDER BY name;
name  balance
----  -------
Rina      300
Sam       300
(2 rows)

Note: with con: does not close the connection. It only ends the transaction:

try:
    con.execute("SELECT 1")
    print("still open")
except Exception as e:
    print(e)
still open

2. A failure halfway really is undone

c = sqlite3.connect(":memory:")
c.execute("CREATE TABLE t (n INTEGER UNIQUE)")
try:
    with c:
        c.execute("INSERT INTO t VALUES (1)")
        c.execute("INSERT INTO t VALUES (1)")
except sqlite3.IntegrityError as e:
    print(e)
print(c.execute("SELECT COUNT(*) FROM t").fetchone())
UNIQUE constraint failed: t.n
(0,)

The first insert was fine, the second broke the UNIQUE rule, and both were undone (count 0). That is atomicity (lesson 6.3) delivered by four lines of code.

The same failure halfway in SQL: the first insert is fine, the second breaks the UNIQUE rule, and the rollback undoes both.

CREATE TABLE t (n INTEGER UNIQUE);
BEGIN;
INSERT INTO t VALUES (1);
(1 row changed)
INSERT INTO t VALUES (1);
IntegrityError: UNIQUE constraint failed: t.n
ROLLBACK;
SELECT COUNT(*) AS rows_left FROM t;
rows_left
---------
        0
(1 row)
CREATE TABLE t (n INTEGER UNIQUE);
BEGIN;
INSERT INTO t VALUES (1);
(1 row changed)
INSERT INTO t VALUES (1);
IntegrityError: UNIQUE constraint failed: t.n
ROLLBACK;
SELECT COUNT(*) AS rows_left FROM t;
rows_left
---------
        0
(1 row)
CREATE TABLE t (n INTEGER UNIQUE);
BEGIN;
INSERT INTO t VALUES (1);
(1 row changed)
INSERT INTO t VALUES (1);
IntegrityError: UNIQUE constraint failed: t.n
ROLLBACK;
SELECT COUNT(*) AS rows_left FROM t;
rows_left
---------
        0
(1 row)

3. Retrying when the database is busy

Lesson 6.6 showed database is locked. A robust program tries again a few times. Here a second connection b wants to write while a holds the write lock; a commits after b's second failed try:

import os, tempfile

path = os.path.join(tempfile.mkdtemp(), "r.db")
a = sqlite3.connect(path, isolation_level=None)
a.execute("CREATE TABLE t (n INTEGER)")
a.execute("INSERT INTO t VALUES (0)")
b = sqlite3.connect(path, timeout=0.1, isolation_level=None)

a.execute("BEGIN IMMEDIATE")
attempts = 0
while True:
    attempts += 1
    try:
        b.execute("UPDATE t SET n = n + 1")
        print("done after", attempts, "attempts")
        break
    except sqlite3.OperationalError as e:
        print("attempt", attempts, "->", e)
        if attempts == 2:
            a.execute("COMMIT")      # simulates the other user finishing
print(b.execute("SELECT n FROM t").fetchone())
attempt 1 -> database is locked
attempt 2 -> database is locked
done after 3 attempts
(1,)

In a real program you would also set a maximum number of attempts, wait a little longer each time, and report failure if it still does not work. Retries are only safe if the whole transaction can be repeated without side effects (do not send an email inside it).

4. A checklist

  1. Put the steps that must belong together inside one with con: block.
  2. Keep it short: no user input, web calls or long calculations inside.
  3. Let errors reach you, catch the specific ones (IntegrityError, OperationalError), and tell the user what happened.
  4. Retry only for busy or deadlock errors, and only a limited number of times.
  5. Do the arithmetic in SQL (qty = qty - 1) when you can.
  6. Test the failure path as carefully as the happy path.

Worked example: placing an order

An order needs three steps: insert the order, insert its items, reduce the stock. Put all three in one block:

Step Inside with con:
1 INSERT the order
2 INSERT the item rows
3 UPDATE stock with qty = qty - ?

If step 3 breaks a CHECK (qty >= 0) rule (not enough stock), the error rolls back steps 1 and 2 as well. The customer sees "not enough stock" and no half-built order is left in the database. The shop is made up.

Common mistakes

  • Using with con: and expecting it to close the connection. Call con.close() separately (or use contextlib.closing).
  • Putting a print or an email inside the block and then retrying, so it runs twice.
  • Catching every exception and carrying on as if the transfer worked.
  • Retrying forever. Always set a limit.

Key takeaways

  • with con: commits on success and rolls back on error, then re-raises the error.
  • It does not close the connection.
  • Keep transactions short, catch specific errors, and retry busy errors a limited number of times.
  • A multi-step job in one block is all or nothing.

Practice

1. What does with con: do if an error escapes the block?

Show answer

It rolls back the transaction and lets the error continue to your code.

2. Does with con: close the connection?

Show answer

No; it only commits or rolls back. Close the connection separately.

3. In the UNIQUE example, why was the count 0 and not 1?

Show answer

The second insert failed, so the whole block was rolled back, including the first insert.

4. Why should a retry loop have a maximum number of attempts?

Show answer

Without a limit a permanently blocked program would wait forever instead of reporting the problem.

5. Why is it a mistake to send an email inside a transaction that may be retried?

Show answer

A retry would send it again, and a rollback cannot take an email back.

6. Rewrite in words: which three steps would you put in one block when cancelling an order?

Show answer

Mark the order as cancelled, put the items back in stock, and record the refund, all in one block so they happen together or not at all.