"""Offline educational example; no wallet calls.""" import sqlite3 def reserve(db, intent, child, amount): if child == "root" or type(amount) is not int or amount <= 0: return False db.execute("BEGIN IMMEDIATE") try: old = db.execute("SELECT child, amount FROM reservations WHERE id=?", (intent,)).fetchone() if old is not None: db.rollback() return old == (child, amount) for key in ("root", child): if db.execute("UPDATE budgets SET remaining=remaining-? WHERE id=? AND remaining>=?", (amount,key,amount)).rowcount != 1: db.rollback() return False db.execute("INSERT INTO reservations VALUES (?,?,?)", (intent,child,amount)) db.commit() return True except Exception: db.rollback() raise db = sqlite3.connect(":memory:", isolation_level=None) db.executescript("CREATE TABLE budgets(id TEXT PRIMARY KEY, remaining INTEGER); CREATE TABLE reservations(id TEXT PRIMARY KEY, child TEXT, amount INTEGER); INSERT INTO budgets VALUES ('root',1000),('a',700),('b',700);") assert reserve(db,"i1","a",600) assert reserve(db,"i1","a",600) assert not reserve(db,"i1","a",601) assert not reserve(db,"i2","b",500) assert reserve(db,"i3","b",400) db.close()