SET @queue_column_exists := (
    SELECT COUNT(*)
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE TABLE_SCHEMA = DATABASE()
      AND TABLE_NAME = 'rvx_sync_batches'
      AND COLUMN_NAME = 'queue_name'
);

SET @add_queue_column := IF(
    @queue_column_exists = 0,
    'ALTER TABLE rvx_sync_batches ADD COLUMN queue_name VARCHAR(64) NOT NULL DEFAULT ''rvx'' AFTER status',
    'SELECT 1'
);

PREPARE stmt FROM @add_queue_column;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @queue_index_exists := (
    SELECT COUNT(*)
    FROM INFORMATION_SCHEMA.STATISTICS
    WHERE TABLE_SCHEMA = DATABASE()
      AND TABLE_NAME = 'rvx_sync_batches'
      AND INDEX_NAME = 'idx_rvx_sync_batches_queue_status'
);

SET @add_queue_index := IF(
    @queue_index_exists = 0,
    'CREATE INDEX idx_rvx_sync_batches_queue_status ON rvx_sync_batches (queue_name, status, available_at)',
    'SELECT 1'
);

PREPARE stmt FROM @add_queue_index;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
