"""A local transactional CDC replay reference with retained tombstones."""
import sqlite3


def connect():
    db = sqlite3.connect(":memory:")
    db.execute("CREATE TABLE current (id TEXT PRIMARY KEY, version INTEGER NOT NULL, value TEXT)")
    return db


def apply(db, events):
    """Apply a batch atomically. A null value represents a tombstone."""
    with db:
        for key, version, value in events:
            if not isinstance(key, str) or not key or type(version) is not int or version < 0:
                raise ValueError("Expected a nonempty key and a nonnegative integer version")
            if value is not None and not isinstance(value, str):
                raise ValueError("Expected text or a tombstone")
            row = db.execute("SELECT version, value FROM current WHERE id = ?", (key,)).fetchone()
            if row and row[0] == version and row[1] != value:
                raise ValueError("Conflicting payload at the same source version")
            db.execute("""
                INSERT INTO current VALUES (?, ?, ?)
                ON CONFLICT(id) DO UPDATE SET version = excluded.version, value = excluded.value
                WHERE excluded.version > current.version
                """, (key, version, value))


def snapshot(db):
    return db.execute("SELECT id, value FROM current WHERE value IS NOT NULL ORDER BY id").fetchall()


if __name__ == "__main__":
    database = connect()
    apply(database, [("a", 1, "created"), ("a", 3, None), ("a", 2, "late"), ("b", 1, "active")])
    print(snapshot(database))
