schema_sync.py 1.45 KB
"""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