#!/usr/bin/env python3 """WorkLog 数据库清除脚本(Windows / Linux 通用)。 用法: python clear_db.py 交互式选择清除范围 python clear_db.py --junk -y 只清过期会话、已用/过期验证码(安全,不动业务数据) python clear_db.py --activities -y 清空活动和参加记录(保留用户) python clear_db.py --all -y 清空全部业务数据(恢复初始状态) 可选参数: --db PATH 指定数据库文件(默认按 WORKLOG_DB / config.toml 的 database.path 解析) --no-backup 清除前不做备份(默认备份为 <库名>.bak-时间戳,放在同目录) -y, --yes 跳过确认 """ from __future__ import annotations import argparse import os import sqlite3 import sys import time from datetime import datetime from pathlib import Path PROJECT_DIR = Path(__file__).resolve().parent TABLES = ("users", "sessions", "email_verifications", "activities", "participations") # 每张表的固定 COUNT 语句(与 TABLES 一一对应,均为字面量) COUNT_SQL = { "users": 'SELECT COUNT(*) FROM users', "sessions": 'SELECT COUNT(*) FROM sessions', "email_verifications": 'SELECT COUNT(*) FROM email_verifications', "activities": 'SELECT COUNT(*) FROM activities', "participations": 'SELECT COUNT(*) FROM participations', } SCOPE_NAMES = { "junk": "只清理过期数据(过期会话、已用/过期验证码)", "activities": "清空活动数据(活动 + 参加记录,用户保留)", "all": "清空全部业务数据(用户、活动、会话、验证码,恢复初始状态)", } def resolve_db_path(explicit: str | None) -> Path: """与 server/main.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 table_counts(conn: sqlite3.Connection) -> dict[str, int | None]: counts: dict[str, int | None] = {} for table, sql in COUNT_SQL.items(): try: counts[table] = conn.execute(sql).fetchone()[0] except sqlite3.OperationalError: counts[table] = None return counts def build_plan(scope: str, now_ms: int): """返回 [(说明, DELETE 语句, 参数)]。all 必须先删子表再删父表,避免外键阻塞。""" if scope == "junk": return [ ("过期登录会话", "DELETE FROM sessions WHERE expires_at < ?", (now_ms,)), ( "已用/过期邮箱验证码", "DELETE FROM email_verifications WHERE used = 1 OR expires_at < ?", (now_ms,), ), ] if scope == "activities": return [ ("参加记录", "DELETE FROM participations", ()), ("活动", "DELETE FROM activities", ()), ] return [ ("参加记录", "DELETE FROM participations", ()), ("活动", "DELETE FROM activities", ()), ("登录会话", "DELETE FROM sessions", ()), ("邮箱验证码", "DELETE FROM email_verifications", ()), ("用户", "DELETE FROM users", ()), ] def main() -> int: parser = argparse.ArgumentParser(description="WorkLog 数据库清除脚本") group = parser.add_mutually_exclusive_group() group.add_argument("--junk", action="store_true", help="只清过期会话和已用/过期验证码") group.add_argument("--activities", action="store_true", help="清空活动与参加记录,保留用户") group.add_argument("--all", action="store_true", help="清空全部业务数据") parser.add_argument("--db", help="数据库文件路径(默认 WORKLOG_DB / config.toml)") parser.add_argument("--no-backup", action="store_true", help="清除前不备份") parser.add_argument("-y", "--yes", action="store_true", help="跳过确认") args = parser.parse_args() scope = ( "junk" if args.junk else "activities" if args.activities else "all" if args.all else None ) db_path = resolve_db_path(args.db) if not db_path.exists(): print(f"[!] 数据库不存在:{db_path}") return 1 conn = sqlite3.connect(str(db_path)) counts = table_counts(conn) print(f"数据库:{db_path} ({db_path.stat().st_size / 1024:.0f} KB)") print("当前数据:") for table in TABLES: value = counts[table] print(f" {table:<20}{value if value is not None else '(表不存在)'}") if scope is None: print("\n请选择清除范围:") print(" 1) 只清理过期数据(过期会话、已用/过期验证码)—— 安全") print(" 2) 清空活动数据(活动 + 参加记录,保留用户)") print(" 3) 清空全部数据(用户、活动、会话、验证码,恢复初始状态)") print(" 0) 取消") choice = input("请输入编号: ").strip() scope = {"1": "junk", "2": "activities", "3": "all"}.get(choice) if scope is None: print("已取消。") return 0 plan = build_plan(scope, int(time.time() * 1000)) print(f"\n即将执行:{SCOPE_NAMES[scope]}") for name, _, _ in plan: print(f" - 删除{name}") if scope != "junk": print("注意:清除后已登录用户会被强制下线,该操作不可撤销(有备份可恢复)。") if not args.yes: if input("输入 yes 继续: ").strip().lower() != "yes": print("已取消。") return 0 if not args.no_backup: stamp = datetime.now().strftime("%Y%m%d-%H%M%S") backup_path = db_path.with_name(f"{db_path.name}.bak-{stamp}") dest = sqlite3.connect(str(backup_path)) with dest: conn.backup(dest) dest.close() print(f"已备份到:{backup_path}") total = 0 try: with conn: for name, sql, params in plan: cursor = conn.execute(sql, params) print(f" 已删除{name}: {cursor.rowcount} 条") total += cursor.rowcount except sqlite3.OperationalError as exc: print(f"[!] 清除失败:{exc}") print(" 若提示表不存在,请先启动一次服务(python -m server.main)完成建表后再试。") conn.close() return 1 print(f"共删除 {total} 条记录。") try: conn.execute("PRAGMA wal_checkpoint(TRUNCATE)") conn.execute("VACUUM") print(f"完成(VACUUM 后 {db_path.stat().st_size / 1024:.0f} KB)。") except sqlite3.Error as exc: print(f"VACUUM 已跳过({exc}),不影响清除结果。") conn.close() return 0 if __name__ == "__main__": sys.exit(main())