SET @add_cp_app_admin_created := (
  SELECT IF(
    COUNT(*) = 0,
    'ALTER TABLE user_cp_applications ADD INDEX idx_user_cp_app_admin_created (app_code, created_at_ms, application_id)',
    'SELECT 1'
  )
  FROM information_schema.STATISTICS
  WHERE TABLE_SCHEMA = DATABASE()
    AND TABLE_NAME = 'user_cp_applications'
    AND INDEX_NAME = 'idx_user_cp_app_admin_created'
);

PREPARE stmt FROM @add_cp_app_admin_created;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @add_cp_app_admin_filter := (
  SELECT IF(
    COUNT(*) = 0,
    'ALTER TABLE user_cp_applications ADD INDEX idx_user_cp_app_admin_filter (app_code, status, relation_type, created_at_ms, application_id)',
    'SELECT 1'
  )
  FROM information_schema.STATISTICS
  WHERE TABLE_SCHEMA = DATABASE()
    AND TABLE_NAME = 'user_cp_applications'
    AND INDEX_NAME = 'idx_user_cp_app_admin_filter'
);

PREPARE stmt FROM @add_cp_app_admin_filter;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @add_cp_rel_admin_formed := (
  SELECT IF(
    COUNT(*) = 0,
    'ALTER TABLE user_cp_relationships ADD INDEX idx_user_cp_rel_admin_formed (app_code, formed_at_ms, relationship_id)',
    'SELECT 1'
  )
  FROM information_schema.STATISTICS
  WHERE TABLE_SCHEMA = DATABASE()
    AND TABLE_NAME = 'user_cp_relationships'
    AND INDEX_NAME = 'idx_user_cp_rel_admin_formed'
);

PREPARE stmt FROM @add_cp_rel_admin_formed;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @add_cp_rel_admin_filter := (
  SELECT IF(
    COUNT(*) = 0,
    'ALTER TABLE user_cp_relationships ADD INDEX idx_user_cp_rel_admin_filter (app_code, status, relation_type, formed_at_ms, relationship_id)',
    'SELECT 1'
  )
  FROM information_schema.STATISTICS
  WHERE TABLE_SCHEMA = DATABASE()
    AND TABLE_NAME = 'user_cp_relationships'
    AND INDEX_NAME = 'idx_user_cp_rel_admin_filter'
);

PREPARE stmt FROM @add_cp_rel_admin_filter;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
