"""Stream an online SQLite backup, or restore it to a new database path.""" import argparse import os import shutil import sqlite3 import sys import tempfile from contextlib import closing from pathlib import Path from .store import Database def checked(connection): if connection.execute("PRAGMA integrity_check").fetchone()[0] != "ok": raise ValueError("Нарушена целостность базы") for table in ("games", "catalogs", "commands", "events"): connection.execute(f"SELECT 1 FROM {table} LIMIT 0") if connection.execute("PRAGMA foreign_key_check").fetchone(): raise ValueError("Нарушена целостность связей") def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--restore", action="store_true") args = parser.parse_args() store = Database() if store.dsn: parser.error("Для PostgreSQL используйте pg_dump") path = Path(store.path).resolve() with tempfile.TemporaryDirectory(dir=path.parent if args.restore else None) as tmp: copy = Path(tmp) / "backup.db" if args.restore: with copy.open("wb") as out: shutil.copyfileobj(sys.stdin.buffer, out) with closing(sqlite3.connect(copy)) as con: checked(con) os.link(copy, path) else: with closing(sqlite3.connect(path.as_uri()+"?mode=ro", uri=True)) as src: with closing(sqlite3.connect(copy)) as dst: src.backup(dst) checked(dst) with copy.open("rb") as stream: shutil.copyfileobj(stream, sys.stdout.buffer) if __name__ == "__main__": main()