Class: PgLock::Locket

Inherits:
Object
  • Object
show all
Defined in:
lib/pg_lock/locket.rb

Overview

Holds the logic to aquire a lock and parse if locking was successful

Constant Summary collapse

TRUE_VALUES =
[true, "t"].freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(connection, lock_args) ⇒ Locket

Returns a new instance of Locket.


7
8
9
10
# File 'lib/pg_lock/locket.rb', line 7

def initialize(connection, lock_args)
  self.connection = connection
  self.args       = lock_args
end

Instance Attribute Details

#argsObject

Returns the value of attribute args


6
7
8
# File 'lib/pg_lock/locket.rb', line 6

def args
  @args
end

#connectionObject

Returns the value of attribute connection


6
7
8
# File 'lib/pg_lock/locket.rb', line 6

def connection
  @connection
end

Instance Method Details

#active?Boolean

Returns:

  • (Boolean)

28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/pg_lock/locket.rb', line 28

def active?
  active = connection.exec(<<-eos, args).getvalue(0,0)
    SELECT granted
    FROM pg_locks
    WHERE locktype = 'advisory' AND
     pid = pg_backend_pid() AND
     mode = 'ExclusiveLock' AND
     classid = $1 AND
     objid = $2
  eos

  TRUE_VALUES.include?(active)
end

#aquired?Boolean

Returns:

  • (Boolean)

22
23
24
25
26
# File 'lib/pg_lock/locket.rb', line 22

def aquired?
  TRUE_VALUES.include?(@lock[0]["pg_try_advisory_lock"])
rescue
  false
end

#lockObject


12
13
14
15
# File 'lib/pg_lock/locket.rb', line 12

def lock
  @lock = connection.exec("select pg_try_advisory_lock($1,$2)", args)
  return aquired?
end

#unlockObject


17
18
19
20
# File 'lib/pg_lock/locket.rb', line 17

def unlock
  connection.exec("select pg_advisory_unlock($1,$2)", args)
  @lock = false
end