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



37
38
39
40
41
42
43
# File 'lib/active_record/locking_extensions.rb', line 37

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.



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

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.



21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/active_record/locking_extensions.rb', line 21

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

      raise ActiveRecord::RestartTransaction
    else
      raise
    end
  end
end