-- 给 order_items 添加 spec_snapshot 字段，用于保存付款时的规格数据快照
ALTER TABLE order_items ADD COLUMN spec_snapshot JSON DEFAULT NULL;

-- 去掉 order_items 的 spec_data_id 外键约束（避免删除 spec_data 时级联删除订单商品）
-- 先查找并删除外键
SET @fk_name = (
  SELECT CONSTRAINT_NAME FROM information_schema.KEY_COLUMN_USAGE
  WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'order_items'
  AND COLUMN_NAME = 'spec_data_id' AND REFERENCED_TABLE_NAME = 'spec_data'
  LIMIT 1
);
SET @sql = IF(@fk_name IS NOT NULL, CONCAT('ALTER TABLE order_items DROP FOREIGN KEY ', @fk_name), 'SELECT 1');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

-- 去掉 cart_items 的 spec_data_id 外键约束
SET @fk_name2 = (
  SELECT CONSTRAINT_NAME FROM information_schema.KEY_COLUMN_USAGE
  WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'cart_items'
  AND COLUMN_NAME = 'spec_data_id' AND REFERENCED_TABLE_NAME = 'spec_data'
  LIMIT 1
);
SET @sql2 = IF(@fk_name2 IS NOT NULL, CONCAT('ALTER TABLE cart_items DROP FOREIGN KEY ', @fk_name2), 'SELECT 1');
PREPARE stmt2 FROM @sql2;
EXECUTE stmt2;
DEALLOCATE PREPARE stmt2;
