schema_sync.py
1.45 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
"""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')")
)
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")
_synced = True