"""Original Lawfare Academy SQLite integration lab. Not a production authentication system. Run: python relational_orders.py. Caller identities in these tests are verified fixtures. """ import sqlite3 def database(): db = sqlite3.connect(':memory:') db.execute('PRAGMA foreign_keys = ON') db.executescript(''' CREATE TABLE orders(id INTEGER PRIMARY KEY, owner TEXT NOT NULL, cents INTEGER NOT NULL CHECK(cents >= 0)); CREATE TABLE lines(id INTEGER PRIMARY KEY, order_id INTEGER NOT NULL REFERENCES orders(id)); CREATE TABLE payments(id INTEGER PRIMARY KEY, order_id INTEGER NOT NULL REFERENCES orders(id)); CREATE TABLE inventory(id INTEGER PRIMARY KEY, stock INTEGER NOT NULL CHECK(stock >= 0)); INSERT INTO orders VALUES(1,'a',12000); INSERT INTO lines VALUES(1,1),(2,1),(3,1); INSERT INTO payments VALUES(1,1),(2,1); INSERT INTO inventory VALUES(1,5); ''') return db def owned_order(db, order_id, verified_owner): return db.execute('SELECT id,cents FROM orders WHERE id=? AND owner=?', (order_id, verified_owner)).fetchone() def sell(db, item_id, quantity): if type(quantity) is not int or quantity <= 0: raise ValueError('Positive integer quantity required') with db: changed = db.execute('UPDATE inventory SET stock=stock-? WHERE id=? AND stock>=?', (quantity, item_id, quantity)) return changed.rowcount == 1 def main(): db = database() assert owned_order(db, 1, 'a') == (1, 12000) assert owned_order(db, 1, 'b') is None assert owned_order(db, 1, "' OR 1=1 --") is None wrong = db.execute('SELECT SUM(o.cents) FROM orders o JOIN lines l ON l.order_id=o.id JOIN payments p ON p.order_id=o.id').fetchone()[0] assert wrong == 72000 correct = db.execute('SELECT SUM(cents) FROM orders').fetchone()[0] assert correct == 12000 assert sell(db, 1, 4) is True assert sell(db, 1, 4) is False assert db.execute('SELECT stock FROM inventory WHERE id=1').fetchone()[0] == 1 # Verify a rollback, rather than merely asserting that transactions exist. try: with db: db.execute('INSERT INTO orders VALUES(2,?,?)', ('a', 500)) db.execute('INSERT INTO orders VALUES(3,?,?)', ('a', -1)) except sqlite3.IntegrityError: pass assert db.execute('SELECT COUNT(*) FROM orders WHERE id IN (2,3)').fetchone()[0] == 0 print('PASS: foreign-key configuration, owner filtering, injection value, join-grain trap, conditional decrement and rollback') db.close() if __name__ == '__main__': main()