Class: WithAdvisoryLock::PostgreSQL

Inherits:
Base
  • Object
show all
Defined in:
lib/with_advisory_lock/postgresql.rb

Instance Attribute Summary

Attributes inherited from Base

#connection, #lock_name, #timeout_seconds

Instance Method Summary collapse

Methods inherited from Base

#advisory_lock_exists?, #already_locked?, #initialize, lock_stack, #lock_str, #query_cache_buster, #stable_hashcode, #with_advisory_lock_if_needed, #yield_with_lock

Constructor Details

This class inherits a constructor from WithAdvisoryLock::Base

Instance Method Details

#lock_keysObject

PostgreSQL wants 2 32bit integers as the lock key.



17
18
19
20
21
22
23
24
# File 'lib/with_advisory_lock/postgresql.rb', line 17

def lock_keys
  @lock_keys ||= begin
    [stable_hashcode(lock_name), ENV['WITH_ADVISORY_LOCK_PREFIX']].map do |ea|
      # pg advisory args must be 31 bit ints
      ea.to_i & 0x7fffffff
    end
  end
end

#release_lockObject



11
12
13
14
# File 'lib/with_advisory_lock/postgresql.rb', line 11

def release_lock
  sql = "SELECT pg_advisory_unlock(#{lock_keys.join(',')}) #{query_cache_buster}"
  't' == connection.select_value(sql).to_s
end

#try_lockObject



4
5
6
7
8
9
# File 'lib/with_advisory_lock/postgresql.rb', line 4

def try_lock
  # pg_try_advisory_lock will either obtain the lock immediately and return true
  # or return false if the lock cannot be acquired immediately
  sql = "SELECT pg_try_advisory_lock(#{lock_keys.join(',')}) #{query_cache_buster}"
  't' == connection.select_value(sql).to_s
end