Code

Transfer the Lantern Fuel

Fog Reach is running dry. Pip wants to move 3 barrels from Amber Isle. That's two changes: take from one depot, add to another.

UPDATE changes rows

cur = conn.execute(
    "UPDATE depots SET barrels = barrels - ? "
    "WHERE island = ?",
    (3, "Amber Isle"),
)
print(cur.rowcount)  # how many rows changed

Always include WHERE, or every row changes! If rowcount is 0, no row matched: maybe the island name is wrong.

Transactions: all or nothing

What if the first UPDATE works and the second fails? Barrels would vanish. A transaction groups changes so they all happen, or none do. In sqlite3, use the connection in a with block:

with conn:
    conn.execute(...)   # change 1
    conn.execute(...)   # change 2
  • If the block finishes, the changes are committed (saved).
  • If an exception escapes the block, they are rolled back (undone), and the exception carries on.

So you can raise an error on purpose to cancel everything. (with conn: doesn't close the connection. It just handles the transaction.)

Assignment

Table: depots(island TEXT PRIMARY KEY, barrels INTEGER).

  1. refuel(conn, island, barrels) adds barrels to that island, inside with conn:. If no row changed, raise KeyError(island).
  2. transfer(conn, giver, taker, barrels) takes barrels from giver and adds them to taker, inside one with conn: block. If either UPDATE changes 0 rows, raise KeyError, so the whole transfer is rolled back.