This commit is contained in:
latypov committed 2026-11-23 23:55:37 +07:00
commit 2ca7a264b3
53 files changed
+7113

No files matched your search

+42
View File
@@ -0,0 +1,42 @@
"""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()