"""添加 task_id 字段到 Task 表

Revision ID: 001
Revises: 
Create Date: 2023-07-01

"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy import text
import uuid
from sqlalchemy.engine import reflection
import sys
import os
from pathlib import Path

# 添加 migrations 目录到 Python 路径
sys.path.insert(0, str(Path(__file__).parent.parent))

# 导入迁移辅助模块
from migration_helpers import (
    safe_add_column, 
    safe_create_index, 
    safe_alter_column,
    generate_uuid_for_null_values,
    safe_drop_index,
    safe_drop_column
)

# revision identifiers, used by Alembic.
revision = '001'
down_revision = None
branch_labels = None
depends_on = None


def upgrade():
    # 添加 task_id 字段到 Task 表
    if safe_add_column('tasks', 'task_id', sa.String(36), nullable=True, comment='任务UUID，用于外部引用'):
        # 为已有记录生成 UUID
        generate_uuid_for_null_values('tasks', 'task_id')
    
    # 添加唯一索引
    safe_create_index('ix_tasks_task_id', 'tasks', ['task_id'], unique=True)
    
    # 添加非空约束
    safe_alter_column('tasks', 'task_id', nullable=False, existing_type=sa.String(36))


def downgrade():
    # 删除索引
    safe_drop_index('ix_tasks_task_id', 'tasks')
    
    # 删除列
    safe_drop_column('tasks', 'task_id') 