-- 修复 exit_order_id 唯一约束问题
-- 问题：exit_order_id 有 UNIQUE 约束，但在状态同步时，同一个订单可能被多次更新，导致重复键错误
-- 解决方案：移除 UNIQUE 约束，保留索引以便快速查询

USE `auto_trade_sys`;

-- 1. 删除唯一约束（如果存在）
-- 注意：MySQL 中，如果字段有 UNIQUE 约束，删除索引会同时删除唯一约束
-- 先检查是否存在唯一索引
SET @index_exists = (
    SELECT COUNT(*) 
    FROM information_schema.statistics 
    WHERE table_schema = 'auto_trade_sys' 
    AND table_name = 'trades' 
    AND index_name = 'exit_order_id'
    AND non_unique = 0
);

-- 如果存在唯一索引，删除它
SET @sql = IF(@index_exists > 0, 
    'ALTER TABLE `trades` DROP INDEX `exit_order_id`', 
    'SELECT "exit_order_id 唯一索引不存在，跳过删除" as message'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

-- 2. 重新添加普通索引（非唯一）
-- 先检查是否已存在普通索引
SET @normal_index_exists = (
    SELECT COUNT(*) 
    FROM information_schema.statistics 
    WHERE table_schema = 'auto_trade_sys' 
    AND table_name = 'trades' 
    AND index_name = 'idx_exit_order_id'
);

-- 如果不存在普通索引，添加它
SET @sql2 = IF(@normal_index_exists = 0, 
    'ALTER TABLE `trades` ADD INDEX `idx_exit_order_id` (`exit_order_id`)', 
    'SELECT "idx_exit_order_id 索引已存在，跳过添加" as message'
);
PREPARE stmt2 FROM @sql2;
EXECUTE stmt2;
DEALLOCATE PREPARE stmt2;

-- 验证：检查表结构
-- SHOW CREATE TABLE `trades`;
-- 或者
-- SHOW INDEX FROM `trades` WHERE Column_name = 'exit_order_id';
