6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
# File 'lib/db_lock.rb', line 6
def get(name, timeout=0)
timeout = timeout.to_i
timeout = 0 if timeout < 0
raise "Invalid lock name: #{name.inspect}" if name.empty?
raise AlreadyLocked.new("Already lock in progress") if locked?
name = prefixed_lock_name(name)
sql = ActiveRecord::Base.send(:sanitize_sql_array, ["SELECT GET_LOCK(?, ?)", name, timeout])
lock = ActiveRecord::Base.connection.execute(sql)
if @locked = (lock and lock.first and lock.first[0] == 1)
yield
else
raise AlreadyLocked.new("Unable to obtain lock '#{name}' within #{timeout} seconds") unless locked?
end
ensure
if locked?
sql = ActiveRecord::Base.send(:sanitize_sql_array, ["SELECT RELEASE_LOCK(?)", name])
ActiveRecord::Base.connection.execute(sql)
end
@locked = false
end
|