Complete worked example
python
import sqlite3
def inspect_example(events, as_of):
connection = sqlite3.connect('history.db', autocommit=False)
try:
connection.execute('CREATE TABLE dimension(id TEXT, country TEXT, valid_from INTEGER, valid_to INTEGER, PRIMARY KEY(id,valid_from))')
connection.commit()
with connection:
for event in events:
current = connection.execute('SELECT country,valid_from FROM dimension WHERE id=? AND valid_to IS NULL', [event['id']]).fetchone()
if current and event['tick'] < current[1]:
raise ValueError('historical correction needs explicit rebuilding')
if current and event['country'] == current[0]:
continue
if current and event['tick'] == current[1]:
raise ValueError('conflicting change at one instant')
connection.execute('UPDATE dimension SET valid_to=? WHERE id=? AND valid_to IS NULL', [event['tick'],event['id']])
connection.execute('INSERT INTO dimension VALUES(?,?,?,NULL)', [event['id'],event['country'],event['tick']])
history = [list(r) for r in connection.execute('SELECT id,country,valid_from,valid_to FROM dimension ORDER BY id,valid_from')]
visible = [list(r) for r in connection.execute('SELECT id,country FROM dimension WHERE valid_from <= ? AND (valid_to IS NULL OR ? < valid_to) ORDER BY id',[as_of,as_of])]
return {'history': history, 'asOf': visible}
finally:
connection.close()- Reasoning
- The program finds an identity's open row for each incoming change. A changed country closes the prior interval at the new tick and inserts a new open version. An unchanged country creates no redundant interval. Equal-tick contradictions and changes older than the current interval are explicitly rejected.