Skip to content

Commit e6206dd

Browse files
authored
Merge pull request #986 from yellowspot/reimplement-preloader-monkey-patch
[Rails 7] Update preloader monkey patch
2 parents 57e1428 + 965a722 commit e6206dd

File tree

2 files changed

+25
-15
lines changed

2 files changed

+25
-15
lines changed

lib/active_record/connection_adapters/sqlserver/core_ext/preloader.rb

Lines changed: 7 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -6,20 +6,12 @@ module ActiveRecord
66
module ConnectionAdapters
77
module SQLServer
88
module CoreExt
9-
module Preloader
10-
private
9+
module LoaderQuery
10+
def load_records_for_keys(keys, &block)
11+
return super unless scope.connection.adapter_name == "SQLServer"
1112

12-
def records_for(ids)
13-
return super unless klass.connection.adapter_name == "SQLServer"
14-
15-
ids.each_slice(in_clause_length).flat_map do |slice|
16-
scope.where(association_key_name => slice).load do |record|
17-
# Processing only the first owner
18-
# because the record is modified but not an owner
19-
owner = owners_by_key[convert_key(record[association_key_name])].first
20-
association = owner.association(reflection.name)
21-
association.set_inverse_instance(record)
22-
end.records
13+
keys.each_slice(in_clause_length).flat_map do |slice|
14+
scope.where(association_key_name => slice).load(&block).records
2315
end
2416
end
2517

@@ -33,6 +25,6 @@ def in_clause_length
3325
end
3426

3527
ActiveSupport.on_load(:active_record) do
36-
mod = ActiveRecord::ConnectionAdapters::SQLServer::CoreExt::Preloader
37-
ActiveRecord::Associations::Preloader::Association.prepend(mod)
28+
mod = ActiveRecord::ConnectionAdapters::SQLServer::CoreExt::LoaderQuery
29+
ActiveRecord::Associations::Preloader::Association::LoaderQuery.prepend(mod)
3830
end
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
require "cases/helper_sqlserver"
2+
require "models/citation"
3+
require "models/book"
4+
5+
class EagerLoadingTooManyIdsTest < ActiveRecord::TestCase
6+
fixtures :citations
7+
8+
def test_batch_preloading_too_many_ids
9+
in_clause_length = 10_000
10+
11+
# We Monkey patch Preloader to work with batches of 10_000 records.
12+
# Expect: N Books queries + Citation query
13+
expected_query_count = (Citation.count / in_clause_length.to_f).ceil + 1
14+
assert_queries(expected_query_count) do
15+
Citation.preload(:reference_of).to_a.size
16+
end
17+
end
18+
end

0 commit comments

Comments
 (0)