"""Measure SQLite REPLACE foreign-key actions on private disposable databases. No database path is accepted. Output uses exclusive creation; existing data is never overwritten. Python 3.11+ standard library only. No crash simulation. """ import argparse import hashlib import itertools import json import platform import sqlite3 import tempfile from datetime import datetime, timezone from pathlib import Path OPERATIONS = { "replace": "INSERT OR REPLACE INTO parent VALUES(1, 'new')", "upsert": ("INSERT INTO parent VALUES(1, 'new') " "ON CONFLICT(id) DO UPDATE SET label=excluded.label"), } ACTIONS = ("CASCADE", "RESTRICT", "NO ACTION") JOURNALS = ("DELETE", "WAL") def rows(db, sql): return [list(row) for row in db.execute(sql).fetchall()] def connect(path, journal, recursive): db = sqlite3.connect(path, isolation_level=None) db.execute("PRAGMA foreign_keys=ON") db.execute(f"PRAGMA recursive_triggers={recursive}") actual = db.execute(f"PRAGMA journal_mode={journal}").fetchone()[0] if actual.upper() != journal: raise RuntimeError(f"journal mode unavailable: {actual}") if db.execute("PRAGMA foreign_keys").fetchone()[0] != 1: raise RuntimeError("foreign-key enforcement unavailable") if db.execute("PRAGMA recursive_triggers").fetchone()[0] != recursive: raise RuntimeError("recursive_triggers setting not applied") return db def schema(action): if action not in ACTIONS: raise ValueError(action) return f""" CREATE TABLE parent(id INTEGER PRIMARY KEY, label TEXT NOT NULL); CREATE TABLE child(id INTEGER PRIMARY KEY, parent_id INTEGER NOT NULL REFERENCES parent(id) ON DELETE {action} DEFERRABLE INITIALLY DEFERRED, payload TEXT NOT NULL); CREATE TABLE audit(seq INTEGER PRIMARY KEY, event TEXT, object_id INTEGER); INSERT INTO parent VALUES(1,'original'),(2,'sentinel'); INSERT INTO child VALUES(11,1,'alpha'),(12,1,'beta'),(21,2,'untouched'); CREATE TRIGGER parent_delete AFTER DELETE ON parent BEGIN INSERT INTO audit(event,object_id) VALUES('parent-delete',old.id); END; CREATE TRIGGER parent_insert AFTER INSERT ON parent BEGIN INSERT INTO audit(event,object_id) VALUES('parent-insert',new.id); END; CREATE TRIGGER parent_update AFTER UPDATE ON parent BEGIN INSERT INTO audit(event,object_id) VALUES('parent-update',new.id); END; CREATE TRIGGER child_delete AFTER DELETE ON child BEGIN INSERT INTO audit(event,object_id) VALUES('child-delete',old.id); END; """ def snapshot(db): return { "parent": rows(db, "SELECT * FROM parent ORDER BY id"), "child": rows(db, "SELECT * FROM child ORDER BY id"), "audit": rows(db, "SELECT event,object_id FROM audit ORDER BY seq"), "integrityCheck": rows(db, "PRAGMA integrity_check"), "foreignKeyCheck": rows(db, "PRAGMA foreign_key_check"), "inTransaction": db.in_transaction, "deferForeignKeys": db.execute("PRAGMA defer_foreign_keys").fetchone()[0], } def perform(db, operation, global_defer=0): db.execute("BEGIN") db.execute(f"PRAGMA defer_foreign_keys={global_defer}") if db.execute("PRAGMA defer_foreign_keys").fetchone()[0] != global_defer: raise RuntimeError("defer_foreign_keys not applied") error = None try: db.execute(OPERATIONS[operation]) except sqlite3.IntegrityError as exc: error = {"message": str(exc), "code": exc.sqlite_errorcode, "name": exc.sqlite_errorname, "phase": "statement"} return {"error": error, "pending": snapshot(db)} def run_case(root, journal, action, recursive, operation, global_defer=0): key = f"{journal}-{action.replace(' ', '-')}-{recursive}-{operation}" if global_defer: key += "-global-defer" path = root / (key + ".sqlite") db = connect(path, journal, recursive) db.executescript(schema(action)) baseline = snapshot(db) trace = [] db.set_trace_callback(trace.append) rollback = perform(db, operation, global_defer) db.execute("ROLLBACK") db.close() db = connect(path, journal, recursive) rollback["reopened"] = snapshot(db) db.set_trace_callback(trace.append) final = perform(db, operation, global_defer) if final["error"] is None: try: db.execute("COMMIT") final["finalizer"] = "commit" except sqlite3.IntegrityError as exc: final["error"] = {"message": str(exc), "code": exc.sqlite_errorcode, "name": exc.sqlite_errorname, "phase": "commit"} db.execute("ROLLBACK") final["finalizer"] = "rollback-after-commit-error" else: db.execute("ROLLBACK") final["finalizer"] = "rollback-after-statement-error" db.close() digest = hashlib.sha256(path.read_bytes()).hexdigest() db = connect(path, journal, recursive) final["reopened"] = snapshot(db) settings = {name: db.execute(f"PRAGMA {name}").fetchone()[0] for name in ("foreign_keys", "recursive_triggers", "journal_mode", "defer_foreign_keys")} db.close() return {"id": key, "journal": journal, "action": action, "recursiveTriggers": recursive, "operation": operation, "globalDefer": global_defer, "sql": OPERATIONS[operation], "schemaSql": schema(action), "settings": settings, "baseline": baseline, "rollback": rollback, "final": final, "closedDatabaseSha256": digest, "trace": trace} def orphan_control(root, journal): path = root / ("orphan-" + journal + ".sqlite") db = connect(path, journal, 0) db.executescript(schema("NO ACTION")) db.execute("PRAGMA foreign_keys=OFF") if db.execute("PRAGMA foreign_keys").fetchone()[0] != 0: raise RuntimeError("orphan control was not configured") db.execute("DELETE FROM parent WHERE id=1") db.close() db = connect(path, journal, 0) result = snapshot(db) db.close() return {"journal": journal, "method": "foreign_keys OFF before parent deletion; ON after reopen", "reopened": result} def run(): with sqlite3.connect(":memory:") as db: environment = { "python": platform.python_version(), "sqlite": sqlite3.sqlite_version, "sqliteSourceId": db.execute("SELECT sqlite_source_id()").fetchone()[0], "compileOptions": [r[0] for r in db.execute("PRAGMA compile_options")], "system": platform.system(), "kernel": platform.release(), } with tempfile.TemporaryDirectory(prefix="hesela-replace-fk-") as directory: root = Path(directory) cases = [run_case(root, *values) for values in itertools.product(JOURNALS, ACTIONS, (0, 1), OPERATIONS)] controls = [orphan_control(root, journal) for journal in JOURNALS] defer_controls = [run_case(root, journal, "RESTRICT", recursive, "replace", 1) for journal, recursive in itertools.product(JOURNALS, (0, 1))] return { "schemaVersion": 1, "generatedAt": datetime.now(timezone.utc).isoformat(), "kind": "controlled-software-observation", "environment": environment, "harnessSha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), "design": "2 journals x 3 deferred FK actions x 2 trigger settings x 2 operations; 2 orphan controls; 4 global-deferral controls", "limits": ["Single writer and one INTEGER PRIMARY KEY conflict.", "All FK declarations are DEFERRABLE INITIALLY DEFERRED; main matrix leaves defer_foreign_keys OFF; four extra controls enable it.", "No crash, power loss, concurrency, performance or failure-frequency measurement.", "Trace callbacks can repeat statement text during trigger execution; they are not event counts."], "cases": cases, "orphanControls": controls, "globalDeferControls": defer_controls, } def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--output", required=True, type=Path) args = parser.parse_args() if args.output.exists(): parser.error("output already exists") result = run() with args.output.open("x", encoding="utf-8") as handle: json.dump(result, handle, indent=2) handle.write("\n") print(f"Recorded {len(result['cases'])} cases, 2 orphan and 4 global-deferral controls") if __name__ == "__main__": main()