Skip to content

Commit

Permalink
CHOUETTE-2358 Change query syntax to avoid multiple rows in the Delay…
Browse files Browse the repository at this point in the history
…ed Job reserve subquery

Approach described into collectiveidea/delayed_job_active_record#169
  • Loading branch information
albanpeignier committed Sep 26, 2022
1 parent b3e01f2 commit a69e22e
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
31 changes: 31 additions & 0 deletions app/lib/delayed/uniq_reservation.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# frozen_string_literal: true

module Delayed
# Used to customize Delayed::Backend::ActiveRecord::Job
#
# Fixes PostgreSQL SQL to ensure reservation uniqueness
# See https://github.com/collectiveidea/delayed_job_active_record/pull/169
module UniqReservation
def self.prepended(base)
class << base
prepend ClassMethods
end
end

module ClassMethods # rubocop:disable Style/Documentation
def reserve_with_scope_using_optimized_postgres(ready_scope, worker, now)
# Custom SQL required for PostgreSQL because postgres does not support UPDATE...LIMIT
# This locks the single record 'FOR UPDATE' in the subquery
# http://www.postgresql.org/docs/9.0/static/sql-select.html#SQL-FOR-UPDATE-SHARE
# Note: active_record would attempt to generate UPDATE...LIMIT like
# SQL for Postgres if we use a .limit() filter, but it would not
# use 'FOR UPDATE' and we would have many locking conflicts
quoted_name = connection.quote_table_name(table_name)
subquery = ready_scope.limit(1).lock(true).select('id').to_sql
sql = "UPDATE #{quoted_name} SET locked_at = ?, locked_by = ? WHERE id = (#{subquery}) RETURNING *"
reserved = find_by_sql([sql, now, worker.name])
reserved[0]
end
end
end
end
1 change: 1 addition & 0 deletions config/initializers/delayed_job.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
# Add organisation management for Job
class Delayed::Job # rubocop:disable Style/ClassAndModuleChildren(RuboCop)
prepend Delayed::WithOrganisation
prepend Delayed::UniqReservation
end

# Add :dead_worker hook
Expand Down

0 comments on commit a69e22e

Please sign in to comment.