fix(tenant): 修复生产备份迁移与未读查询性能

This commit is contained in:
yml
2026-11-16 19:50:49 +08:00
parent fed950ea5a
commit ac9717a5d8
5 changed files with 341 additions and 3 deletions
@@ -1,8 +1,35 @@
-- +goose Up
ALTER TABLE game_accounts
ADD COLUMN source_tenant_id BIGINT UNSIGNED NOT NULL DEFAULT 0 AFTER id,
ADD KEY idx_game_accounts_source_tenant (source_tenant_id, status);
-- 生产库曾提前手工补过来源站点字段,迁移需兼容已有列和索引。
SET @has_source_tenant_column = (
SELECT COUNT(*) FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'game_accounts'
AND COLUMN_NAME = 'source_tenant_id'
);
SET @add_source_tenant_column = IF(
@has_source_tenant_column = 0,
'ALTER TABLE game_accounts ADD COLUMN source_tenant_id BIGINT UNSIGNED NOT NULL DEFAULT 0 AFTER id',
'DO 0'
);
PREPARE add_source_tenant_column FROM @add_source_tenant_column;
EXECUTE add_source_tenant_column;
DEALLOCATE PREPARE add_source_tenant_column;
SET @has_source_tenant_index = (
SELECT COUNT(*) FROM information_schema.STATISTICS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'game_accounts'
AND INDEX_NAME = 'idx_game_accounts_source_tenant'
);
SET @add_source_tenant_index = IF(
@has_source_tenant_index = 0,
'ALTER TABLE game_accounts ADD KEY idx_game_accounts_source_tenant (source_tenant_id, status)',
'DO 0'
);
PREPARE add_source_tenant_index FROM @add_source_tenant_index;
EXECUTE add_source_tenant_index;
DEALLOCATE PREPARE add_source_tenant_index;
UPDATE game_accounts a
JOIN users u ON u.id = a.owner_id
@@ -0,0 +1,25 @@
-- +goose Up
-- 未读统计按会话和已读时间取消息,覆盖索引可避免逐会话回表。
ALTER TABLE chat_messages
ADD KEY idx_chat_messages_conversation_created_sender (conversation_id, created_at, sender_type, sender_id);
ALTER TABLE chat_participants
ADD KEY idx_chat_participants_unread (participant_type, participant_id, conversation_id, last_read_at);
-- 通知未读需要同时过滤站点并计数,将站点字段纳入覆盖索引。
ALTER TABLE notifications
DROP KEY idx_notifications_tenant_user_read,
ADD KEY idx_notifications_tenant_user_unread_site (tenant_id, user_id, read_at, distribution_site_id, id);
-- +goose Down
ALTER TABLE notifications
DROP KEY idx_notifications_tenant_user_unread_site,
ADD KEY idx_notifications_tenant_user_read (tenant_id, user_id, read_at, id);
ALTER TABLE chat_participants
DROP KEY idx_chat_participants_unread;
ALTER TABLE chat_messages
DROP KEY idx_chat_messages_conversation_created_sender;