#!/usr/bin/env python3 """Inspect secondary-index metadata and readback in private in-memory databases.""" import argparse from contextlib import closing from datetime import datetime, timezone import hashlib import json from pathlib import Path import sqlite3 ROWS = [("A", "one", "group"), ("a", "one", "group"), ("B", "two", "group"), ("b", "two", "other")] COLUMNS = ["seqno", "cid", "name", "desc", "coll", "key"] VARIANTS = ( ("rowid", "", "a,c"), ("primary-key-suffix", " WITHOUT ROWID", "c"), ("matching-collation", " WITHOUT ROWID", "a,c"), ("different-collation", " WITHOUT ROWID", "a COLLATE NOCASE,c"), ) EXPECTED = { "rowid": [(0, 0, "a", 0, "BINARY", 1), (1, 2, "c", 0, "BINARY", 1), (2, -1, None, 0, "BINARY", 0)], "primary-key-suffix": [(0, 2, "c", 0, "BINARY", 1), (1, 0, "a", 0, "BINARY", 0), (2, 1, "b", 0, "BINARY", 0)], "matching-collation": [(0, 0, "a", 0, "BINARY", 1), (1, 2, "c", 0, "BINARY", 1), (2, 1, "b", 0, "BINARY", 0)], "different-collation": [(0, 0, "a", 0, "NOCASE", 1), (1, 2, "c", 0, "BINARY", 1), (2, 0, "a", 0, "BINARY", 0), (3, 1, "b", 0, "BINARY", 0)], } READ = "SELECT a,b,c FROM entries INDEXED BY idx ORDER BY a COLLATE BINARY,b,c" POINT = "SELECT a,b,c FROM entries INDEXED BY idx WHERE a=? COLLATE BINARY AND b=?" def require(condition, message): if not condition: raise ValueError(message) def validate(case): name = case["variant"] require(name in EXPECTED, "variant") require(case["indexXinfo"] == [dict(zip(COLUMNS, row)) for row in EXPECTED[name]], "index metadata") require(case["rows"] == [list(row) for row in sorted(ROWS)], "complete readback") require(case["pointReads"] == [[list(ROWS[0])], [list(ROWS[1])]], "case-sensitive lookup") require(case["integrityCheck"] == ["ok"], "integrity check") def run(): cases = [] for name, suffix, columns in VARIANTS: schema = [ "CREATE TABLE entries(a TEXT COLLATE BINARY,b TEXT,c TEXT,PRIMARY KEY(a,b))" + suffix, "CREATE INDEX idx ON entries(" + columns + ")", ] with closing(sqlite3.connect(":memory:")) as db: for sql in schema: db.execute(sql) db.executemany("INSERT INTO entries VALUES(?,?,?)", ROWS) cursor = db.execute("PRAGMA index_xinfo(idx)") require([col[0] for col in cursor.description] == COLUMNS, "metadata columns") case = { "variant": name, "schema": schema, "indexXinfo": [dict(zip(COLUMNS, row)) for row in cursor], "rows": [list(row) for row in db.execute(READ)], "pointReads": [[list(row) for row in db.execute(POINT, (a, "one"))] for a in ("A", "a")], "integrityCheck": [row[0] for row in db.execute("PRAGMA integrity_check")], } validate(case) cases.append(case) source_id = db.execute("SELECT sqlite_source_id()").fetchone()[0] return { "evidenceType": "controlled-software-observation", "generatedAt": datetime.now(timezone.utc).isoformat(), "sqliteVersion": sqlite3.sqlite_version, "sqliteSourceId": source_id, "codeSha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), "method": {"insertedRows": ROWS, "metadataSql": "PRAGMA index_xinfo(idx)", "readSql": READ, "pointSql": POINT, "pointParameters": [["A", "one"], ["a", "one"]]}, "limits": [ "Four generated in-memory schemas, not a benchmark or production dataset.", "index_xinfo reports index metadata; it does not decode file bytes or measure storage size.", "key=0 marks auxiliary columns, not columns irrelevant to distinguishing index entries.", "The original 12 page-layout fixtures are a separate experiment and remain unchanged.", ], "cases": cases, } 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; choose a new path") result = run() with args.output.open("x", encoding="utf-8") as output: json.dump(result, output, indent=2) output.write("\n") print("Validated four in-memory secondary-index controls") if __name__ == "__main__": main()