Complete worked example
python
import sqlite3
def inspect_example(events):
connection = sqlite3.connect('cdc.db', autocommit=False)
try:
connection.execute('CREATE TABLE state(id TEXT PRIMARY KEY, version INTEGER, amount_cents INTEGER, deleted INTEGER)')
connection.commit()
with connection:
for event in events:
if event['op'] not in ['upsert', 'delete']:
raise ValueError('unknown operation')
connection.execute('INSERT INTO state VALUES(?,?,?,?) ON CONFLICT(id) DO UPDATE SET version=excluded.version,amount_cents=excluded.amount_cents,deleted=excluded.deleted WHERE excluded.version > state.version',
[event['id'], event['version'], event.get('amount_cents'), int(event['op'] == 'delete')])
visible = [r[0] for r in connection.execute('SELECT id FROM state WHERE deleted=0 ORDER BY id')]
retained = [list(r) for r in connection.execute('SELECT id,version,deleted FROM state ORDER BY id')]
return {'visible': visible, 'retained': retained}
finally:
connection.close()- Reasoning
- For each event the program forms a current-state payload and applies a parameterized UPSERT guarded by a strictly newer version. A delete stores a tombstone; an upsert stores a visible amount. The report separately queries visible identities and retained ordering state so the distinction can be inspected.