schema_patch.py 13.5 KB
from __future__ import annotations

from sqlalchemy import text


def _rebuild_official_site_agent_display_without_unique(conn) -> None:
    conn.execute(text("PRAGMA foreign_keys=OFF"))
    conn.execute(
        text(
            """
            CREATE TABLE IF NOT EXISTS official_site_agent_display_new (
                id INTEGER PRIMARY KEY,
                tab_id INTEGER NOT NULL,
                agent_id INTEGER NOT NULL,
                agent_name VARCHAR(50) NOT NULL DEFAULT '',
                status VARCHAR(20) NOT NULL DEFAULT 'enable',
                summary VARCHAR(500),
                icon_url VARCHAR(500),
                media_url VARCHAR(500),
                media_type VARCHAR(10),
                speech_title VARCHAR(100),
                speech_content VARCHAR(200),
                display_status VARCHAR(20) NOT NULL DEFAULT 'enable',
                sort_order INTEGER NOT NULL DEFAULT 0,
                created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
                updated_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL
            )
            """
        )
    )
    conn.execute(
        text(
            """
            INSERT INTO official_site_agent_display_new (
                id,
                tab_id,
                agent_id,
                agent_name,
                status,
                summary,
                icon_url,
                media_url,
                media_type,
                speech_title,
                speech_content,
                display_status,
                sort_order,
                created_at,
                updated_at
            )
            SELECT
                id,
                tab_id,
                agent_id,
                COALESCE(agent_name, ''),
                COALESCE(status, 'enable'),
                summary,
                icon_url,
                media_url,
                media_type,
                speech_title,
                speech_content,
                COALESCE(display_status, 'enable'),
                COALESCE(sort_order, 0),
                created_at,
                updated_at
            FROM official_site_agent_display
            """
        )
    )
    conn.execute(text("DROP TABLE official_site_agent_display"))
    conn.execute(text("ALTER TABLE official_site_agent_display_new RENAME TO official_site_agent_display"))
    conn.execute(text("CREATE INDEX IF NOT EXISTS ix_official_site_agent_display_tab_id ON official_site_agent_display(tab_id)"))
    conn.execute(text("CREATE INDEX IF NOT EXISTS ix_official_site_agent_display_agent_id ON official_site_agent_display(agent_id)"))
    conn.execute(text("CREATE INDEX IF NOT EXISTS ix_official_site_agent_display_display_status ON official_site_agent_display(display_status)"))
    conn.execute(text("CREATE INDEX IF NOT EXISTS ix_official_site_agent_display_sort_order ON official_site_agent_display(sort_order)"))
    conn.execute(text("CREATE INDEX IF NOT EXISTS idx_osad_status ON official_site_agent_display(status)"))
    conn.execute(text("PRAGMA foreign_keys=ON"))


