import sqlite3 def reserve(db, intent, amount, cap): if type(amount) is not int or type(cap) is not int or not 0 < amount <= cap <= 21_000_000*100_000_000: raise ValueError('invalid amount or cap') db.execute('BEGIN IMMEDIATE') try: total = db.execute('SELECT COALESCE(SUM(amount),0) FROM reservations').fetchone()[0] if total + amount > cap: raise ValueError('budget exceeded') db.execute('INSERT INTO reservations VALUES (?,?)',(intent,amount)) db.commit() except Exception: db.rollback() raise if __name__ == '__main__': db = sqlite3.connect(':memory:') db.execute('CREATE TABLE reservations (intent TEXT PRIMARY KEY, amount INTEGER NOT NULL)') reserve(db,'a',600,1000) try: reserve(db,'b',500,1000) except ValueError: pass else: raise AssertionError('overspend accepted')