Spaces:
Sleeping

File size: 1,687 Bytes
69d639b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
"""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()