"""add_pg_trgm_indexes

为 title / abstract / journal 的 ILIKE 搜索添加 pg_trgm GIN 索引。
避免高频全表扫描（对照 tsvector 未覆盖的中文/精确短语搜索兜底路径）。

Revision ID: 3f0ba5a7a28c
Revises: fd8a420af4e4
Create Date: 2026-07-12 22:33:09.834437
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa


revision: str = '3f0ba5a7a28c'
down_revision: Union[str, None] = 'fd8a420af4e4'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    # pg_trgm 扩展（幂等）
    op.execute("CREATE EXTENSION IF NOT EXISTS pg_trgm")

    # title 与 abstract 的 GIN trgm 索引——覆盖 ILIKE '%term%' 兜底搜索
    # 用 op.create_index 的 postgresql_ops 参数指定 gin_trgm_ops
    op.create_index(
        "ix_global_literature_title_trgm",
        "global_literature",
        ["title"],
        postgresql_using="gin",
        postgresql_ops={"title": "gin_trgm_ops"},
    )
    op.create_index(
        "ix_global_literature_abstract_trgm",
        "global_literature",
        ["abstract"],
        postgresql_using="gin",
        postgresql_ops={"abstract": "gin_trgm_ops"},
    )
    # journal ILIKE 搜索（`field="journal"` 无 tsvector 兜底，全表扫描风险高）
    op.create_index(
        "ix_global_literature_journal_trgm",
        "global_literature",
        ["journal"],
        postgresql_using="gin",
        postgresql_ops={"journal": "gin_trgm_ops"},
    )


def downgrade() -> None:
    op.drop_index("ix_global_literature_title_trgm")
    op.drop_index("ix_global_literature_abstract_trgm")
    op.drop_index("ix_global_literature_journal_trgm")
    # 不删 pg_trgm extension（不影响，其他表可能也在用）
