|
| 1 | +"""基于活动 SQLAlchemy 引擎的 SQLite 与 PostgreSQL 备份实现。""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import os |
| 6 | +import shutil |
| 7 | +import sqlite3 |
| 8 | +import subprocess |
| 9 | +from contextlib import closing |
| 10 | +from dataclasses import dataclass |
| 11 | +from pathlib import Path |
| 12 | +from typing import Callable, Mapping, Protocol, Sequence |
| 13 | + |
| 14 | +from sqlalchemy.engine import Engine |
| 15 | + |
| 16 | + |
| 17 | +@dataclass(frozen=True, slots=True) |
| 18 | +class DatabaseBackupCheck: |
| 19 | + """数据库适配器返回的基础校验结果。""" |
| 20 | + |
| 21 | + valid: bool |
| 22 | + method: str |
| 23 | + detail: str | None = None |
| 24 | + |
| 25 | + |
| 26 | +class ProcessResult(Protocol): |
| 27 | + """数据库命令执行结果的最小合同。""" |
| 28 | + |
| 29 | + returncode: int |
| 30 | + stdout: str |
| 31 | + stderr: str |
| 32 | + |
| 33 | + |
| 34 | +class ProcessRunner(Protocol): |
| 35 | + """可替换的数据库命令执行边界。""" |
| 36 | + |
| 37 | + def __call__( |
| 38 | + self, |
| 39 | + command: Sequence[str], |
| 40 | + *, |
| 41 | + env: Mapping[str, str], |
| 42 | + capture_output: bool, |
| 43 | + text: bool, |
| 44 | + check: bool, |
| 45 | + ) -> ProcessResult: |
| 46 | + """执行命令并返回结果。""" |
| 47 | + |
| 48 | + |
| 49 | +class SQLiteBackupBackend: |
| 50 | + """使用 SQLite 在线备份 API 管理活动文件数据库。""" |
| 51 | + |
| 52 | + db_type = "sqlite" |
| 53 | + suffix = ".db" |
| 54 | + |
| 55 | + def __init__(self, engine: Engine) -> None: |
| 56 | + self._engine = engine |
| 57 | + database = engine.url.database |
| 58 | + if not database or database == ":memory:": |
| 59 | + raise ValueError("SQLite 内存数据库不支持文件备份") |
| 60 | + self._database = Path(database) |
| 61 | + |
| 62 | + def create(self, destination: Path) -> None: |
| 63 | + """从活动引擎指向的 SQLite 文件创建一致快照。""" |
| 64 | + source = self._engine.raw_connection() |
| 65 | + try: |
| 66 | + with closing(sqlite3.connect(destination)) as target: |
| 67 | + source.driver_connection.backup(target) |
| 68 | + target.commit() |
| 69 | + finally: |
| 70 | + source.close() |
| 71 | + |
| 72 | + def verify(self, artifact: Path) -> DatabaseBackupCheck: |
| 73 | + """通过 SQLite integrity_check 校验备份内容。""" |
| 74 | + method = "PRAGMA integrity_check" |
| 75 | + try: |
| 76 | + # 已发布前的临时快照不会再变化;immutable 避免 WAL 模式为只读校验创建旁路文件。 |
| 77 | + uri = f"{artifact.resolve().as_uri()}?mode=ro&immutable=1" |
| 78 | + with closing(sqlite3.connect(uri, uri=True)) as connection: |
| 79 | + rows = connection.execute("PRAGMA integrity_check").fetchall() |
| 80 | + except sqlite3.Error as error: |
| 81 | + return DatabaseBackupCheck(False, method, str(error)) |
| 82 | + valid = bool(rows) and all(row[0] == "ok" for row in rows) |
| 83 | + detail = None if valid else "; ".join(str(row[0]) for row in rows) |
| 84 | + return DatabaseBackupCheck(valid, method, detail) |
| 85 | + |
| 86 | + def restore(self, artifact: Path) -> None: |
| 87 | + """在 CLI 离线进程中原子替换活动 SQLite 文件。""" |
| 88 | + temporary = self._database.with_name(f".{self._database.name}.restore") |
| 89 | + self._engine.dispose() |
| 90 | + try: |
| 91 | + shutil.copy2(artifact, temporary) |
| 92 | + temporary.chmod(0o600) |
| 93 | + self._database.with_name(f"{self._database.name}-wal").unlink(missing_ok=True) |
| 94 | + self._database.with_name(f"{self._database.name}-shm").unlink(missing_ok=True) |
| 95 | + os.replace(temporary, self._database) |
| 96 | + finally: |
| 97 | + temporary.unlink(missing_ok=True) |
| 98 | + |
| 99 | + |
| 100 | +class PostgreSQLBackupBackend: |
| 101 | + """使用 pg_dump 与 pg_restore 管理活动 PostgreSQL 数据库。""" |
| 102 | + |
| 103 | + db_type = "postgresql" |
| 104 | + suffix = ".dump" |
| 105 | + |
| 106 | + def __init__( |
| 107 | + self, |
| 108 | + engine: Engine, |
| 109 | + *, |
| 110 | + runner: ProcessRunner = subprocess.run, |
| 111 | + tool_resolver: Callable[[str], str | None] = shutil.which, |
| 112 | + pg_dump: str = "pg_dump", |
| 113 | + pg_restore: str = "pg_restore", |
| 114 | + ) -> None: |
| 115 | + self._engine = engine |
| 116 | + self._runner = runner |
| 117 | + self._tool_resolver = tool_resolver |
| 118 | + self._pg_dump = pg_dump |
| 119 | + self._pg_restore = pg_restore |
| 120 | + |
| 121 | + def create(self, destination: Path) -> None: |
| 122 | + """创建 PostgreSQL custom-format 在线备份。""" |
| 123 | + command = [ |
| 124 | + self._require_tool(self._pg_dump), |
| 125 | + "--format=custom", |
| 126 | + "--no-owner", |
| 127 | + "--no-acl", |
| 128 | + "--file", |
| 129 | + str(destination), |
| 130 | + *self._connection_arguments(), |
| 131 | + ] |
| 132 | + result = self._run(command, include_password=True) |
| 133 | + if result.returncode != 0: |
| 134 | + raise RuntimeError(f"pg_dump 执行失败,退出码 {result.returncode}") |
| 135 | + if not destination.is_file() or destination.stat().st_size == 0: |
| 136 | + raise RuntimeError("pg_dump 未生成有效的备份文件") |
| 137 | + |
| 138 | + def verify(self, artifact: Path) -> DatabaseBackupCheck: |
| 139 | + """通过 pg_restore 目录读取校验 custom-format 归档。""" |
| 140 | + method = "pg_restore --list" |
| 141 | + result = self._run( |
| 142 | + [self._require_tool(self._pg_restore), "--list", str(artifact)], |
| 143 | + include_password=False, |
| 144 | + ) |
| 145 | + valid = result.returncode == 0 and bool(result.stdout.strip()) |
| 146 | + detail = None if valid else f"pg_restore 退出码 {result.returncode}" |
| 147 | + return DatabaseBackupCheck(valid, method, detail) |
| 148 | + |
| 149 | + def restore(self, artifact: Path) -> None: |
| 150 | + """在 CLI 离线进程中覆盖当前 PostgreSQL 数据库内容。""" |
| 151 | + command = [ |
| 152 | + self._require_tool(self._pg_restore), |
| 153 | + "--clean", |
| 154 | + "--if-exists", |
| 155 | + "--no-owner", |
| 156 | + "--no-acl", |
| 157 | + "--single-transaction", |
| 158 | + "--exit-on-error", |
| 159 | + *self._connection_arguments(), |
| 160 | + str(artifact), |
| 161 | + ] |
| 162 | + result = self._run(command, include_password=True) |
| 163 | + if result.returncode != 0: |
| 164 | + raise RuntimeError(f"pg_restore 执行失败,退出码 {result.returncode}") |
| 165 | + |
| 166 | + def _connection_arguments(self) -> list[str]: |
| 167 | + url = self._engine.url |
| 168 | + host = str(url.query.get("host") or url.host or "") |
| 169 | + port = str(url.query.get("port") or url.port or "") |
| 170 | + arguments = [ |
| 171 | + "--username", |
| 172 | + str(url.username or ""), |
| 173 | + "--dbname", |
| 174 | + str(url.database or ""), |
| 175 | + ] |
| 176 | + if host: |
| 177 | + arguments.extend(["--host", host]) |
| 178 | + if port: |
| 179 | + arguments.extend(["--port", port]) |
| 180 | + return arguments |
| 181 | + |
| 182 | + def _run(self, command: Sequence[str], *, include_password: bool) -> ProcessResult: |
| 183 | + return self._runner( |
| 184 | + command, |
| 185 | + env=self._environment(include_password=include_password), |
| 186 | + capture_output=True, |
| 187 | + text=True, |
| 188 | + check=False, |
| 189 | + ) |
| 190 | + |
| 191 | + def _require_tool(self, executable: str) -> str: |
| 192 | + resolved = self._tool_resolver(executable) |
| 193 | + if resolved is None: |
| 194 | + raise RuntimeError( |
| 195 | + f"未找到 {executable},请安装与服务端同主版本或更高的 " |
| 196 | + "PostgreSQL client 并加入 PATH" |
| 197 | + ) |
| 198 | + return resolved |
| 199 | + |
| 200 | + def _environment(self, *, include_password: bool) -> dict[str, str]: |
| 201 | + environment = dict(os.environ) |
| 202 | + environment.pop("PGPASSWORD", None) |
| 203 | + environment.pop("PGSSLMODE", None) |
| 204 | + if include_password and self._engine.url.password: |
| 205 | + environment["PGPASSWORD"] = str(self._engine.url.password) |
| 206 | + sslmode = self._engine.url.query.get("sslmode") |
| 207 | + if sslmode: |
| 208 | + environment["PGSSLMODE"] = str(sslmode) |
| 209 | + return environment |
0 commit comments