#!/usr/bin/env python3 """Консистентная копия SQLite через backup API.""" from __future__ import annotations import argparse import hashlib import sqlite3 import sys import time from pathlib import Path def file_digest(path: Path, chunk_size: int = 1024 * 1024) -> str: digest = hashlib.sha256() with path.open("rb") as handle: while block := handle.read(chunk_size): digest.update(block) return digest.hexdigest() def main() -> int: parser = argparse.ArgumentParser(description="Создать копию базы SQLite") parser.add_argument("--database", type=Path, required=True) parser.add_argument("--dest", type=Path, required=True) parser.add_argument("--dry-run", action="store_true") args = parser.parse_args() source = args.database.expanduser().resolve() dest = args.dest.expanduser().resolve() if not source.is_file(): parser.error(f"База не найдена: {source}") if dest == source: parser.error("База и каталог назначения совпадают") timestamp = time.strftime("%Y%m%d-%H%M%S") target = dest / f"{source.stem}-{timestamp}.sqlite" if target.exists(): parser.error(f"Файл уже существует: {target}") if args.dry_run: print(f"Будет создано: {target}") return 0 dest.mkdir(parents=True, exist_ok=True) source_conn = sqlite3.connect(source.as_uri() + "?mode=ro", uri=True) target_conn = sqlite3.connect(target) try: source_conn.backup(target_conn) check = target_conn.execute("PRAGMA integrity_check").fetchone() if not check or check[0] != "ok": raise RuntimeError("integrity_check не прошёл") except Exception as error: target_conn.close() source_conn.close() target.unlink(missing_ok=True) print(f"Ошибка копирования: {error}", file=sys.stderr) return 1 target_conn.close() source_conn.close() print(f"Создана копия: {target}") print(f"Размер: {target.stat().st_size} байт") print(f"SHA-256: {file_digest(target)}") return 0 if __name__ == "__main__": sys.exit(main())