stage17-hierarchical-budget.py
TEXT FILE1.3 KB · Public source code for developers, search crawlers and AI agents
1"""Offline educational example; no wallet calls."""
2import sqlite3
3
4def reserve(db, intent, child, amount):
5 if child == "root" or type(amount) is not int or amount <= 0:
6 return False
7 db.execute("BEGIN IMMEDIATE")
8 try:
9 old = db.execute("SELECT child, amount FROM reservations WHERE id=?", (intent,)).fetchone()
10 if old is not None:
11 db.rollback()
12 return old == (child, amount)
13 for key in ("root", child):
14 if db.execute("UPDATE budgets SET remaining=remaining-? WHERE id=? AND remaining>=?", (amount,key,amount)).rowcount != 1:
15 db.rollback()
16 return False
17 db.execute("INSERT INTO reservations VALUES (?,?,?)", (intent,child,amount))
18 db.commit()
19 return True
20 except Exception:
21 db.rollback()
22 raise
23
24db = sqlite3.connect(":memory:", isolation_level=None)
25db.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);")
26assert reserve(db,"i1","a",600)
27assert reserve(db,"i1","a",600)
28assert not reserve(db,"i1","a",601)
29assert not reserve(db,"i2","b",500)
30assert reserve(db,"i3","b",400)
31db.close()Read-only source · Select a line number to link directly · Raw download above
