"""add composite index (status, created_at) on comparison_record

首页轮播 feed(按 status='success' 过滤 + created_at 近期排序)与省钱战绩聚合
都吃这个过滤+排序;复合索引避免随数据量增大退化成全表扫。

Revision ID: comparison_status_created_idx
Revises: a8c47fc4dc39
Create Date: 2026-06-10
"""

from __future__ import annotations

from alembic import op

revision = "comparison_status_created_idx"
down_revision = "a8c47fc4dc39"
branch_labels = None
depends_on = None

INDEX_NAME = "ix_comparison_status_created"


def upgrade() -> None:
    bind = op.get_bind()
    if bind.dialect.name == "postgresql":
        # PG 上 comparison_record 已有数据量, 普通 CREATE INDEX 持表写锁会阻塞线上写入;
        # 用 CONCURRENTLY 不锁表(须脱离事务, autocommit_block 切到自动提交)。
        with op.get_context().autocommit_block():
            op.create_index(
                INDEX_NAME, "comparison_record", ["status", "created_at"],
                unique=False, postgresql_concurrently=True,
            )
    else:
        op.create_index(
            INDEX_NAME, "comparison_record", ["status", "created_at"], unique=False
        )


def downgrade() -> None:
    bind = op.get_bind()
    if bind.dialect.name == "postgresql":
        with op.get_context().autocommit_block():
            op.drop_index(
                INDEX_NAME, table_name="comparison_record",
                postgresql_concurrently=True,
            )
    else:
        op.drop_index(INDEX_NAME, table_name="comparison_record")
