Complete worked example
python
import sqlite3
def inspect_example(rows):
connection = sqlite3.connect('warehouse.db', autocommit=False)
try:
connection.execute('CREATE TABLE fact(id TEXT PRIMARY KEY, version INTEGER NOT NULL, amount_cents INTEGER NOT NULL)')
connection.commit()
for batch in [rows, rows]:
with connection:
for row in batch:
previous = connection.execute('SELECT version, amount_cents FROM fact WHERE id=?', [row['id']]).fetchone()
if previous and previous[0] == row['version'] and previous[1] != row['amount_cents']:
raise ValueError('conflicting source version')
connection.execute('INSERT INTO fact VALUES (:id,:version,:amount_cents) ON CONFLICT(id) DO UPDATE SET version=excluded.version, amount_cents=excluded.amount_cents WHERE excluded.version > fact.version', row)
stored = [list(r) for r in connection.execute('SELECT id,version,amount_cents FROM fact ORDER BY id')]
return {'rows': stored, 'count': len(stored)}
finally:
connection.close()- Reasoning
- The program opens an on-disk database, creates its fact table and applies the same delivery twice. INSERT handles a new identity; ON CONFLICT performs an update only when excluded.version exceeds the stored version. A preliminary check rejects equal-version payload disagreements instead of choosing an arbitrary winner.