"""Read-only inspection and safe identifiers for imported SQLite databases.""" import sqlite3 from contextlib import contextmanager from pathlib import Path def quote(name): return '"' + name.replace('"', '""') + '"' def public_row(row): """Keep opaque bytes out of JSON metadata and model context.""" return {key: None if isinstance(value, bytes) else value for key, value in dict(row).items()} def foreign_key_groups(table): groups = {} for field in table["foreign_keys"]: groups.setdefault(field["id"], []).append(field) return [sorted(group, key=lambda field: field["seq"]) for group in groups.values()] def composite_references(table, entity): """Find declared tuples whose complete mapping the recipe elects to sample.""" for group in foreign_key_groups(table): if len(group) < 2: continue fields = tuple(fk["from"] for fk in group) parent = group[0]["table"] keys = tuple(fk["to"] for fk in group) generators = [entity.generators[field] for field in fields] if any( gen.kind != "reference" or gen.target_table != parent or gen.target_field != key for gen, key in zip(generators, keys, strict=True) ): continue scopes = {gen.reference_scope for gen in generators} if len(scopes) != 1: raise ValueError(f"Composite reference {entity.table}{fields} needs one target scope") yield fields, parent, keys, scopes.pop() @contextmanager def connect(path, readonly=False): db = sqlite3.connect( Path(path).resolve().as_uri() + ("?mode=ro" if readonly else "?mode=rw"), uri=True ) db.row_factory = sqlite3.Row db.execute("PRAGMA foreign_keys=ON") db.execute("PRAGMA trusted_schema=OFF") db.setlimit(sqlite3.SQLITE_LIMIT_LENGTH, 10_000_000) try: with db: yield db finally: db.close() def inspect(path): with connect(path, True) as db: tables = [] for row in db.execute( "SELECT name, sql FROM sqlite_schema WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name" ): name = row["name"] columns = [dict(c) for c in db.execute(f"PRAGMA table_xinfo({quote(name)})")] unique_columns = set() primary = sorted((c for c in columns if c["pk"]), key=lambda c: c["pk"]) unique_keys = [[c["name"] for c in primary]] if primary else [] for index in db.execute(f"PRAGMA index_list({quote(name)})"): if index["unique"]: fields = list(db.execute(f"PRAGMA index_info({quote(index['name'])})")) if len(fields) == 1 and fields[0]["name"]: unique_columns.add(fields[0]["name"]) if not index["partial"] and all(f["name"] is not None for f in fields): key = [f["name"] for f in fields] if key not in unique_keys: unique_keys.append(key) for column in columns: column["unique"] = column["name"] in unique_columns field = quote(column["name"]) profile = db.execute( f"SELECT count({field}), max(typeof({field})='blob') FROM {quote(name)}" ).fetchone() column["non_null_count"] = profile[0] column["opaque"] = bool(profile[1]) or column["type"].upper() == "BLOB" foreign_keys = [dict(f) for f in db.execute(f"PRAGMA foreign_key_list({quote(name)})")] for foreign_key in foreign_keys: if foreign_key["to"] is None: parent_keys = sorted( ( dict(c) for c in db.execute(f"PRAGMA table_info({quote(foreign_key['table'])})") if c["pk"] ), key=lambda c: c["pk"], ) if foreign_key["seq"] < len(parent_keys): foreign_key["to"] = parent_keys[foreign_key["seq"]]["name"] tables.append( { "name": name, "sql": row["sql"], "columns": columns, "unique_keys": unique_keys, "foreign_keys": foreign_keys, "count": db.execute(f"SELECT count(*) FROM {quote(name)}").fetchone()[0], "samples": [ public_row(r) for r in db.execute(f"SELECT * FROM {quote(name)} LIMIT 5") ], } ) if not tables: raise ValueError("Database contains no tables") return { "tables": tables, "constraints": "SQLite NOT NULL, UNIQUE, CHECK, and foreign keys remain enforced. Generated columns and triggers are preserved.", } def backup(source, destination): with connect(source, True) as src, sqlite3.connect(destination) as dst: src.backup(dst)