Module: Locksmith::Pg

Extended by:
Pg
Included in:
Pg
Defined in:
lib/locksmith/pg.rb

Constant Summary collapse

BACKOFF =
0.5

Instance Method Summary collapse

Instance Method Details

#connObject



35
36
37
38
39
40
41
42
43
44
# File 'lib/locksmith/pg.rb', line 35

def conn
  @conn ||= PG::Connection.open(
    dburl.host,
    dburl.port || 5432,
    nil, '', #opts, tty
    dburl.path.gsub("/",""), # database name
    dburl.user,
    dburl.password
  )
end

#conn=(conn) ⇒ Object



31
32
33
# File 'lib/locksmith/pg.rb', line 31

def conn=(conn)
  @conn = conn
end

#dburlObject



46
47
48
# File 'lib/locksmith/pg.rb', line 46

def dburl
  URI.parse(ENV["DATABASE_URL"])
end

#lock(name) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/locksmith/pg.rb', line 8

def lock(name)
  i = Zlib.crc32(name)
  result = nil
  begin
    sleep(BACKOFF) until write_lock(i)
    if block_given?
      result = yield
    end
    return result
  ensure
    release_lock(i)
  end
end

#log(data, &blk) ⇒ Object



50
51
52
# File 'lib/locksmith/pg.rb', line 50

def log(data, &blk)
  Log.log({:ns => "postgresql-lock"}.merge(data), &blk)
end

#release_lock(i) ⇒ Object



27
28
29
# File 'lib/locksmith/pg.rb', line 27

def release_lock(i)
  conn.exec("select pg_advisory_unlock($1)", [i])
end

#write_lock(i) ⇒ Object



22
23
24
25
# File 'lib/locksmith/pg.rb', line 22

def write_lock(i)
  r = conn.exec("select pg_try_advisory_lock($1)", [i])
  r[0]["pg_try_advisory_lock"] == "t"
end