-- 国家资料级联同步按 (country_id, id) 游标分页；该索引避免国家更新时扫描整张用户表。
-- 生产表当前约 1.4 万行/4.5 MB，使用 INPLACE + LOCK=NONE，且限制元数据锁等待避免影响在线请求。
SET @current_schema = DATABASE();
SET SESSION lock_wait_timeout = 10;

SET @ddl = IF(
  EXISTS (
    SELECT 1
    FROM INFORMATION_SCHEMA.STATISTICS first_column
    WHERE first_column.TABLE_SCHEMA = @current_schema
      AND first_column.TABLE_NAME = 'user_base_info'
      AND first_column.SEQ_IN_INDEX = 1
      AND first_column.COLUMN_NAME = 'country_id'
      AND EXISTS (
        SELECT 1
        FROM INFORMATION_SCHEMA.STATISTICS second_column
        WHERE second_column.TABLE_SCHEMA = first_column.TABLE_SCHEMA
          AND second_column.TABLE_NAME = first_column.TABLE_NAME
          AND second_column.INDEX_NAME = first_column.INDEX_NAME
          AND second_column.SEQ_IN_INDEX = 2
          AND second_column.COLUMN_NAME = 'id'
      )
  ),
  'SELECT 1',
  'ALTER TABLE `user_base_info` ADD KEY `idx_country_id_id` (`country_id`, `id`), ALGORITHM=INPLACE, LOCK=NONE'
);

PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