def ensure_runtime_schema(engine) -> None:
    if not str(engine.url).startswith("sqlite"):
        return

    with engine.begin() as conn:
        table_names = {
            row[0]
            for row in conn.execute(text("SELECT name FROM sqlite_master WHERE type='table'"))
        }

        if "wecom_customer_position_groups" in table_names:
            conn.execute(text("DROP TABLE wecom_customer_position_groups"))
            table_names.remove("wecom_customer_position_groups")

        if "wecom_groups" in table_names:
            conn.execute(text("DROP TABLE wecom_groups"))
            table_names.remove("wecom_groups")

        if "wecom_job_configs" not in table_names:
            conn.execute(
                text(
                    """
                    CREATE TABLE wecom_job_configs (
                        id INTEGER PRIMARY KEY,
                        job_key VARCHAR(64) NOT NULL UNIQUE,
                        enabled BOOLEAN NOT NULL DEFAULT 1,
                        last_run_at DATETIME,
                        last_status VARCHAR(32),
                        last_error TEXT,
                        created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
                        updated_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL
                    )
                    """
                )
            )

        if "wecom_group_create_requests" not in table_names:
            conn.execute(
                text(
                    """
                    CREATE TABLE wecom_group_create_requests (
                        id INTEGER PRIMARY KEY,
                        biz_rela_no VARCHAR(191) NOT NULL UNIQUE,
                        bot_id VARCHAR(128) NOT NULL,
                        bot_code VARCHAR(191) NOT NULL,
                        customer_contact_id VARCHAR(191) NOT NULL,
                        customer_name VARCHAR(255),
                        qrcode_id INTEGER NOT NULL,
                        qrcode_name VARCHAR(255),
                        channel_code VARCHAR(100) NOT NULL,
                        position_id INTEGER NOT NULL,
                        position_code VARCHAR(100) NOT NULL,
                        position_name VARCHAR(255) NOT NULL,
                        group_name VARCHAR(255) NOT NULL,
                        member_bot_ids JSON NOT NULL,
                        member_snapshot JSON,
                        request_payload JSON,
                        submit_result JSON,
                        task_id VARCHAR(191),
                        status VARCHAR(32) NOT NULL DEFAULT 'pending',
                        fail_reason TEXT,
                        resolved_group_contact_id VARCHAR(191),
                        resolved_group_name VARCHAR(255),
                        resolved_contact_type VARCHAR(64),
                        external_result JSON,
                        resolved_at DATETIME,
                        created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
                        updated_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL
                    )
                    """
                )
            )
            conn.execute(text("CREATE INDEX idx_wgcr_status ON wecom_group_create_requests(status)"))
            conn.execute(text("CREATE INDEX idx_wgcr_bot ON wecom_group_create_requests(bot_id)"))
            conn.execute(text("CREATE INDEX idx_wgcr_customer ON wecom_group_create_requests(customer_contact_id)"))
            conn.execute(text("CREATE INDEX idx_wgcr_task_id ON wecom_group_create_requests(task_id)"))
            conn.execute(text("CREATE INDEX idx_wgcr_resolved_group ON wecom_group_create_requests(resolved_group_contact_id)"))
        else:
            group_create_columns = {
                row[1]
                for row in conn.execute(text("PRAGMA table_info(wecom_group_create_requests)"))
            }
            if "submit_result" not in group_create_columns:
                conn.execute(
                    text("ALTER TABLE wecom_group_create_requests ADD COLUMN submit_result JSON")
                )

        if "wecom_customer_groups" not in table_names:
            conn.execute(
                text(
                    """
                    CREATE TABLE wecom_customer_groups (
                        id INTEGER PRIMARY KEY,
                        customer_contact_id VARCHAR(191) NOT NULL UNIQUE,
                        customer_name VARCHAR(255),
                        bot_id VARCHAR(128) NOT NULL,
                        bot_code VARCHAR(191) NOT NULL,
                        group_id VARCHAR(191),
                        group_name VARCHAR(255),
                        group_status VARCHAR(32) NOT NULL DEFAULT 'pending',
                        group_create_request_id INTEGER,
                        member_bot_ids JSON NOT NULL,
                        is_deleted BOOLEAN NOT NULL DEFAULT 0,
                        created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
                        updated_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL
                    )
                    """
                )
            )
            conn.execute(text("CREATE INDEX ix_wecom_customer_groups_customer_contact_id ON wecom_customer_groups(customer_contact_id)"))
            conn.execute(text("CREATE INDEX ix_wecom_customer_groups_bot_id ON wecom_customer_groups(bot_id)"))
            conn.execute(text("CREATE INDEX ix_wecom_customer_groups_bot_code ON wecom_customer_groups(bot_code)"))
            conn.execute(text("CREATE INDEX ix_wecom_customer_groups_group_id ON wecom_customer_groups(group_id)"))
            conn.execute(text("CREATE INDEX ix_wecom_customer_groups_group_status ON wecom_customer_groups(group_status)"))
            conn.execute(text("CREATE INDEX ix_wecom_customer_groups_group_create_request_id ON wecom_customer_groups(group_create_request_id)"))
            conn.execute(text("CREATE INDEX ix_wecom_customer_groups_is_deleted ON wecom_customer_groups(is_deleted)"))

        if "wecom_messages" in table_names:
            wecom_message_columns = {
                row[1]
                for row in conn.execute(text("PRAGMA table_info(wecom_messages)"))
            }
            if "customer_group_id" not in wecom_message_columns:
                conn.execute(
                    text("ALTER TABLE wecom_messages ADD COLUMN customer_group_id INTEGER")
                )
                conn.execute(
                    text(
                        "CREATE INDEX IF NOT EXISTS ix_wecom_messages_customer_group_id "
                        "ON wecom_messages(customer_group_id)"
                    )
                )

        if "official_tabs" in table_names:
            official_tab_columns = {
                row[1]
                for row in conn.execute(text("PRAGMA table_info(official_tabs)"))
            }

            if "main_title" not in official_tab_columns:
                conn.execute(
                    text("ALTER TABLE official_tabs ADD COLUMN main_title VARCHAR(200)")
                )

            if "sub_title" not in official_tab_columns:
                conn.execute(
                    text("ALTER TABLE official_tabs ADD COLUMN sub_title VARCHAR(500)")
                )

        if "ai_agents" in table_names:
            ai_agent_columns = {
                row[1]
                for row in conn.execute(text("PRAGMA table_info(ai_agents)"))
            }

            if "managed_user_id" not in ai_agent_columns:
                conn.execute(
                    text("ALTER TABLE ai_agents ADD COLUMN managed_user_id INTEGER")
                )
                conn.execute(
                    text(
                        "CREATE INDEX IF NOT EXISTS ix_ai_agents_managed_user_id "
                        "ON ai_agents(managed_user_id)"
                    )
                )

            if "is_steward" not in ai_agent_columns:
                conn.execute(
                    text(
                        "ALTER TABLE ai_agents ADD COLUMN is_steward "
                        "BOOLEAN NOT NULL DEFAULT 0"
                    )
                )

        if "official_site_agent_display" in table_names:
            display_columns = {
                row[1]
                for row in conn.execute(text("PRAGMA table_info(official_site_agent_display)"))
            }
            display_table_sql = conn.execute(
                text("SELECT sql FROM sqlite_master WHERE type='table' AND name='official_site_agent_display'")
            ).scalar() or ""
            if "UNIQUE (tab_id, agent_id)" in display_table_sql or "UNIQUE(tab_id, agent_id)" in display_table_sql:
                _rebuild_official_site_agent_display_without_unique(conn)
                display_columns = {
                    row[1]
                    for row in conn.execute(text("PRAGMA table_info(official_site_agent_display)"))
                }

            if "agent_name" not in display_columns:
                conn.execute(
                    text("ALTER TABLE official_site_agent_display ADD COLUMN agent_name VARCHAR(50) NOT NULL DEFAULT ''")
                )

            if "status" not in display_columns:
                conn.execute(
                    text("ALTER TABLE official_site_agent_display ADD COLUMN status VARCHAR(20) NOT NULL DEFAULT 'enable'")
                )
                conn.execute(
                    text("CREATE INDEX IF NOT EXISTS idx_osad_status ON official_site_agent_display(status)")
                )

            if "summary" not in display_columns:
                conn.execute(
                    text("ALTER TABLE official_site_agent_display ADD COLUMN summary VARCHAR(500)")
                )

            if "icon_url" not in display_columns:
                conn.execute(
                    text("ALTER TABLE official_site_agent_display ADD COLUMN icon_url VARCHAR(500)")
                )

            if "media_url" not in display_columns:
                conn.execute(
                    text("ALTER TABLE official_site_agent_display ADD COLUMN media_url VARCHAR(500)")
                )

            if "media_type" not in display_columns:
                conn.execute(
                    text("ALTER TABLE official_site_agent_display ADD COLUMN media_type VARCHAR(10)")
                )

            if "speech_title" not in display_columns:
                conn.execute(
                    text("ALTER TABLE official_site_agent_display ADD COLUMN speech_title VARCHAR(100)")
                )

            if "speech_content" not in display_columns:
                conn.execute(
                    text("ALTER TABLE official_site_agent_display ADD COLUMN speech_content VARCHAR(200)")
                )