Commit and rollback from code
After this: Write a transfer that commits both changes or rolls both back, in Python and in Java.
On this page · 5 sections · 3 checks
Ana has 100 and Ben has 50 in a small bank table. Ana sends Ben 30. That is two changes: Ben's balance goes up, and Ana's goes down. If the program saved the first change and then failed on the second, money would appear from nowhere. In the tutorial on changing data you made such a pair all-or-nothing by typing BEGIN, COMMIT and ROLLBACK. This lesson does the same from a program.
The plan
The table has a rule, CHECK (balance >= 0), so no balance can go below zero. A function transfer(src, dst, amount) moves amount from account src to account dst:
- Add the amount to
dstwith an UPDATE. - Take the amount from
srcwith a second UPDATE. If that would leavesrcbelow zero, the database refuses it with an error. - If both worked, commit: both changes are saved together.
- If either failed, roll back: every change since the transaction began is undone.
To is the opposite of commit. Steps 3 and 4 need a way to notice the error, and you know that from the tutorial on errors: try and excepttry and catch.
Python's sqlite3 already opens a transaction before the first UPDATE, as lesson 1 showed, so the function does not need a line to begin one.Java must first turn autocommit off with conn.setAutoCommit(false). Without that line, each UPDATE would be saved the moment it ran, and there would be nothing to roll back.Step through it
The program makes two transfers. The first moves 30 from Ana to Ben. The second tries to move 120, which Ana no longer has.
- Run the programRun it and step through. The first transfer reaches the commit line. In the second, follow the line after the second UPDATE: the program jumps to the error handler, prints why, and rolls back. Then compare the two balances that show() prints after each transfer.
import sqlite3
conn = sqlite3.connect(":memory:")conn.execute("CREATE TABLE accounts (id INTEGER PRIMARY KEY, owner TEXT NOT NULL, balance INTEGER NOT NULL CHECK (balance >= 0))")conn.execute("INSERT INTO accounts VALUES (1, 'Ana', 100), (2, 'Ben', 50)")conn.commit()
def transfer(src, dst, amount): try: conn.execute("UPDATE accounts SET balance = balance + ? WHERE id = ?", (amount, dst)) conn.execute("UPDATE accounts SET balance = balance - ? WHERE id = ?", (amount, src)) conn.commit() return True except sqlite3.IntegrityError as e: print("refused:", e) conn.rollback() return False
def show(): for owner, balance in conn.execute("SELECT owner, balance FROM accounts ORDER BY id"): print(owner, balance)
print(transfer(1, 2, 30))show()print(transfer(1, 2, 120))show()run the program to see its boxes
nothing printed yetPress Run it, then step through the program one line at a time.
- lines
- 0
- prints
- 0
- calls
- 0
Follow the second transfer closely:
- The first UPDATE adds 120 to Ben. Inside the open transaction, Ben now has 200.
- The second UPDATE would leave Ana with 70 − 120 = −50. The rule refuses it, and the database raises an error.
- The program jumps to the error handler. It prints why, then rolls back. Ben's +120 is undone.
- The function returns Falsefalse, and
show()prints Ana 70 and Ben 80, the balances from after the first transfer.
The two languages print the same reason in different words:
Python: refused: CHECK constraint failed: balance >= 0Java: refused: [SQLITE_CONSTRAINT_CHECK] A CHECK constraint failed (CHECK constraint failed: balance >= 0)The shorter Python form
Check yourself
In the second transfer, the UPDATE that adds 120 to Ben worked, and then the UPDATE on Ana failed. The program runs conn.rollback()conn.rollback();. What does that do?
Start again from the fresh table: Ana has 100 and Ben has 50. The program makes only these calls, with the same transfer and show. What does it print?
print(transfer(2, 1, 50))show()System.out.println(transfer(2, 1, 50));show();Ana has 70 and Ben has 80. Suppose a broken transfer sends its two UPDATEs with no transaction, so each one is saved the moment it runs. It is asked to move 120 from Ana to Ben. What is left in the table?
Honesty notes
- Write a transfer that sends two UPDATEs, commits when both work, and rolls back when either fails.
- Catch the error the database raises when a CHECK rule is broken: IntegrityError in Python, SQLException in Java.
- Turn autocommit off in Java with setAutoCommit(false) before changes that must happen together.
- Use with conn: in Python to commit or roll back for you, and remember that it does not close the connection.