SET @invoice_order_index = (
  SELECT IF(
    EXISTS(
      SELECT 1 FROM information_schema.statistics
      WHERE table_schema = DATABASE()
        AND table_name = 'invoices'
        AND index_name = 'idx_invoices_order'
    ),
    'SELECT 1',
    'ALTER TABLE invoices ADD INDEX idx_invoices_order (order_id, status, id)'
  )
);
PREPARE invoice_order_index_stmt FROM @invoice_order_index;
EXECUTE invoice_order_index_stmt;
DEALLOCATE PREPARE invoice_order_index_stmt;

SET @invoice_order_unique = (
  SELECT IF(
    EXISTS(
      SELECT 1 FROM information_schema.statistics
      WHERE table_schema = DATABASE()
        AND table_name = 'invoices'
        AND column_name = 'order_id'
        AND non_unique = 0
    ),
    (
      SELECT CONCAT('ALTER TABLE invoices DROP INDEX ', index_name)
      FROM information_schema.statistics
      WHERE table_schema = DATABASE()
        AND table_name = 'invoices'
        AND column_name = 'order_id'
        AND non_unique = 0
      LIMIT 1
    ),
    'SELECT 1'
  )
);
PREPARE invoice_order_unique_stmt FROM @invoice_order_unique;
EXECUTE invoice_order_unique_stmt;
DEALLOCATE PREPARE invoice_order_unique_stmt;
