Module: DeadlockRetry::ClassMethods

Defined in:
lib/deadlock_retry.rb

Constant Summary collapse

DEADLOCK_ERROR_MESSAGES =
[
  "Deadlock found when trying to get lock",
  "Lock wait timeout exceeded"
]
MAXIMUM_RETRIES_ON_DEADLOCK =
3

Instance Method Summary collapse

Instance Method Details

#transaction_with_deadlock_handling(*objects, &block) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/deadlock_retry.rb', line 40

def transaction_with_deadlock_handling(*objects, &block)
  retry_count = 0

  begin
    transaction_without_deadlock_handling(*objects, &block)
  rescue ActiveRecord::StatementInvalid => error
    raise if in_nested_transaction?
    if DEADLOCK_ERROR_MESSAGES.any? { |msg| error.message =~ /#{Regexp.escape(msg)}/ }
      raise if retry_count >= MAXIMUM_RETRIES_ON_DEADLOCK
      retry_count += 1
      logger.info "Deadlock detected on retry #{retry_count}, restarting transaction"
      log_innodb_status
      retry
    else
      raise
    end
  end
end