"""add_unique_constraints_to_global_journals

Revision ID: 5bb112b00290
Revises: d4eaf8b152c0
Create Date: 2026-07-14 10:11:27.461192
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa


revision: str = '5bb112b00290'
down_revision: Union[str, None] = 'd4eaf8b152c0'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    # 先将空字符串 issn 转为 NULL（PG unique 约束允许 NULL 重复但禁止 '' 重复）
    op.execute("UPDATE global_journals SET issn = NULL WHERE issn = ''")
    # 清理 name 中可能的前后空白
    op.execute("UPDATE global_journals SET name = TRIM(name) WHERE name != TRIM(name)")
    # 添加唯一约束
    op.create_unique_constraint('uq_gj_issn', 'global_journals', ['issn'])
    op.create_unique_constraint('uq_gj_name', 'global_journals', ['name'])


def downgrade() -> None:
    op.drop_constraint('uq_gj_issn', 'global_journals', type_='unique')
    op.drop_constraint('uq_gj_name', 'global_journals', type_='unique')
