#!/usr/bin/env python3 """Controlled SQLite generated-column semantics; disposable fixtures only.""" import argparse from contextlib import closing from datetime import datetime, timezone import hashlib import json from pathlib import Path import platform import shutil import sqlite3 import tempfile SCHEMA = """CREATE TABLE sample( id INTEGER PRIMARY KEY, x INTEGER NOT NULL, stored INTEGER GENERATED ALWAYS AS(score(x)) STORED, virtual INTEGER GENERATED ALWAYS AS(score(x)) VIRTUAL); CREATE INDEX stored_idx ON sample(stored);""" ROWS_SQL = "SELECT id,x,stored,virtual FROM sample NOT INDEXED ORDER BY id" INDEX_SQL = "SELECT id FROM sample INDEXED BY stored_idx WHERE stored=102 ORDER BY id" STAGES = ("original", "changed", "reindex", "backup", "dump-original", "dump-changed", "rewrite-one") def sha(path): return hashlib.sha256(Path(path).read_bytes()).hexdigest() def require(condition, message): if not condition: raise RuntimeError(message) def connect(path, offset=0, readonly=False): db = sqlite3.connect(path.resolve().as_uri() + ("?mode=ro" if readonly else "?mode=rw"), uri=True) db.create_function("score", 1, lambda value: value + offset, deterministic=True) return db def observe(path, stage, offset): before = sha(path) with closing(connect(path, offset, True)) as db: rows = [list(row) for row in db.execute(ROWS_SQL)] record = { "stage": stage, "callbackOffset": offset, "rowsSql": ROWS_SQL, "rows": rows, "mismatchIds": [row[0] for row in rows if row[2] != row[1] + offset], "indexedSql": INDEX_SQL, "indexedIds": [row[0] for row in db.execute(INDEX_SQL)], "queryPlan": [list(row) for row in db.execute("EXPLAIN QUERY PLAN " + INDEX_SQL)], "quickCheck": [row[0] for row in db.execute("PRAGMA quick_check")], "integrityCheck": [row[0] for row in db.execute("PRAGMA integrity_check")], "tableInfo": [list(row) for row in db.execute("PRAGMA table_info(sample)")], "tableXinfo": [list(row) for row in db.execute("PRAGMA table_xinfo(sample)")], "schema": [list(row) for row in db.execute( "SELECT type,name,sql FROM sqlite_schema WHERE sql IS NOT NULL ORDER BY name")], } record.update(sha256Before=before, sha256After=sha(path)) return record def validate(result): require(result["kind"] == "controlled-software-experiment", "experiment label") require([row["stage"] for row in result["cases"]] == list(STAGES), "stage coverage") for row in result["cases"]: stage = row["stage"] offset = 0 if stage in ("original", "dump-original") else 100 stored = [101, 102, 103] if stage == "dump-changed" else ( [1, 102, 3] if stage == "rewrite-one" else [1, 2, 3]) expected = [[i, i, stored[i-1], i+offset] for i in (1, 2, 3)] require(row["callbackOffset"] == offset and row["rows"] == expected, stage + " rows") require(row["mismatchIds"] == [r[0] for r in expected if r[2] != r[3]], stage + " mismatch") require(row["indexedIds"] == ([2] if stage in ("dump-changed", "rewrite-one") else []), stage + " indexed result") require(any("stored_idx" in p[3] for p in row["queryPlan"]), stage + " forced index") require(row["rowsSql"] == ROWS_SQL and row["indexedSql"] == INDEX_SQL, "query identity") require(row["quickCheck"] == ["ok"] and row["integrityCheck"] == ["ok"], stage + " checks") require([r[1] for r in row["tableInfo"]] == ["id", "x"], stage + " table_info") require([(r[1], r[6]) for r in row["tableXinfo"]] == [("id", 0), ("x", 0), ("stored", 3), ("virtual", 2)], stage + " table_xinfo") require(row["schema"] == result["cases"][0]["schema"], stage + " schema preservation") for name in ("sha256Before", "sha256After"): value = row[name] require(len(value) == 64 and all(c in "0123456789abcdef" for c in value), "hash syntax") require(row["sha256Before"] == row["sha256After"], stage + " read-only preservation") require(result["sourceSha256Before"] == result["sourceSha256After"] == result["cases"][0]["sha256Before"] == result["cases"][1]["sha256Before"], "source preservation") require(result["backupProgress"] and result["backupProgress"][-1]["status"] == sqlite3.SQLITE_DONE and result["backupProgress"][-1]["remaining"] == 0, "backup completion") inserts = [line for line in result["dumpSql"].splitlines() if line.startswith("INSERT INTO")] require(inserts == ['INSERT INTO "sample" VALUES(1,1);', 'INSERT INTO "sample" VALUES(2,2);', 'INSERT INTO "sample" VALUES(3,3);'], "dump inputs") require(result["operations"]["reindex"] == "REINDEX main.stored_idx" and result["operations"]["rewrite-one"] == "UPDATE sample SET x=x WHERE id=2", "operation identity") require(result["dumpSha256"] == hashlib.sha256(result["dumpSql"].encode()).hexdigest(), "dump hash") def run(work_root): with tempfile.TemporaryDirectory(prefix="hesela-generated-", dir=work_root) as folder: root = Path(folder) source = root / "source.db" with closing(sqlite3.connect(source)) as db: db.create_function("score", 1, lambda value: value, deterministic=True) require(db.execute("PRAGMA journal_mode=DELETE").fetchone()[0] == "delete", "journal") db.executescript(SCHEMA) db.executemany("INSERT INTO sample(id,x) VALUES(?,?)", [(1, 1), (2, 2), (3, 3)]) db.commit() source_hash = sha(source) with closing(connect(source, readonly=True)) 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")], "platform": platform.system(), "machine": platform.machine(), } dump_sql = "\n".join(db.iterdump()) + "\n" cases, progress = [], [] operations = {"reindex": "REINDEX main.stored_idx", "rewrite-one": "UPDATE sample SET x=x WHERE id=2"} for stage in STAGES: target = root / (stage + ".db") offset = 0 if stage in ("original", "dump-original") else 100 if stage == "backup": with closing(connect(source, readonly=True)) as src, closing(sqlite3.connect(target)) as dst: src.backup(dst, pages=1, progress=lambda status, remaining, total: progress.append(dict(status=status, remaining=remaining, total=total))) elif stage.startswith("dump-"): with closing(sqlite3.connect(target)) as dst: dst.create_function("score", 1, lambda value: value + offset, deterministic=True) dst.executescript(dump_sql) else: shutil.copyfile(source, target) if stage in operations: with closing(connect(target, offset)) as dst: dst.execute(operations[stage]) dst.commit() cases.append(observe(target, stage, offset)) result = { "schemaVersion": 1, "kind": "controlled-software-experiment", "generatedAt": datetime.now(timezone.utc).isoformat(), "harnessSha256": sha(__file__), "environment": environment, "fixtureSchema": SCHEMA, "operations": operations, "cases": cases, "sourceSha256Before": source_hash, "sourceSha256After": sha(source), "backupProgress": progress, "dumpSql": dump_sql, "dumpSha256": hashlib.sha256(dump_sql.encode()).hexdigest(), "limitations": [ "Deliberately changed deterministic callback; not a newly discovered SQLite defect.", "Three constructed rows, no incident sample or estimated failure frequency.", "Closed DELETE-journal fixtures; no concurrent writes, crash, power loss or WAL.", "Python iterdump replay, not every SQL dump tool; callbacks are supplied explicitly.", "The rewrite-one control is not a production migration recommendation.", ], } validate(result) return result def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--work-root", type=Path, default=Path(".")) parser.add_argument("--output", type=Path, required=True) args = parser.parse_args() if args.output.exists() or args.output.is_symlink(): parser.error("refusing to overwrite an output path") result = run(args.work_root) with args.output.open("x", encoding="utf-8") as output: json.dump(result, output, indent=2) output.write("\n") print("Verified 7 generated-column cases; wrote " + str(args.output)) if __name__ == "__main__": main()