mum / scripts /migrate_sqlite_to_postgres.py
MUZISANG\muzi
feat(deploy): dockerize service and add postgres/redis-ready runtime
de0a22d
Raw History Blame Contribute Delete
7.45 kB
#!/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())