Skip to content

Commit

Permalink
Fix Postgres UPDATE ... LIMIT bug
Browse files Browse the repository at this point in the history
collectiveidea#143

> The subquery returns 1 row so there is no need to use "IN" as the "=" operator will work just fine. Additionally, using "=" doesn't allow the query planner to choose a plan that can sidestep the LIMIT.
  • Loading branch information
hardbap committed May 25, 2022
1 parent 97f26a3 commit 118caf4
Showing 1 changed file with 2 additions and 1 deletion.
3 changes: 2 additions & 1 deletion lib/delayed/backend/active_record.rb
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,8 @@ def self.reserve_with_scope_using_optimized_postgres(ready_scope, worker, now)
# 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 IN (#{subquery}) RETURNING *"
# see https://github.com/collectiveidea/delayed_job_active_record/pull/169
sql = "UPDATE #{quoted_name} SET locked_at = ?, locked_by = ? WHERE id = (#{subquery}) RETURNING *"
reserved = find_by_sql([sql, now, worker.name])
reserved[0]
end
Expand Down

0 comments on commit 118caf4

Please sign in to comment.