Complete worked example
python
import sqlite3
def inspect_example(values, fail):
connection = sqlite3.connect('warehouse.db', autocommit=False)
try:
connection.executescript('CREATE TABLE fact(pos INTEGER PRIMARY KEY, value INTEGER); CREATE TABLE checkpoint(pos INTEGER); INSERT INTO checkpoint VALUES(0);')
connection.commit()
try:
with connection:
for pos, value in enumerate(values, 1):
connection.execute('INSERT INTO fact VALUES(?,?)', [pos, value])
if fail:
raise RuntimeError('controlled failure before checkpoint')
connection.execute('UPDATE checkpoint SET pos=?', [len(values)])
except RuntimeError:
pass
finally:
connection.close()
reopened = sqlite3.connect('warehouse.db', autocommit=False)
try:
rows = [list(r) for r in reopened.execute('SELECT pos,value FROM fact ORDER BY pos')]
return {'rows': rows, 'checkpoint': reopened.execute('SELECT pos FROM checkpoint').fetchone()[0]}
finally:
reopened.close()- Reasoning
- The baseline configures sqlite3 with autocommit disabled and enters the connection context for the batch. It writes facts, optionally raises the deliberate RuntimeError, then advances the checkpoint only on the successful path. Context exit commits success or rolls back the failed transaction.