schema_sync.py 2.87 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', '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