Class: Sequel::AdvisoryLock

Inherits:
Object
  • Object
show all
Defined in:
lib/sequel/advisory_lock.rb

Instance Method Summary collapse

Constructor Details

#initialize(db, key_or_key1, key2 = nil, shared: false, xact: false) ⇒ AdvisoryLock

Returns a new instance of AdvisoryLock.



6
7
8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/sequel/advisory_lock.rb', line 6

def initialize(db, key_or_key1, key2=nil, shared: false, xact: false)
  @db = db
  xstr = xact ? "_xact" : ""
  sharestr = shared ? "_shared" : ""
  @locker = to_expr("pg_advisory#{xstr}_lock#{sharestr}", key_or_key1, key2)
  @trylocker = to_expr("pg_try_advisory#{xstr}_lock#{sharestr}", key_or_key1, key2)
  @unlocker = to_expr(shared ? "pg_advisory_unlock_shared" : "pg_advisory_unlock", key_or_key1, key2)
  if key2
    @cond = {classid: key_or_key1, objid: key2, objsubid: 2}
  else
    k2 = key_or_key1 & 0xFFFF_FFFF
    @cond = {classid: 1, objid: k2, objsubid: 1}
  end
end

Instance Method Details

#dataset(this: false) ⇒ Object



25
26
27
28
29
# File 'lib/sequel/advisory_lock.rb', line 25

def dataset(this: false)
  ds = @db[:pg_locks]
  ds = ds.where(@cond) if this
  return ds
end

#unlockObject



58
59
60
# File 'lib/sequel/advisory_lock.rb', line 58

def unlock
  @db.get(@unlocker)
end

#unlock_allObject



62
63
64
# File 'lib/sequel/advisory_lock.rb', line 62

def unlock_all
  @db.get(Sequel.function(:pg_advisory_unlock_all))
end

#with_lockObject

pg_advisory_lock pg_advisory_lock_shared pg_advisory_xact_lock pg_advisory_xact_lock_shared



35
36
37
38
39
40
41
# File 'lib/sequel/advisory_lock.rb', line 35

def with_lock
  raise LocalJumpError unless block_given?
  @db.get(@locker)
  return yield
ensure
  self.unlock
end

#with_lock?Boolean

pg_try_advisory_lock pg_try_advisory_lock_shared pg_try_advisory_xact_lock pg_try_advisory_xact_lock_shared

Returns:

  • (Boolean)

Raises:

  • (LocalJumpError)


47
48
49
50
51
52
53
54
55
56
# File 'lib/sequel/advisory_lock.rb', line 47

def with_lock?
  raise LocalJumpError unless block_given?
  acquired = @db.get(@trylocker)
  return false, nil unless acquired
  begin
    return true, yield
  ensure
    self.unlock
  end
end