Files
worklog/repair_db.py
T
2026-10-29 16:27:34 +08:00

249 lines
9.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""WorkLog 数据库损坏检测与修复脚本(Windows / Linux 通用,只用标准库)。
用法:
python repair_db.py --check 只做完整性检测
python repair_db.py 检测,损坏则恢复到 <库名>.recovered
python repair_db.py --replace -y 恢复后用修复库替换原库(坏库存为 .corrupt-时间戳)
说明:
"database disk image is malformed" 表示数据库文件损坏,常见诱因:
服务运行中直接拷贝/上传覆盖了 db 文件、文件传输被截断、磁盘写满、
残留的 -wal/-shm 文件与主库不匹配。
修复优先用 sqlite3 命令行的 .recover(最完整);没有 sqlite3 命令时
退化为逐表读取复制(损坏页所在表的数据可能缺失,脚本会逐表报告)。
"""
from __future__ import annotations
import argparse
import os
import shutil
import sqlite3
import subprocess
import sys
from datetime import datetime
from pathlib import Path
PROJECT_DIR = Path(__file__).resolve().parent
TABLES = ("users", "sessions", "email_verifications", "activities", "participations")
SIDE_SUFFIXES = ("-wal", "-shm", "-journal")
def resolve_db_path(explicit: str | None) -> Path:
"""与 server/main.py / clear_db.py 一致:--db > WORKLOG_DB > config.toml > ./data/worklog.db"""
raw = explicit or os.getenv("WORKLOG_DB")
if not raw:
raw = "./data/worklog.db"
config_path = Path(os.getenv("WORKLOG_CONFIG", str(PROJECT_DIR / "config.toml")))
try:
import tomllib
with open(config_path, "rb") as fh:
cfg = tomllib.load(fh)
raw = cfg.get("database", {}).get("path", raw)
except Exception:
pass
path = Path(raw)
return path if path.is_absolute() else PROJECT_DIR / path
def integrity_report(path: Path) -> tuple[bool, str]:
"""返回 (是否完好, 详情)。只读打开,不改动文件。"""
try:
conn = sqlite3.connect(f"file:{path}?mode=ro", uri=True)
except sqlite3.DatabaseError as exc:
return False, f"无法打开数据库:{exc}"
try:
rows = conn.execute("PRAGMA integrity_check").fetchall()
except sqlite3.DatabaseError as exc:
return False, str(exc)
finally:
conn.close()
bad = [r[0] for r in rows if r[0] != "ok"]
return (not bad), ("ok" if not bad else ";".join(bad[:5]))
def table_counts(path: Path) -> dict[str, int | None]:
counts: dict[str, int | None] = {}
try:
conn = sqlite3.connect(f"file:{path}?mode=ro", uri=True)
except sqlite3.DatabaseError:
return {t: None for t in TABLES}
for table in TABLES:
try:
counts[table] = conn.execute(f"SELECT COUNT(*) FROM {table}").fetchone()[0]
except sqlite3.DatabaseError:
counts[table] = None
conn.close()
return counts
def recover_with_cli(src: Path, dst: Path) -> bool:
"""sqlite3 命令行可用时用 .recover,最完整。"""
cli = shutil.which("sqlite3")
if not cli:
return False
proc = subprocess.run([cli, str(src), ".recover"], capture_output=True, text=True)
if proc.returncode != 0 or not proc.stdout.strip():
return False
dst.unlink(missing_ok=True)
out = sqlite3.connect(str(dst))
try:
out.executescript(proc.stdout)
out.commit()
except sqlite3.DatabaseError:
out.close()
return False
out.close()
return True
def recover_with_python(src: Path, dst: Path) -> tuple[bool, list[str]]:
"""兜底方案:只读打开坏库,逐表复制到新库。返回 (是否成功, 说明)。"""
notes: list[str] = []
try:
ro = sqlite3.connect(f"file:{src}?mode=ro&immutable=1", uri=True)
except sqlite3.DatabaseError as exc:
return False, [f"坏库打不开:{exc}"]
try:
master = ro.execute(
"SELECT type, name, sql FROM sqlite_master WHERE sql IS NOT NULL"
).fetchall()
except sqlite3.DatabaseError as exc:
ro.close()
return False, [f"连表结构都读不出来,无法恢复({exc}),只能删库重建。"]
dst.unlink(missing_ok=True)
out = sqlite3.connect(str(dst))
tables: list[str] = []
for typ, name, sql in master:
if name.startswith("sqlite_"):
continue
try:
out.execute(sql)
if typ == "table":
tables.append(name)
except sqlite3.DatabaseError as exc:
notes.append(f"跳过 {typ} {name}:{exc}")
out.commit()
for table in tables:
recovered = 0
truncated = False
try:
cur = ro.execute(f'SELECT * FROM "{table}"')
except sqlite3.DatabaseError as exc:
notes.append(f"表 {table} 无法读取:{exc}")
continue
cols = [d[0] for d in cur.description]
col_list = ",".join(f'"{c}"' for c in cols)
marks = ",".join("?" * len(cols))
insert = f'INSERT OR IGNORE INTO "{table}" ({col_list}) VALUES ({marks})'
while True:
try:
batch = cur.fetchmany(200)
except sqlite3.DatabaseError as exc:
notes.append(f"表 {table} 读取中断于第 {recovered} 行之后:{exc}")
truncated = True
break
if not batch:
break
try:
out.executemany(insert, batch)
out.commit()
recovered += len(batch)
except sqlite3.DatabaseError:
# 这一批里混着坏行,逐行抢救能救多少是多少
for row in batch:
try:
out.execute(insert, row)
recovered += 1
except sqlite3.DatabaseError:
pass
out.commit()
print(f" 表 {table}: 恢复 {recovered} 行" + ("(有缺失)" if truncated else ""))
out.commit()
out.close()
ro.close()
return True, notes
def main() -> int:
parser = argparse.ArgumentParser(description="WorkLog 数据库损坏检测与修复")
parser.add_argument("--db", help="数据库文件路径(默认 WORKLOG_DB / config.toml)")
parser.add_argument("--check", action="store_true", help="只检测,不修复")
parser.add_argument("--replace", action="store_true", help="修复成功后替换原库(坏库自动备份)")
parser.add_argument("-y", "--yes", action="store_true", help="跳过确认")
args = parser.parse_args()
db_path = resolve_db_path(args.db)
if not db_path.exists():
print(f"[!] 数据库不存在:{db_path}")
return 1
print(f"数据库:{db_path} ({db_path.stat().st_size / 1024:.0f} KB)")
for suffix in SIDE_SUFFIXES:
side = db_path.with_name(db_path.name + suffix)
if side.exists():
print(f" 注意:存在伴随文件 {side.name} ({side.stat().st_size / 1024:.0f} KB)")
healthy, report = integrity_report(db_path)
if healthy:
print("完整性检查:通过,数据库没有损坏。")
return 0
print(f"完整性检查:损坏({report})")
if args.check:
return 1
if not args.yes:
print("修复前请确认服务已停止(运行中的服务继续写坏库会越写越糟)。")
if input("输入 yes 继续: ").strip().lower() != "yes":
print("已取消。")
return 0
recovered_path = db_path.with_suffix(db_path.suffix + ".recovered")
notes: list[str] = []
if recover_with_cli(db_path, recovered_path):
print("已用 sqlite3 .recover 完成恢复。")
else:
print("sqlite3 命令行不可用,用逐表复制方式恢复……")
ok, notes = recover_with_python(db_path, recovered_path)
if not ok:
for line in notes:
print(f" {line}")
print("[!] 恢复失败。若数据不重要,删除该库重启服务即可重建空库。")
return 1
ok2, report2 = integrity_report(recovered_path)
print(f"修复库完整性:{'通过' if ok2 else '仍有问题(' + report2 + ')'}")
print("修复后各表行数:")
for table, count in table_counts(recovered_path).items():
print(f" {table:<20}{count if count is not None else '(表不存在)'}")
for line in notes:
print(f" 备注:{line}")
if args.replace:
stamp = datetime.now().strftime("%Y%m%d-%H%M%S")
corrupt_backup = db_path.with_name(f"{db_path.name}.corrupt-{stamp}")
db_path.rename(corrupt_backup)
for suffix in SIDE_SUFFIXES:
side = db_path.with_name(db_path.name + suffix)
if side.exists():
# 旧库的 wal/shm 绝不能留给新库用,一并挪走
side.rename(db_path.with_name(f"{db_path.name}{suffix}.corrupt-{stamp}"))
recovered_path.replace(db_path)
print(f"已替换。坏库保留在:{corrupt_backup}")
print("现在可以启动服务了(python -m server.main 或 bash start.sh)。")
else:
print(f"修复库在:{recovered_path}")
print("确认无误后手动替换:")
print(f" mv {db_path} {db_path}.corrupt && mv {recovered_path} {db_path}")
return 0
if __name__ == "__main__":
sys.exit(main())