schema_sync.py
2.87 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
"""Lightweight schema sync for existing wiki database tables."""
import logging
from sqlalchemy import text
from src.database.session import engine
logger = logging.getLogger(__name__)
_synced = False
async def ensure_wiki_schema() -> None:
"""Add backward-compatible wiki_files columns that create_all cannot add."""
global _synced
if _synced:
return
async with engine.begin() as conn:
result = await conn.execute(
text(
"SHOW COLUMNS FROM wiki_files WHERE Field IN "
"('input_tokens', 'output_tokens', 'vlm_total_tokens', "
"'cached_input_tokens', 'ingest_mode')"
)
)
existing = {row[0] for row in result}
if "input_tokens" not in existing:
await conn.execute(
text(
"ALTER TABLE wiki_files "
"ADD COLUMN input_tokens INT NOT NULL DEFAULT 0 "
"COMMENT 'Input LLM tokens consumed by ingestion' "
"AFTER status"
)
)
logger.info("[WikiSchema] Added wiki_files.input_tokens")
if "output_tokens" not in existing:
await conn.execute(
text(
"ALTER TABLE wiki_files "
"ADD COLUMN output_tokens INT NOT NULL DEFAULT 0 "
"COMMENT 'Output LLM tokens consumed by ingestion' "
"AFTER input_tokens"
)
)
logger.info("[WikiSchema] Added wiki_files.output_tokens")
if "vlm_total_tokens" not in existing:
await conn.execute(
text(
"ALTER TABLE wiki_files "
"ADD COLUMN vlm_total_tokens INT NOT NULL DEFAULT 0 "
"COMMENT 'VLM tokens consumed while parsing PDF/PPT' "
"AFTER output_tokens"
)
)
logger.info("[WikiSchema] Added wiki_files.vlm_total_tokens")
if "cached_input_tokens" not in existing:
await conn.execute(
text(
"ALTER TABLE wiki_files "
"ADD COLUMN cached_input_tokens INT NOT NULL DEFAULT 0 "
"COMMENT 'Cached input tokens hit during ingestion' "
"AFTER total_tokens"
)
)
logger.info("[WikiSchema] Added wiki_files.cached_input_tokens")
if "ingest_mode" not in existing:
await conn.execute(
text(
"ALTER TABLE wiki_files "
"ADD COLUMN ingest_mode VARCHAR(32) NULL "
"COMMENT 'Ingest route: 3-phase or 3-phase-chunked' "
"AFTER vlm_total_tokens"
)
)
logger.info("[WikiSchema] Added wiki_files.ingest_mode")
_synced = True