lib/mysql_getlock.rb in mysql_getlock-0.2.0 vs lib/mysql_getlock.rb in mysql_getlock-0.2.1
- old
+ new
@@ -5,10 +5,11 @@
attr_reader :mysql2, :key, :logger, :timeout
TIMEOUT = -1 # inifinity
class Error < ::StandardError; end
+ class LockError < ::StandardError; end
def initialize(mysql2:, key:, logger: nil, timeout: TIMEOUT)
self.mysql2 = mysql2
@key = Mysql2::Client.escape(key)
@logger = logger
@@ -25,11 +26,11 @@
def lock
if !multiple_lockable? and (current_session_key and current_session_key != key)
raise Error, "get_lock() is already issued in the same connection for '#{current_session_key}'"
end
- logger.info { "#{log_head}Wait acquiring a mysql lock '#{key}'" } if logger
+ logger.info { "#{log_head}Wait #{timeout < 0 ? '' : "#{timeout} sec "}to acquire a mysql lock '#{key}'" } if logger
results = mysql2.query(%Q[select get_lock('#{key}', #{timeout})], as: :array)
case results.to_a.first.first
when 1
logger.info { "#{log_head}Acquired a mysql lock '#{key}'" } if logger
set_current_session_key(key)
@@ -79,10 +80,10 @@
self_id = results.to_a.first.first
self_id == lock_id
end
def synchronize(&block)
- lock
+ raise LockError unless lock
begin
yield
ensure
unlock
end