Module: ArTableLock

Included in:
ApplicationRecord
Defined in:
lib/extensions/ar_table_lock.rb

Instance Method Summary collapse

Instance Method Details

#with_lock(timeout = 60.seconds) ⇒ Object

Creates mutex by locking on a database table in SQL. Please use record level locking over this

"SHARE ROW EXCLUSIVE"
  This mode protects a table against concurrent data changes.
  It is self-exclusive so that only one session can hold it at a time.

details on locks can be found on postgres docs:

can be fount http://www.postgresql.org/docs/9.4/static/explicit-locking.html

12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/extensions/ar_table_lock.rb', line 12

def with_lock(timeout = 60.seconds)
  lock = "SHARE ROW EXCLUSIVE"

  transaction do
    _log.debug "Acquiring lock on #{name} (table: #{table_name}..."
    connection.execute("LOCK TABLE #{table_name} in #{lock} MODE")
    _log.debug "Acquired lock on #{name} (table: #{table_name}..."

    begin
      Timeout.timeout(timeout) { yield }
    ensure
      _log.debug "Releasing lock on #{name} (table: #{table_name}..."
    end
  end
end