wipe_all.py
3.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
"""整库清空:把系统恢复成一个干净环境(只清数据,不删表结构)。
会清空:元数据库里所有 otlg_* 表的行(本体、数据源、文档、流程卡、动作、审批、
对话、审计、评测、调用日志……),以及本地的知识图谱、向量索引、上传文件、LLM 缓存。
保留:用户(otlg_user)、业务角色(otlg_biz_role)、运行设置(otlg_config),
以及伪业务表 otlg_dm_* / otlg_dm2_*(它们是「业务库」,不是系统数据)。
注意:审计日志平时只追加、永不删除;这个脚本会连它一起清掉,只用于重置演示环境。
./.venv/Scripts/python.exe scripts/wipe_all.py # 只打印各表行数
./.venv/Scripts/python.exe scripts/wipe_all.py --yes # 真的清空
"""
from __future__ import annotations
import argparse
import shutil
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))
sys.stdout.reconfigure(encoding="utf-8")
KEEP = {"otlg_user", "otlg_biz_role", "otlg_config", "otlg_demo_env"}
BUSINESS_PREFIX = ("otlg_dm_", "otlg_dm2_")
LOCAL_FILES = ["index", "uploads", "cache/llm", "graph.json", "communities.json", "sop.json"]
def _tables(conn) -> list[str]:
from sqlalchemy import inspect
names = inspect(conn).get_table_names()
return sorted(n for n in names
if n.startswith("otlg_")
and not n.startswith(BUSINESS_PREFIX) and n not in KEEP)
def _counts(conn, tables: list[str]) -> dict[str, int]:
from sqlalchemy import text
return {t: conn.execute(text(f"SELECT COUNT(*) FROM `{t}`")).scalar() or 0 for t in tables}
def main() -> None:
ap = argparse.ArgumentParser(description="整库清空")
ap.add_argument("--yes", action="store_true", help="确认清空")
args = ap.parse_args()
from sqlalchemy import text
from app.core import db as core_db
from app.core.config import get_settings
core_db.init_db()
with core_db.engine.begin() as conn:
tables = _tables(conn)
before = _counts(conn, tables)
total = sum(before.values())
print(f"待清空 {len(tables)} 张表,共 {total} 行:")
for t, n in before.items():
if n:
print(f" {t:32s} {n}")
if not args.yes:
print("\n只做了统计。确认清空请加 --yes(审计日志也会被清掉)。")
return
with core_db.engine.begin() as conn:
conn.execute(text("SET FOREIGN_KEY_CHECKS=0"))
for t in tables:
conn.execute(text(f"DELETE FROM `{t}`"))
conn.execute(text("SET FOREIGN_KEY_CHECKS=1"))
left = sum(_counts(conn, tables).values())
print(f"\n数据库已清空:删除 {total} 行,剩余 {left} 行")
data = get_settings().data_path
for rel in LOCAL_FILES:
p = data / rel
if p.is_dir():
shutil.rmtree(p, ignore_errors=True)
p.mkdir(parents=True, exist_ok=True)
elif p.exists():
p.unlink()
for log in data.glob("*.log"):
try:
log.unlink(missing_ok=True)
except PermissionError: # 正在运行的服务占着日志文件:清空内容即可
log.write_text("", encoding="utf-8")
print(f"本地文件已清空:{data.resolve()}({', '.join(LOCAL_FILES)}、*.log)")
if __name__ == "__main__":
main()