Spaces:
Sleeping

app / scripts /export_to_sqlite.py
CarlChaaya's picture
Super-squash branch 'main' using huggingface_hub
69d639b
Raw History Blame Contribute Delete
1.69 kB
"""Dump the configured database (typically local Postgres) to a portable SQLite
file the Dockerfile can bake into the deployed image.
Usage:
uv run python scripts/export_to_sqlite.py [TARGET_PATH]
Default target: tracker_local.sqlite at the repo root.
"""
from __future__ import annotations
import sys
from pathlib import Path
from sqlalchemy import create_engine, select
from opportunity_tracker.config import get_settings
from opportunity_tracker.models import Base
def export(target: Path) -> dict[str, int]:
src_url = get_settings().database_url
if src_url.startswith("sqlite") and Path(src_url.replace("sqlite:///", "")).resolve() == target.resolve():
raise SystemExit(f"Refusing to export {src_url} onto itself ({target}).")
if target.exists():
target.unlink()
src_engine = create_engine(src_url, future=True)
dst_engine = create_engine(
f"sqlite:///{target}", future=True, connect_args={"check_same_thread": False}
)
Base.metadata.create_all(dst_engine)
counts: dict[str, int] = {}
with src_engine.connect() as src, dst_engine.begin() as dst:
for table in Base.metadata.sorted_tables:
rows = src.execute(select(table)).mappings().all()
counts[table.name] = len(rows)
if rows:
dst.execute(table.insert(), [dict(r) for r in rows])
return counts
def main() -> None:
target = Path(sys.argv[1] if len(sys.argv) > 1 else "tracker_local.sqlite")
target = target.resolve()
counts = export(target)
print(f"Wrote {target}")
for name, n in counts.items():
print(f" {name}: {n}")
if __name__ == "__main__":
main()