-- =============================================
-- 数据库迁移脚本：为 member_driver 表添加 id_card 字段
-- 用途：存储司机身份证前后面照片地址
-- 创建时间：2025-10-20
-- 数据库：MySQL
-- 版本：安全版本（包含错误处理）
-- =============================================

-- 开始事务
START TRANSACTION;

-- 检查表是否存在
SET @table_exists = (
    SELECT COUNT(*) 
    FROM INFORMATION_SCHEMA.TABLES 
    WHERE TABLE_SCHEMA = DATABASE() 
      AND TABLE_NAME = 'member_driver'
);

-- 如果表不存在，回滚并退出
IF @table_exists = 0 THEN
    ROLLBACK;
    SELECT 'ERROR: member_driver 表不存在' AS result;
    LEAVE;
END IF;

-- 检查字段是否已存在
SET @column_exists = (
    SELECT COUNT(*) 
    FROM INFORMATION_SCHEMA.COLUMNS 
    WHERE TABLE_SCHEMA = DATABASE() 
      AND TABLE_NAME = 'member_driver' 
      AND COLUMN_NAME = 'id_card'
);

-- 如果字段已存在，回滚并退出
IF @column_exists > 0 THEN
    ROLLBACK;
    SELECT 'WARNING: id_card 字段已存在，无需添加' AS result;
    LEAVE;
END IF;

-- 添加 id_card 字段
ALTER TABLE member_driver 
ADD COLUMN id_card TEXT COMMENT '身份证前后面照片地址（多个URL用逗号分隔）' 
AFTER car_img;

-- 验证字段是否添加成功
SET @verify_result = (
    SELECT COUNT(*) 
    FROM INFORMATION_SCHEMA.COLUMNS 
    WHERE TABLE_SCHEMA = DATABASE() 
      AND TABLE_NAME = 'member_driver' 
      AND COLUMN_NAME = 'id_card'
);

-- 如果验证失败，回滚
IF @verify_result = 0 THEN
    ROLLBACK;
    SELECT 'ERROR: id_card 字段添加失败' AS result;
    LEAVE;
END IF;

-- 提交事务
COMMIT;

-- 显示成功信息
SELECT 'SUCCESS: id_card 字段添加成功' AS result;

-- 显示字段信息
SELECT 
    COLUMN_NAME as '字段名',
    DATA_TYPE as '数据类型',
    IS_NULLABLE as '允许空值',
    COLUMN_DEFAULT as '默认值',
    COLUMN_COMMENT as '注释'
FROM INFORMATION_SCHEMA.COLUMNS 
WHERE TABLE_SCHEMA = DATABASE() 
  AND TABLE_NAME = 'member_driver' 
  AND COLUMN_NAME = 'id_card';
