schema_sync.py
5.04 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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
"""Lightweight schema sync for existing wiki database tables.
`Base.metadata.create_all` 只能创建缺失的表,无法为**已存在**的表补列。
本模块在服务启动时(create_all 之后)以幂等方式补齐这些列。
新增列时只需往下方的表驱动清单里追加一项即可。注意清单顺序有意义:
DDL 中的 `AFTER xxx` 可能引用同一批里前面刚加的列。
"""
import logging
from sqlalchemy import text
from src.database.session import engine
logger = logging.getLogger(__name__)
_synced = False
# 既有列的 DDL 保持原样(英文注释),避免改动历史行为;新增列统一使用中文注释。
_COLUMN_SPECS: dict[str, list[tuple[str, str]]] = {
"wiki_files": [
(
"input_tokens",
"ADD COLUMN input_tokens INT NOT NULL DEFAULT 0 "
"COMMENT 'Input LLM tokens consumed by ingestion' AFTER status",
),
(
"output_tokens",
"ADD COLUMN output_tokens INT NOT NULL DEFAULT 0 "
"COMMENT 'Output LLM tokens consumed by ingestion' AFTER input_tokens",
),
(
"vlm_total_tokens",
"ADD COLUMN vlm_total_tokens INT NOT NULL DEFAULT 0 "
"COMMENT 'VLM tokens consumed while parsing PDF/PPT' AFTER output_tokens",
),
(
"cached_input_tokens",
"ADD COLUMN cached_input_tokens INT NOT NULL DEFAULT 0 "
"COMMENT 'Cached input tokens hit during ingestion' AFTER total_tokens",
),
(
"ingest_mode",
"ADD COLUMN ingest_mode VARCHAR(32) NULL "
"COMMENT 'Ingest route: 3-phase or 3-phase-chunked' AFTER vlm_total_tokens",
),
],
# 智能化模块:把 wiki_query_logs 升级为覆盖「前端会话 + 外部无状态接口」的全量审计表
"wiki_query_logs": [
(
"user_id",
"ADD COLUMN user_id CHAR(36) NULL "
"COMMENT '归属用户 ID,外部无状态调用为 NULL' AFTER session_id",
),
(
"source",
"ADD COLUMN source VARCHAR(20) NOT NULL DEFAULT 'web' "
"COMMENT '调用来源:web=前端会话 / api=外部接口' AFTER user_id",
),
(
"client_ip",
"ADD COLUMN client_ip VARCHAR(45) NULL "
"COMMENT '调用方 IP(兼容 IPv6),外部接口开放后的追责依据' AFTER source",
),
(
"tool_calls_json",
"ADD COLUMN tool_calls_json TEXT NULL "
"COMMENT '工具调用极简轨迹 JSON:工具名/目标文件/成功与否,不含返回正文' AFTER answer_text",
),
(
"input_tokens",
"ADD COLUMN input_tokens INT NOT NULL DEFAULT 0 "
"COMMENT '输入 token 数' AFTER total_tokens",
),
(
"output_tokens",
"ADD COLUMN output_tokens INT NOT NULL DEFAULT 0 "
"COMMENT '输出 token 数' AFTER input_tokens",
),
(
"cached_input_tokens",
"ADD COLUMN cached_input_tokens INT NOT NULL DEFAULT 0 "
"COMMENT '命中上下文缓存的 input token 数(⊆ input_tokens),用于观测前缀缓存命中率' "
"AFTER output_tokens",
),
],
}
# 需要补建的索引:(表名, 索引名, 建索引 DDL 片段)
_INDEX_SPECS: list[tuple[str, str, str]] = [
(
"wiki_query_logs",
"idx_wiki_query_logs_user_created",
"ADD INDEX idx_wiki_query_logs_user_created (user_id, created_at)",
),
]
async def _ensure_columns(conn, table: str, specs: list[tuple[str, str]]) -> None:
"""按清单为单张表补齐缺失的列,已存在的列自动跳过。"""
if not specs:
return
field_list = ", ".join(f"'{name}'" for name, _ in specs)
result = await conn.execute(
text(f"SHOW COLUMNS FROM {table} WHERE Field IN ({field_list})")
)
existing = {row[0] for row in result}
for name, ddl in specs:
if name in existing:
continue
await conn.execute(text(f"ALTER TABLE {table} {ddl}"))
logger.info("[WikiSchema] Added %s.%s", table, name)
async def _ensure_index(conn, table: str, index_name: str, ddl: str) -> None:
"""补建缺失的索引,已存在则跳过。"""
result = await conn.execute(
text(f"SHOW INDEX FROM {table} WHERE Key_name = '{index_name}'")
)
if result.first() is not None:
return
await conn.execute(text(f"ALTER TABLE {table} {ddl}"))
logger.info("[WikiSchema] Added index %s on %s", index_name, table)
async def ensure_wiki_schema() -> None:
"""补齐 create_all 无法添加的向后兼容列与索引(幂等,进程内只跑一次)。"""
global _synced
if _synced:
return
async with engine.begin() as conn:
for table, specs in _COLUMN_SPECS.items():
await _ensure_columns(conn, table, specs)
for table, index_name, ddl in _INDEX_SPECS:
await _ensure_index(conn, table, index_name, ddl)
_synced = True