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.



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/active_record/locking_extensions.rb', line 32

def create_ignoring_duplicates!(*args)
  # Error examples:
  #   PG::Error: ERROR:  deadlock detected
  #   Mysql::Error: Deadlock found when trying to get lock
  #   PG::Error: ERROR:  duplicate key value violates unique constraint
  #   Mysql2::Error: Duplicate entry 'keith' for key 'index_users_on_username': INSERT INTO `users...
  begin
    create!(*args)
  rescue ActiveRecord::StatementInvalid => exception
    if  exception.message =~ /duplicate/i
      # Just ignore it...someone else has already created the record.
    elsif  exception.message =~ /deadlock/i
      # Somebody else is in the midst of creating the record. We'd better
      # retry, so we ensure they're done before we move on.
      retry
    else
      raise
    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
      raise ActiveRecord::RestartTransaction
    else
      raise
    end
  end
end