"""Copy a consistent PostgreSQL snapshot into an empty SQLite database.""" import sqlite3 from .store import Database def migrate(): import psycopg store = Database() if not store.dsn: raise SystemExit("Укажите исходную PostgreSQL через DATABASE_URL или DB_PASSWORD_FILE") source = store.dsn store.dsn = None store.init() tables = ("catalogs", "games", "events", "commands") with psycopg.connect(source) as pg, sqlite3.connect(store.path, timeout=30) as dest: pg.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ, READ ONLY") dest.execute("PRAGMA foreign_keys=ON") dest.execute("BEGIN IMMEDIATE") for table in tables: if dest.execute(f"SELECT 1 FROM {table} LIMIT 1").fetchone(): raise SystemExit("Целевая SQLite уже содержит данные") for table in tables: columns = [row[1] for row in dest.execute(f"PRAGMA table_info({table})")] projection = ",".join(columns) marks = ",".join("?" for _ in columns) with pg.cursor(name="copy_" + table) as cur: cur.execute(f"SELECT {projection} FROM {table}") while rows := cur.fetchmany(256): dest.executemany(f"INSERT INTO {table} ({projection}) VALUES ({marks})", rows) count = dest.execute(f"SELECT COUNT(*) FROM {table}").fetchone()[0] if count != pg.execute(f"SELECT COUNT(*) FROM {table}").fetchone()[0]: raise RuntimeError(f"Расхождение числа строк в {table}") print(f"{table}: {count}") if dest.execute("PRAGMA integrity_check").fetchone()[0] != "ok": raise RuntimeError("SQLite integrity_check failed") print("Перенос завершён") if __name__ == "__main__": migrate()