fix(migration): 提升 000070 与 000071 迁移幂等性,兼容已存在的索引与字段

This commit is contained in:
yml2213
2026-09-08 13:20:50 +08:00
parent 044b141e95
commit d178619fc7
2 changed files with 189 additions and 33 deletions
@@ -1,9 +1,23 @@
-- +goose Up
-- 1. notifications 表新增 distribution_site_id 并添加联合索引
ALTER TABLE notifications
ADD COLUMN distribution_site_id BIGINT UNSIGNED NULL AFTER biz_id,
ADD KEY idx_notifications_user_site (user_id, distribution_site_id, id);
SET @sql = IF(
(SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'notifications' AND COLUMN_NAME = 'distribution_site_id') = 0,
'ALTER TABLE notifications ADD COLUMN distribution_site_id BIGINT UNSIGNED NULL AFTER biz_id',
'SELECT 1'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET @sql = IF(
(SELECT COUNT(*) FROM information_schema.STATISTICS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'notifications' AND INDEX_NAME = 'idx_notifications_user_site') = 0,
'ALTER TABLE notifications ADD KEY idx_notifications_user_site (user_id, distribution_site_id, id)',
'SELECT 1'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
-- 2. 回填历史分销订单的站内信通知归属
UPDATE notifications n
@@ -13,6 +27,20 @@ WHERE n.biz_type = 'order' AND o.distribution_site_id IS NOT NULL AND o.distribu
-- +goose Down
ALTER TABLE notifications
DROP KEY idx_notifications_user_site,
DROP COLUMN distribution_site_id;
SET @sql = IF(
(SELECT COUNT(*) FROM information_schema.STATISTICS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'notifications' AND INDEX_NAME = 'idx_notifications_user_site') > 0,
'ALTER TABLE notifications DROP KEY idx_notifications_user_site',
'SELECT 1'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET @sql = IF(
(SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'notifications' AND COLUMN_NAME = 'distribution_site_id') > 0,
'ALTER TABLE notifications DROP COLUMN distribution_site_id',
'SELECT 1'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;