SET @request_id_col_exists = (
    SELECT COUNT(1)
    FROM information_schema.COLUMNS
    WHERE TABLE_SCHEMA = DATABASE()
      AND TABLE_NAME = 'operation_audit_log'
      AND COLUMN_NAME = 'request_id'
);

SET @add_request_id_col_sql = IF(
    @request_id_col_exists = 0,
    'ALTER TABLE operation_audit_log ADD COLUMN request_id VARCHAR(64) DEFAULT NULL AFTER request_query',
    'SELECT 1'
);

PREPARE stmt_add_request_id_col FROM @add_request_id_col_sql;
EXECUTE stmt_add_request_id_col;
DEALLOCATE PREPARE stmt_add_request_id_col;

SET @request_id_idx_exists = (
    SELECT COUNT(1)
    FROM information_schema.STATISTICS
    WHERE TABLE_SCHEMA = DATABASE()
      AND TABLE_NAME = 'operation_audit_log'
      AND INDEX_NAME = 'idx_request_id_time'
);

SET @add_request_id_idx_sql = IF(
    @request_id_idx_exists = 0,
    'ALTER TABLE operation_audit_log ADD KEY idx_request_id_time (request_id, created_at)',
    'SELECT 1'
);

PREPARE stmt_add_request_id_idx FROM @add_request_id_idx_sql;
EXECUTE stmt_add_request_id_idx;
DEALLOCATE PREPARE stmt_add_request_id_idx;
