Skip to content

Commit

Permalink
Use more ActiveRecord in Lockable and not connection.execute
Browse files Browse the repository at this point in the history
  • Loading branch information
bensheldon committed Aug 26, 2020
1 parent 8a272dd commit f3c19ea
Showing 1 changed file with 8 additions and 10 deletions.
18 changes: 8 additions & 10 deletions lib/good_job/lockable.rb
Original file line number Diff line number Diff line change
Expand Up @@ -55,19 +55,17 @@ def with_advisory_lock
end

def advisory_lock
query = <<~SQL
SELECT 1 AS one
WHERE pg_try_advisory_lock(('x'||substr(md5(:table_name || :id::text), 1, 16))::bit(64)::bigint)
where_sql = <<~SQL
pg_try_advisory_lock(('x'||substr(md5(:table_name || :id::text), 1, 16))::bit(64)::bigint)
SQL
self.class.connection.execute(sanitize_sql_for_conditions([query, { table_name: self.class.table_name, id: send(self.class.primary_key) }])).ntuples.positive?
self.class.unscoped.where(where_sql, { table_name: self.class.table_name, id: send(self.class.primary_key) }).exists?
end

def advisory_unlock
query = <<~SQL
SELECT 1 AS one
WHERE pg_advisory_unlock(('x'||substr(md5(:table_name || :id::text), 1, 16))::bit(64)::bigint)
where_sql = <<~SQL
pg_advisory_unlock(('x'||substr(md5(:table_name || :id::text), 1, 16))::bit(64)::bigint)
SQL
self.class.connection.execute(sanitize_sql_for_conditions([query, { table_name: self.class.table_name, id: send(self.class.primary_key) }])).ntuples.positive?
self.class.unscoped.where(where_sql, { table_name: self.class.table_name, id: send(self.class.primary_key) }).exists?
end

def advisory_lock!
Expand All @@ -85,11 +83,11 @@ def with_advisory_lock
end

def advisory_locked?
self.class.advisory_locked.where(id: send(self.class.primary_key)).any?
self.class.unscoped.advisory_locked.where(id: send(self.class.primary_key)).exists?
end

def owns_advisory_lock?
self.class.owns_advisory_locked.where(id: send(self.class.primary_key)).any?
self.class.unscoped.owns_advisory_locked.where(id: send(self.class.primary_key)).exists?
end

def advisory_unlock!
Expand Down

0 comments on commit f3c19ea

Please sign in to comment.