Spaces:
Runtime error

File size: 5,690 Bytes
ed86a97
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
"""One-shot migration: copy all data from local SQLite to Supabase Postgres.

Usage:
    SOURCE_DB=sqlite:///./data/ai_tester.db \
    TARGET_DB=postgresql+psycopg2://postgres:PWD@db.PROJECT.supabase.co:5432/postgres \
    python -m scripts.migrate_sqlite_to_postgres

What it does:
    1. Connects to both DBs via SQLAlchemy.
    2. Calls `Base.metadata.create_all` on TARGET (schema init β€” idempotent).
    3. For each table in dependency order, copies rows SQLite β†’ Postgres in
       batches.

Why not pgloader / `sqlite3 .dump`: SQLite and Postgres SQL dialects differ
on AUTOINCREMENT, JSON storage (TEXT vs JSONB), boolean (INTEGER vs BOOLEAN),
and timestamp formats. Going through SQLAlchemy's column types lets the
driver handle the conversions automatically (e.g. `Boolean(0|1)` β†’ `false|true`,
`JSON("...")` β†’ `jsonb`).

Safety:
    - Idempotency: if a row already exists on target (PK conflict), we
      ABORT the script β€” re-running on a half-migrated DB is your problem
      to resolve (truncate target or use --resume not implemented here).
      For a one-shot migration on a fresh Supabase, this is fine.
    - No deletes: we only INSERT. The SQLite source is left untouched.
"""

from __future__ import annotations

import os
import sys
from typing import Iterable

from sqlalchemy import create_engine, text
from sqlalchemy.engine import Engine
from sqlalchemy.exc import IntegrityError


# Import the SQLAlchemy Base so we know the schema. Importing src.db.models
# registers all tables on `Base.metadata`.
from src.db.database import Base  # noqa: E402
import src.db.models  # noqa: F401,E402  ensure all models register


BATCH_SIZE = 500


def _mask(url: str) -> str:
    """Hide password from a SQLAlchemy URL for log output."""
    if "@" not in url or "://" not in url:
        return url
    scheme, rest = url.split("://", 1)
    if "@" not in rest:
        return url
    creds, host = rest.split("@", 1)
    if ":" in creds:
        user, _ = creds.split(":", 1)
        creds = f"{user}:****"
    return f"{scheme}://{creds}@{host}"


def _copy_table(name: str, src: Engine, dst: Engine) -> int:
    """Copy rows from one table SQLite β†’ Postgres. Returns count copied.

    Uses SQLAlchemy Core (no ORM session): we read raw rows from source
    and feed them to the destination as dicts. SQLAlchemy translates the
    Python values through the destination's column type system, which
    handles type coercion (SQLite stores booleans as int 0/1; Postgres
    needs real booleans, etc.).
    """
    table = Base.metadata.tables[name]
    with src.connect() as sc, dst.begin() as dc:
        total = 0
        result = sc.execute(table.select())
        batch: list[dict] = []
        for row in result:
            batch.append(dict(row._mapping))
            if len(batch) >= BATCH_SIZE:
                dc.execute(table.insert(), batch)
                total += len(batch)
                batch.clear()
        if batch:
            dc.execute(table.insert(), batch)
            total += len(batch)
        return total


def _enable_postgres_extensions(engine: Engine) -> None:
    """Supabase needs `pgcrypto` for `gen_random_uuid()` if any model uses it."""
    try:
        with engine.begin() as conn:
            conn.execute(text('CREATE EXTENSION IF NOT EXISTS "pgcrypto"'))
    except Exception as exc:  # noqa: BLE001
        # Non-fatal: only relevant if a model uses UUID defaults server-side.
        print(f"  ⚠ pgcrypto extension skipped: {exc}")


def main() -> int:
    src_url = os.environ.get("SOURCE_DB", "sqlite:///./data/ai_tester.db")
    dst_url = os.environ.get("TARGET_DB")
    if not dst_url:
        print("ERROR: set TARGET_DB env var (Supabase postgres connection string)")
        return 2

    # SKIP_TABLES: comma-separated list of table names to skip during the
    # data copy phase. Schema is still synced via create_all (idempotent).
    # Use case: keep prod-side `profiles` rows intact (they're tied to
    # Supabase auth.users, can't be recreated from local SQLite).
    skip = {
        t.strip() for t in os.environ.get("SKIP_TABLES", "").split(",") if t.strip()
    }

    print(f"Source:  {_mask(src_url)}")
    print(f"Target:  {_mask(dst_url)}")
    if skip:
        print(f"Skip:    {sorted(skip)}")
    print()

    src = create_engine(src_url)
    dst = create_engine(dst_url, future=True)

    print("β†’ Creating schema on target (idempotent)...")
    _enable_postgres_extensions(dst)
    Base.metadata.create_all(bind=dst)
    print("  βœ“ schema ok")
    print()

    # `sorted_tables` walks parents-before-children based on FK declarations,
    # so we don't violate referential integrity during insert.
    tables: Iterable[str] = [t.name for t in Base.metadata.sorted_tables]

    print("β†’ Copying data...")
    grand_total = 0
    for tname in tables:
        if tname in skip:
            print(f"  Β· {tname:35s} SKIPPED (in SKIP_TABLES)")
            continue
        try:
            n = _copy_table(tname, src, dst)
        except IntegrityError as exc:
            # Most likely: target already has these rows from a previous run.
            print(f"  βœ— {tname}: integrity error β€” target not empty? {exc.orig}")
            return 1
        except Exception as exc:  # noqa: BLE001
            print(f"  βœ— {tname}: {type(exc).__name__}: {exc}")
            return 1
        marker = "Β·" if n == 0 else "βœ“"
        print(f"  {marker} {tname:35s} {n:6d} rows")
        grand_total += n

    print()
    print(f"Done. {grand_total} rows migrated across {len(list(Base.metadata.sorted_tables))} tables.")
    return 0


if __name__ == "__main__":
    sys.exit(main())