Module: ActiveRecord::LockingExtensions

Defined in:
lib/active_record/locking_extensions.rb

Overview

These methods are available as class methods on ActiveRecord::Base.

Instance Method Summary collapse

Instance Method Details

#create_ignoring_duplicates!(*args) ⇒ Object

Create the record, but ignore the exception if there's a duplicate. if there is a deadlock, retry



33
34
35
36
37
38
39
# File 'lib/active_record/locking_extensions.rb', line 33

def create_ignoring_duplicates!(*args)
  retry_deadlocks do
    ignoring_duplicates do
      create!(*args)
    end
  end
end

#restartable_transaction(&block) ⇒ Object

Execute the given block within a database transaction, and retry the transaction from the beginning if a RestartTransaction exception is raised.



9
10
11
12
13
14
15
# File 'lib/active_record/locking_extensions.rb', line 9

def restartable_transaction(&block)
  begin
    transaction(&block)
  rescue ActiveRecord::RestartTransaction
    retry
  end
end

#with_restart_on_deadlockObject

Execute the given block, and retry the current restartable transaction if a MySQL deadlock occurs.



19
20
21
22
23
24
25
26
27
28
29
# File 'lib/active_record/locking_extensions.rb', line 19

def with_restart_on_deadlock
  begin
    yield
  rescue ActiveRecord::StatementInvalid => exception
    if exception.message =~ /deadlock/i || exception.message =~ /database is locked/i
      raise ActiveRecord::RestartTransaction
    else
      raise
    end
  end
end