class Mimi::DB::Lock::MysqlLock

Attributes

name[R]
name_uint64[R]
options[R]
timeout[R]

Public Class Methods

new(name, opts = {}) click to toggle source

Timeout semantics: nil – wait indefinitely 0 – do not wait <s> – wait <s> seconds (can be Float)

# File lib/mimi/db/lock/mysql_lock.rb, line 13
def initialize(name, opts = {})
  @name = name
  @name_uint64 = Digest::SHA1.digest(name).unpack('q').first
  @options = opts
  @timeout =
    if opts[:timeout].nil?
      -1
    elsif opts[:timeout] <= 0
      0
    else
      opts[:timeout].to_f.round
    end
end

Public Instance Methods

execute() { || ... } click to toggle source
# File lib/mimi/db/lock/mysql_lock.rb, line 27
def execute(&_block)
  ActiveRecord::Base.transaction(requires_new: true) do
    begin
      acquire_lock_with_timeout!
      yield if block_given?
    ensure
      release_lock!
    end
  end
end

Private Instance Methods

acquire_lock_with_timeout!() click to toggle source
# File lib/mimi/db/lock/mysql_lock.rb, line 41
def acquire_lock_with_timeout!
  result = Mimi::DB.execute('select get_lock(?, ?) as lock_acquired', name, timeout)
  lock_acquired = result.first[0] == 1
  raise Mimi::DB::Lock::NotAvailable unless lock_acquired
  true
end
release_lock!() click to toggle source
# File lib/mimi/db/lock/mysql_lock.rb, line 49
def release_lock!
  Mimi::DB.execute('select release_lock(?)', name)
  true
end