#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
添加 exam.visibility 字段的数据库迁移脚本
"""

from app import app, db
from models import Exam

def add_visibility_column():
    """为 Exam 表添加 visibility 字段"""
    with app.app_context():
        try:
            # 检查字段是否已存在
            inspector = db.inspect(db.engine)
            columns = [col['name'] for col in inspector.get_columns('exam')]

            if 'visibility' in columns:
                print("visibility 字段已存在，无需添加")
                return

            # 添加字段
            with db.engine.connect() as conn:
                conn.execute(db.text("ALTER TABLE exam ADD COLUMN visibility VARCHAR(20) DEFAULT 'private'"))
                conn.commit()
                print("成功添加 visibility 字段")

                # 将所有现有考试设置为公开（保持向后兼容）
                conn.execute(db.text("UPDATE exam SET visibility = 'public' WHERE visibility IS NULL"))
                conn.commit()
                print("已将现有考试设置为公开")

        except Exception as e:
            print(f"添加字段时出错: {e}")
            raise

if __name__ == '__main__':
    print("开始添加 visibility 字段...")
    add_visibility_column()
    print("完成！")
