Skip to content

Commit 6e2bffa

Browse files
Mohammad alkhassawnehMohammad alkhassawneh
authored andcommitted
Fix superfluous SELECT when scheduling a single future job
Execution subclasses use belongs_to :job, which Rails validates by loading the associated record before each INSERT. For bulk enqueues this is already avoided via insert_all, but the single-job schedule path (create_or_find_by!) runs an extra SELECT per job. Replace the implicit presence-via-association validation with an explicit column check so the record is only loaded when callers intentionally traverse the association (e.g. Execution#discard).
1 parent 73602fe commit 6e2bffa

2 files changed

Lines changed: 17 additions & 1 deletion

File tree

‎app/models/solid_queue/execution.rb‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,8 @@ class UndiscardableError < StandardError; end
1010

1111
scope :ordered, -> { order(priority: :asc, job_id: :asc) }
1212

13-
belongs_to :job
13+
belongs_to :job, optional: true
14+
validates :job_id, presence: true
1415

1516
class << self
1617
def type

‎test/models/solid_queue/job_test.rb‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,21 @@ class DiscardableNonOverlappingGroupedJob2 < NonOverlappingJob
8787
assert_equal solid_queue_job.scheduled_at, execution.scheduled_at
8888
end
8989

90+
test "scheduling a single future job does not SELECT the job record back" do
91+
active_job = AddToBufferJob.new(1)
92+
job_selects = 0
93+
94+
subscriber = ->(*, payload) do
95+
job_selects += 1 if payload[:sql].match?(/\ASELECT.*FROM.*solid_queue_jobs/i)
96+
end
97+
98+
ActiveSupport::Notifications.subscribed(subscriber, "sql.active_record") do
99+
SolidQueue::Job.enqueue(active_job, scheduled_at: 5.minutes.from_now)
100+
end
101+
102+
assert_equal 0, job_selects
103+
end
104+
90105
test "enqueue jobs within a connected_to block for the primary DB" do
91106
ShardedRecord.connected_to(role: :writing, shard: :shard_two) do
92107
ShardedJobResult.create!(value: "in shard two")

0 commit comments

Comments
 (0)