Sha256: 3b460d6e0c867d4b6b9ba13fe09b98130bed5ef7fa9e4a92c2d1dbe393748767

Contents?: true

Size: 945 Bytes

Versions: 1

Compression:

Stored size: 945 Bytes

Contents

require 'zlib'

module WithAdvisoryLock
  class PostgreSQL < Base

    # See http://www.postgresql.org/docs/9.1/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS

    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(#{numeric_lock}), #{Time.now.to_f}"
      "t" == connection.select_value(sql).to_s
    end

    def release_lock
      sql = "SELECT pg_advisory_unlock(#{numeric_lock}), #{Time.now.to_f}"
      "t" == connection.select_value(sql).to_s
    end

    def numeric_lock
      @numeric_lock ||= begin
        if lock_name.is_a? Numeric
          lock_name.to_i
        else
          # Ruby MRI's String#hash is randomly seeded as of Ruby 1.9 so
          # make sure we use a deterministic hash.
          Zlib.crc32(lock_name.to_s)
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
with_advisory_lock-0.0.8 lib/with_advisory_lock/postgresql.rb