File size: 7,454 Bytes
de0a22d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
Migrate local SQLite stores to PostgreSQL.

Default sources:
  - data/accounts.db
  - data/conversations.db

Target:
  - DATABASE_URL / --postgres-url
"""

import argparse
import json
import os
import sqlite3
import sys
from typing import Any, Dict, Iterable, List, Optional


def _require_psycopg():
    try:
        import psycopg  # type: ignore
        return psycopg
    except Exception:
        print("psycopg is required. Install with: pip install psycopg[binary]", file=sys.stderr)
        raise


def _sqlite_connect(path: str) -> sqlite3.Connection:
    conn = sqlite3.connect(path)
    conn.row_factory = sqlite3.Row
    return conn


def _sqlite_columns(conn: sqlite3.Connection, table: str) -> set[str]:
    cur = conn.execute(f"PRAGMA table_info({table})")
    return {str(r[1]) for r in cur.fetchall()}


def _coerce_retryable(v: Any) -> Optional[bool]:
    if v is None:
        return None
    try:
        return bool(int(v))
    except Exception:
        return None


def _coerce_messages_json(v: Any) -> str:
    if isinstance(v, str):
        try:
            obj = json.loads(v)
            if isinstance(obj, list):
                return json.dumps(obj, ensure_ascii=False)
        except Exception:
            pass
    return "[]"


def _read_accounts(conn: sqlite3.Connection) -> Iterable[Dict[str, Any]]:
    cols = _sqlite_columns(conn, "accounts")
    select_cols = [
        "email",
        "password",
        "status",
        "workspace_id",
        "last_error",
        "failure_code",
        "retryable",
        "created_at",
        "updated_at",
    ]
    real_cols = [c for c in select_cols if c in cols]
    if not real_cols:
        return []

    cur = conn.execute(f"SELECT {', '.join(real_cols)} FROM accounts")
    out: List[Dict[str, Any]] = []
    for row in cur.fetchall():
        d = {k: row[k] if k in row.keys() else None for k in select_cols}
        if not d.get("email"):
            continue
        d["retryable"] = _coerce_retryable(d.get("retryable"))
        out.append(d)
    return out


def _read_conversations(conn: sqlite3.Connection) -> Iterable[Dict[str, Any]]:
    cols = _sqlite_columns(conn, "conversation_history")
    required = {"conversation_id", "messages_json", "updated_at"}
    if not required.issubset(cols):
        return []

    cur = conn.execute("SELECT conversation_id, messages_json, updated_at FROM conversation_history")
    out: List[Dict[str, Any]] = []
    for row in cur.fetchall():
        cid = str(row["conversation_id"] or "").strip()
        if not cid:
            continue
        out.append(
            {
                "conversation_id": cid,
                "messages_json": _coerce_messages_json(row["messages_json"]),
                "updated_at": row["updated_at"],
            }
        )
    return out


def _ensure_pg_schema(pg_conn) -> None:
    with pg_conn.cursor() as cur:
        cur.execute(
            """
            CREATE TABLE IF NOT EXISTS accounts (
                email TEXT PRIMARY KEY,
                password TEXT NOT NULL,
                status TEXT NOT NULL DEFAULT 'registered',
                workspace_id TEXT,
                last_error TEXT,
                failure_code TEXT,
                retryable BOOLEAN,
                created_at TEXT,
                updated_at TEXT
            )
            """
        )
        cur.execute(
            """
            CREATE TABLE IF NOT EXISTS conversation_history (
                conversation_id TEXT PRIMARY KEY,
                messages_json JSONB NOT NULL,
                updated_at TEXT NOT NULL
            )
            """
        )
        cur.execute(
            """
            CREATE INDEX IF NOT EXISTS idx_conversation_history_updated_at
            ON conversation_history(updated_at)
            """
        )
    pg_conn.commit()


def _upsert_accounts(pg_conn, rows: Iterable[Dict[str, Any]]) -> int:
    n = 0
    with pg_conn.cursor() as cur:
        for row in rows:
            cur.execute(
                """
                INSERT INTO accounts (
                    email, password, status, workspace_id, last_error, failure_code, retryable, created_at, updated_at
                )
                VALUES (
                    %(email)s, %(password)s, %(status)s, %(workspace_id)s, %(last_error)s, %(failure_code)s, %(retryable)s, %(created_at)s, %(updated_at)s
                )
                ON CONFLICT (email) DO UPDATE SET
                    password = EXCLUDED.password,
                    status = EXCLUDED.status,
                    workspace_id = COALESCE(EXCLUDED.workspace_id, accounts.workspace_id),
                    last_error = EXCLUDED.last_error,
                    failure_code = EXCLUDED.failure_code,
                    retryable = EXCLUDED.retryable,
                    updated_at = EXCLUDED.updated_at
                """
                ,
                row,
            )
            n += 1
    pg_conn.commit()
    return n


def _upsert_conversations(pg_conn, rows: Iterable[Dict[str, Any]]) -> int:
    n = 0
    with pg_conn.cursor() as cur:
        for row in rows:
            cur.execute(
                """
                INSERT INTO conversation_history (
                    conversation_id, messages_json, updated_at
                )
                VALUES (
                    %(conversation_id)s, %(messages_json)s::jsonb, %(updated_at)s
                )
                ON CONFLICT (conversation_id) DO UPDATE SET
                    messages_json = EXCLUDED.messages_json,
                    updated_at = EXCLUDED.updated_at
                """,
                row,
            )
            n += 1
    pg_conn.commit()
    return n


def main() -> int:
    parser = argparse.ArgumentParser(description="Migrate SQLite stores to PostgreSQL")
    parser.add_argument("--accounts-db", default="data/accounts.db", help="Path to accounts SQLite DB")
    parser.add_argument("--conversations-db", default="data/conversations.db", help="Path to conversations SQLite DB")
    parser.add_argument("--postgres-url", default=os.getenv("DATABASE_URL", ""), help="PostgreSQL URL")
    args = parser.parse_args()

    pg_url = str(args.postgres_url or "").strip()
    if not pg_url:
        print("Missing PostgreSQL URL. Pass --postgres-url or set DATABASE_URL.", file=sys.stderr)
        return 2

    psycopg = _require_psycopg()

    accounts_rows: List[Dict[str, Any]] = []
    conversations_rows: List[Dict[str, Any]] = []

    if os.path.exists(args.accounts_db):
        with _sqlite_connect(args.accounts_db) as conn:
            accounts_rows = list(_read_accounts(conn))
    else:
        print(f"[WARN] accounts DB not found: {args.accounts_db}")

    if os.path.exists(args.conversations_db):
        with _sqlite_connect(args.conversations_db) as conn:
            conversations_rows = list(_read_conversations(conn))
    else:
        print(f"[WARN] conversations DB not found: {args.conversations_db}")

    with psycopg.connect(pg_url) as pg_conn:
        _ensure_pg_schema(pg_conn)
        n_accounts = _upsert_accounts(pg_conn, accounts_rows)
        n_conversations = _upsert_conversations(pg_conn, conversations_rows)

    print("[OK] migration finished")
    print(f"accounts: {n_accounts}")
    print(f"conversations: {n_conversations}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())