Files
worklog/repair_db.py
T
azzz 5c4b8d84ed WorkLog 全量合并:密码登录体系、每日自动备份、发信日志、活动邮件通知一键参加
- 认证:注册设密码(双次确认,>=10 位)、密码/验证码双模式登录、邮箱验证码找回重置密码
- 备份:服务内置每天 23:00 自动备份到 data/backups/(默认保留 14 份),backup_db.py 支持手动/crontab
- 发信日志:logs/mail-YYYYMM.log 记录每次发信成败与失败原因(535 认证失败/断连细分),按月滚动保留 6 个月
- 通知:发起活动群发邮件(参与不发),邮件内一键参加(一次性令牌、7 天有效、私密活动不群发)
- 前端:报错细分(字段/类型/状态码全中文)、验证码按钮 60 秒防连点
- 部署:Dockerfile + entrypoint(seed 机制)、限流/唯一索引/令牌摘要等安全加固
- 工具:repair_db/clear_db 的 SQL 全部常量化,无动态拼接
- 测试:43 项全覆盖(注册/登录/活动/通知/备份/日志/安全)
2026-10-29 19:00:48 +08:00

285 lines
11 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
# 逐表复制用的 SQL 全部是固定字面量:SELECT/INSERT 语句、表名、列名均出自本常量表,
# 与 server/models.py 一一对应;行数据通过 ? 参数绑定传递,代码中不存在 SQL 拼接。
# 若新增表/列,需同步更新这里的语句与 server/models.py。
KNOWN_TABLES = ("users", "sessions", "email_verifications", "activities", "participations", "join_links", "auth_limits")
SIDE_SUFFIXES = ("-wal", "-shm", "-journal")
TABLE_SQL = {
"users": (
'SELECT * FROM "users"',
'INSERT OR IGNORE INTO "users" ("id","username","display_name","department","email","password_hash","phone","role","bio","created_at","last_login_at") VALUES (?,?,?,?,?,?,?,?,?,?,?)',
),
"sessions": (
'SELECT * FROM "sessions"',
'INSERT OR IGNORE INTO "sessions" ("token","user_id","created_at","expires_at") VALUES (?,?,?,?)',
),
"email_verifications": (
'SELECT * FROM "email_verifications"',
'INSERT OR IGNORE INTO "email_verifications" ("id","email","code","purpose","expires_at","used","created_at") VALUES (?,?,?,?,?,?,?)',
),
"activities": (
'SELECT * FROM "activities"',
'INSERT OR IGNORE INTO "activities" ("id","title","start_at","location","description","visibility","capacity","status","organizer_id","created_at","updated_at") VALUES (?,?,?,?,?,?,?,?,?,?,?)',
),
"participations": (
'SELECT * FROM "participations"',
'INSERT OR IGNORE INTO "participations" ("id","activity_id","user_id","role","status","note","joined_at","updated_at") VALUES (?,?,?,?,?,?,?,?)',
),
"join_links": (
'SELECT * FROM "join_links"',
'INSERT OR IGNORE INTO "join_links" ("id","token","activity_id","user_id","expires_at","used","created_at") VALUES (?,?,?,?,?,?,?)',
),
"auth_limits": (
'SELECT * FROM "auth_limits"',
'INSERT OR IGNORE INTO "auth_limits" ("key","window_start","count") VALUES (?,?,?)',
),
}
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 KNOWN_TABLES}
for table in KNOWN_TABLES:
try:
# TABLE_SQL[table][0] 为该表固定的 SELECT 字面量,包一层子查询做计数
counts[table] = conn.execute(
f"SELECT COUNT(*) FROM ({TABLE_SQL[table][0]})"
).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 KNOWN_TABLES:
if table not in tables:
notes.append(f"表 {table} 在坏库中不存在,跳过")
continue
select_sql, insert = TABLE_SQL[table]
recovered = 0
truncated = False
try:
cur = ro.execute(select_sql)
except sqlite3.DatabaseError as exc:
notes.append(f"表 {table} 无法读取:{exc}")
continue
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())