Databases with SQLite · 12 / 15 Exercise Hard

Transfers with rollback

Objective

Create a Python program that makes transfers between accounts inside a transaction: if something fails, no change is applied. The connection can be used as a context manager, with con: commits on a clean exit and rolls back if there is an exception. Use an in-memory database with the sqlite3 module (sqlite3.connect(":memory:")).

Instructions

  • Create the table accounts with name (primary key, text) and balance (integer). Read n accounts with name balance and do commit().
  • Read m transfers with source target amount. Inside with con: subtract the amount from the source and add it to the target with two UPDATE.
  • Raise ValueError with unknown source if the source does not exist (rowcount is 0), with unknown destination if the target does not exist and with insufficient balance if the source ends up negative.
  • If everything goes well show Transfer completed; if there is a ValueError show Rejected: message. At the end show Balances: and each account as name: balance, sorted by name.
Input
2
ana 100
luis 50
2
ana luis 30
luis ana 200
Output
Transfer completed
Rejected: insufficient balance
Balances:
ana: 70
luis: 80

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise