Module: Locksmith::Pg

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

Instance Method Summary collapse

Instance Method Details

#connObject



53
54
55
56
57
58
59
60
61
62
# File 'lib/locksmith/pg.rb', line 53

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



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

def conn=(conn)
  @conn = conn
end

#create(name, opts) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
# File 'lib/locksmith/pg.rb', line 32

def create(name, opts)
  lock_args = [opts[:lspace], key(name)]
  opts[:attempts].times.each do |i|
    res = conn.exec("select pg_try_advisory_lock($1,$2)", lock_args)
    if res[0]["pg_try_advisory_lock"] == "t"
      return(true)
    else
      return(false) if i == (opts[:attempts] - 1)
    end
  end
end

#dburlObject



64
65
66
# File 'lib/locksmith/pg.rb', line 64

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

#delete(name, opts) ⇒ Object



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

def delete(name, opts)
  lock_args = [opts[:lspace], key(name)]
  conn.exec("select pg_advisory_unlock($1,$2)", lock_args)
end

#key(name) ⇒ Object



22
23
24
25
26
27
28
29
30
# File 'lib/locksmith/pg.rb', line 22

def key(name)
  i = Zlib.crc32(name)
  # We need to wrap the value for postgres
  if i > 2147483647
    -(-(i) & 0xffffffff)
  else
    i
  end
end

#lock(name, opts = {}) ⇒ Object



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

def lock(name, opts={})
  opts[:ttl] ||= 60
  opts[:attempts] ||= 3
  opts[:lspace] ||= (Config.pg_lock_space || -2147483648)

  if create(name, opts)
    begin Timeout::timeout(opts[:ttl]) {return(yield)}
    ensure delete(name, opts)
    end
  end
end

#log(data, &blk) ⇒ Object



68
69
70
# File 'lib/locksmith/pg.rb', line 68

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