"""Merge a freshly-baked SQLite snapshot into the live database on disk, preserving human-edited fields on `opportunities`. Usage: python scripts/publish_data.py SOURCE_DB DEST_DB Idempotent. Safe to re-run on every container start. """ from __future__ import annotations import sqlite3 import sys from pathlib import Path # Columns on `opportunities` that humans edit through the dashboard. # These are preserved from DEST when an opportunity already exists. PRESERVED_FIELDS = {"status", "next_action"} # Tables that come straight from the crawler. No human edits — replace wholesale. WHOLESALE_TABLES = ("sources", "crawl_runs", "opportunity_changes", "alerts") def _columns(conn: sqlite3.Connection, table: str) -> list[str]: return [row[1] for row in conn.execute(f"PRAGMA table_info({table})").fetchall()] def _replace_table(src: sqlite3.Connection, dst: sqlite3.Connection, table: str) -> int: cols = _columns(src, table) if not cols: return 0 dst.execute(f"DELETE FROM {table}") rows = src.execute(f"SELECT {', '.join(cols)} FROM {table}").fetchall() if rows: placeholders = ", ".join("?" for _ in cols) dst.executemany( f"INSERT INTO {table} ({', '.join(cols)}) VALUES ({placeholders})", rows, ) return len(rows) def _merge_opportunities(src: sqlite3.Connection, dst: sqlite3.Connection) -> tuple[int, int, int]: cols = _columns(src, "opportunities") if not cols: return (0, 0, 0) overwrite_cols = [c for c in cols if c not in PRESERVED_FIELDS and c != "id"] existing_ids = {row[0] for row in dst.execute("SELECT id FROM opportunities").fetchall()} src_rows = src.execute(f"SELECT {', '.join(cols)} FROM opportunities").fetchall() inserted = updated = 0 insert_placeholders = ", ".join("?" for _ in cols) insert_sql = ( f"INSERT INTO opportunities ({', '.join(cols)}) VALUES ({insert_placeholders})" ) update_assignments = ", ".join(f"{c} = ?" for c in overwrite_cols) update_sql = f"UPDATE opportunities SET {update_assignments} WHERE id = ?" id_index = cols.index("id") overwrite_indices = [cols.index(c) for c in overwrite_cols] src_ids: set[str] = set() for row in src_rows: oid = row[id_index] src_ids.add(oid) if oid in existing_ids: values = [row[i] for i in overwrite_indices] + [oid] dst.execute(update_sql, values) updated += 1 else: dst.execute(insert_sql, row) inserted += 1 # Prune: opportunities that exist live but are no longer in the source DB. # `opportunity_changes` and `alerts` were already replaced wholesale from # the source above, so deleting their parents here cannot orphan anything. stale_ids = existing_ids - src_ids for oid in stale_ids: dst.execute("DELETE FROM opportunities WHERE id = ?", (oid,)) return inserted, updated, len(stale_ids) def merge(source_path: Path, dest_path: Path) -> dict[str, int]: if not source_path.exists(): raise FileNotFoundError(f"Source DB not found: {source_path}") if not dest_path.exists(): raise FileNotFoundError(f"Dest DB not found: {dest_path}") src = sqlite3.connect(str(source_path)) dst = sqlite3.connect(str(dest_path)) try: # Replace crawler-only tables. wholesale_counts = {t: _replace_table(src, dst, t) for t in WHOLESALE_TABLES} # Merge opportunities preserving human-edited fields, then prune stale rows. inserted, updated, pruned = _merge_opportunities(src, dst) dst.commit() finally: src.close() dst.close() return {"inserted": inserted, "updated": updated, "pruned": pruned, **wholesale_counts} def main() -> None: if len(sys.argv) != 3: print("Usage: publish_data.py SOURCE_DB DEST_DB", file=sys.stderr) sys.exit(2) summary = merge(Path(sys.argv[1]), Path(sys.argv[2])) parts = [f"{k}={v}" for k, v in summary.items()] print("Merge complete: " + ", ".join(parts)) if __name__ == "__main__": main()