-- Script incremental idempotente para melhorar a consulta do modulo de contatos
SET @tem_idx_cliente_status_principal := (
    SELECT COUNT(*)
    FROM information_schema.statistics
    WHERE table_schema = DATABASE()
      AND table_name = 'contatos'
      AND index_name = 'idx_contatos_cliente_status_principal'
);
SET @sql_cliente_status_principal := IF(@tem_idx_cliente_status_principal = 0,
    'ALTER TABLE contatos ADD KEY idx_contatos_cliente_status_principal (cliente_id, status, principal)',
    'SELECT "idx_contatos_cliente_status_principal ja existe"'
);
PREPARE stmt FROM @sql_cliente_status_principal;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @tem_idx_email := (
    SELECT COUNT(*)
    FROM information_schema.statistics
    WHERE table_schema = DATABASE()
      AND table_name = 'contatos'
      AND index_name = 'idx_contatos_email'
);
SET @sql_email := IF(@tem_idx_email = 0,
    'ALTER TABLE contatos ADD KEY idx_contatos_email (email)',
    'SELECT "idx_contatos_email ja existe"'
);
PREPARE stmt FROM @sql_email;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
