Module: ActiveRecord::LockingExtensions

Defined in:
lib/active_record/locking_extensions.rb,
lib/active_record/locking_extensions/log_subscriber.rb

Overview

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

Defined Under Namespace

Classes: LogSubscriber

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



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

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
# File 'lib/active_record/locking_extensions.rb', line 9

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

#with_restart_on_deadlockObject

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



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

def with_restart_on_deadlock
  yield
rescue ActiveRecord::StatementInvalid => exception
  if exception.message =~ /deadlock/i || exception.message =~ /database is locked/i
    ActiveSupport::Notifications.publish('deadlock_restart.double_entry', exception: exception)

    raise ActiveRecord::RestartTransaction
  else
    raise
  end
end