stage11-spending-budget.py
TEXT FILE886 B · Public source code for developers, search crawlers and AI agents
1import sqlite3
2
3def reserve(db, intent, amount, cap):
4 if type(amount) is not int or type(cap) is not int or not 0 < amount <= cap <= 21_000_000*100_000_000:
5 raise ValueError('invalid amount or cap')
6 db.execute('BEGIN IMMEDIATE')
7 try:
8 total = db.execute('SELECT COALESCE(SUM(amount),0) FROM reservations').fetchone()[0]
9 if total + amount > cap:
10 raise ValueError('budget exceeded')
11 db.execute('INSERT INTO reservations VALUES (?,?)',(intent,amount))
12 db.commit()
13 except Exception:
14 db.rollback()
15 raise
16
17if __name__ == '__main__':
18 db = sqlite3.connect(':memory:')
19 db.execute('CREATE TABLE reservations (intent TEXT PRIMARY KEY, amount INTEGER NOT NULL)')
20 reserve(db,'a',600,1000)
21 try: reserve(db,'b',500,1000)
22 except ValueError: pass
23 else: raise AssertionError('overspend accepted')Read-only source · Select a line number to link directly · Raw download above
