goldiloader 6.0.1 → 6.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 46c480ad935c508bfb19d696ec74ffa1e86c1a021467ee68bfb321896df05b03
4
- data.tar.gz: 27e4b6fbb05b55e6edff4cc7af74fe86d0d183fce47f37e5a05b177c3e3ff66b
3
+ metadata.gz: 9437f2e3668b6c80019731130febc12063c662ddea37d0c064384704d534448b
4
+ data.tar.gz: cb296d7b43b1eb86114c9415f7d1d46405f1f0018b55a6a27901b4ba91c5ab1e
5
5
  SHA512:
6
- metadata.gz: f317fc98570afe60ed9ddae63109e1dd82d3595f08ce7e36e2ffe23c19451cfd95a7c7cc64aef1126807eaf05c389103d7dbb205b08d4eb0067bf9bb7c6d15b0
7
- data.tar.gz: 0cecf4a7732fe564630ad2f9cbb925bd85afb90a075ef9cee48cadc7cfd5bae18274c5d11d3ee6ef99041bcd5465ecb9456b531d2fa2223b5ce4085d55cb28ad
6
+ metadata.gz: 0a7932704bc534fab3dc221ee681a3e408d507b0f98439f1f1bb4c6dba0c5d4146767ca8b09ff583b771d59efc019b923aff48070cc9c573d3d90c7dac16c0ea
7
+ data.tar.gz: b28a6ed08bbe51aa91de98b793b6237da35637d69408a5a02980dc96af6dd797e08d7bcc2995090a0991136133bce881c3dea60e3332a7188e8af6498e6d6639
@@ -27,18 +27,42 @@ module Goldiloader
27
27
  end
28
28
 
29
29
  def goldiload(cache_name = nil, key: self.class.primary_key, &block)
30
- cache_name ||= block.source_location.join(':')
30
+ cache_name ||= begin
31
+ # Interpolating builds the same name as Array#join(':') but is faster
32
+ path, line = block.source_location
33
+ "#{path}:#{line}"
34
+ end
31
35
  auto_include_context.preloaded(self, cache_name: cache_name, key: key, &block)
32
36
  end
33
37
  end
34
38
  ::ActiveRecord::Base.include(::Goldiloader::BasePatch)
35
39
 
40
+ module QueryingPatch
41
+ def find_by_sql(sql, binds = [], preparable: nil, allow_retry: false, auto_include: true, &block)
42
+ models = super(sql, binds, preparable: preparable, allow_retry: allow_retry, &block)
43
+ Goldiloader::AutoIncludeContext.register_models(models) if auto_include
44
+ models
45
+ end
46
+
47
+ # Rails 7.2's async_find_by_sql takes no allow_retry: keyword
48
+ def async_find_by_sql(sql, binds = [], auto_include: true, **options, &block)
49
+ super(sql, binds, **options, &block).then do |models|
50
+ Goldiloader::AutoIncludeContext.register_models(models) if auto_include
51
+ models
52
+ end
53
+ end
54
+ end
55
+ ::ActiveRecord::Base.singleton_class.prepend(::Goldiloader::QueryingPatch)
56
+
36
57
  module RelationPatch
37
58
  def exec_queries
38
- return super if loaded? || !auto_include_value
59
+ return super unless auto_include_value
39
60
 
40
61
  models = super
41
- Goldiloader::AutoIncludeContext.register_models(models, eager_load_values)
62
+ Goldiloader::AutoIncludeContext.register_models(
63
+ models,
64
+ eager_loading? ? eager_load_values | includes_values : nil
65
+ )
42
66
  models
43
67
  end
44
68
 
@@ -98,6 +122,34 @@ module Goldiloader
98
122
  ActiveRecord::Reflection::AssociationReflection.include(::Goldiloader::AssociationReflectionPatch)
99
123
  ActiveRecord::Reflection::ThroughReflection.include(::Goldiloader::AssociationReflectionPatch)
100
124
 
125
+ module ThroughReflectionPatch
126
+ # Scope values that Rails keeps (`distinct`) or whose loss doesn't change the records the association holds
127
+ SCOPE_VALUES_SAFE_TO_DROP = [
128
+ :distinct, :auto_include, :annotate, :extending, :preload, :includes, :references, :optimizer_hints, :create_with
129
+ ].freeze
130
+ private_constant :SCOPE_VALUES_SAFE_TO_DROP
131
+
132
+ # Whether reusing loaded records loses part of this association's own scope, as Rails does when it preloads
133
+ # it from records already loaded: https://github.com/salsify/goldiloader/issues/166
134
+ def scope_lost_by_reusing_loaded_records?(target_klass)
135
+ @scope_lost_by_reusing_loaded_records_cache ||= Hash.new do |cache, target_klass_key|
136
+ cache[target_klass_key] = if scope.nil?
137
+ false
138
+ elsif scope.arity > 0
139
+ true
140
+ else
141
+ # Compare with the unscoped values, which hold the type condition of an STI
142
+ # subclass
143
+ unscoped = target_klass_key.unscoped
144
+ scope_for(unscoped).values.except(*SCOPE_VALUES_SAFE_TO_DROP) !=
145
+ unscoped.values.except(*SCOPE_VALUES_SAFE_TO_DROP)
146
+ end
147
+ end
148
+ @scope_lost_by_reusing_loaded_records_cache[target_klass]
149
+ end
150
+ end
151
+ ActiveRecord::Reflection::ThroughReflection.include(::Goldiloader::ThroughReflectionPatch)
152
+
101
153
  module AssociationPatch
102
154
  extend ActiveSupport::Concern
103
155
 
@@ -130,13 +182,11 @@ module Goldiloader
130
182
  elsif !auto_include?
131
183
  yield
132
184
  elsif owner.auto_include_context.size == 1
133
- # Bypassing the preloader for a single model reduces object allocations by ~5% in benchmarks
134
- result = yield
135
- # As of https://github.com/rails/rails/commit/bd3b28f7f181dce53e872daa23dda101498b8fb4
136
- # ActiveRecord does not use ActiveRecord::Relation#exec_queries to resolve association
137
- # queries
138
- Goldiloader::AutoIncludeContext.register_models(result)
139
- result
185
+ # Bypassing the preloader for a single model reduces object allocations by ~5% in benchmarks.
186
+ # The loaded models need no registering here: as of
187
+ # https://github.com/rails/rails/commit/bd3b28f7f181dce53e872daa23dda101498b8fb4 association queries
188
+ # go through find_by_sql (StatementCache#execute), which registers them, rather than Relation#exec_queries
189
+ yield
140
190
  else
141
191
  Goldiloader::AssociationLoader.load(owner, reflection.name)
142
192
  target
@@ -200,6 +250,67 @@ module Goldiloader
200
250
  record.new_record? || record.changed? || record.destroyed?
201
251
  end
202
252
  end
253
+
254
+ private
255
+
256
+ # Rails 8.2 queries loaded through or source records again when the association's scope filters them
257
+ # (https://github.com/rails/rails/pull/59599, and https://github.com/rails/rails/pull/59797 for nested
258
+ # through associations), so only earlier versions need the check
259
+ def eager_loadable?
260
+ return super unless ::Goldiloader::Compatibility.pre_rails_8_2?
261
+
262
+ super && !scope_lost_by_reusing_loaded_records?(owner, reflection)
263
+ end
264
+
265
+ # A sibling association might have loaded the records this association would reuse e.g. `tags` loads the
266
+ # `post_tags` and their `tag` that `tags_owned_by_users` goes through too. Rails reuses a loaded association
267
+ # even when it holds nil or nothing, at every level of a nested through association, and loses the scope of
268
+ # the association it preloads. Through records loaded without their source records aren't checked: the
269
+ # source records are queried with the association's scope (a scope with a condition on the through table
270
+ # then raises, and one with a condition and an order can lose the order, with or without this check).
271
+ #
272
+ # `as_scoped_source` is true when Rails preloads `chain_reflection` as the source of a scoped through
273
+ # association with that association's scope e.g. the `tag` of each `post_tag` for `tags_owned_by_users`.
274
+ def scope_lost_by_reusing_loaded_records?(record, chain_reflection, as_scoped_source: false)
275
+ return as_scoped_source if loaded_association?(record, chain_reflection.name)
276
+ return false unless chain_reflection.through_reflection?
277
+
278
+ through_reflection = chain_reflection.through_reflection
279
+ source_reflection = chain_reflection.source_reflection
280
+
281
+ # Preloading the through records can lose the through association's own scope
282
+ return true if scope_lost_by_reusing_loaded_records?(record, through_reflection)
283
+
284
+ # Nothing to lose unless a scope applies to the source records or the source has its own through chain
285
+ source_scoped = as_scoped_source ||
286
+ chain_reflection.scope_lost_by_reusing_loaded_records?(chain_reflection.klass)
287
+ return false unless source_scoped || source_reflection.through_reflection?
288
+
289
+ # Preloading the source records of each through record can lose this association's scope or one it inherits
290
+ any_loaded_record?(record, through_reflection) do |through_record|
291
+ scope_lost_by_reusing_loaded_records?(through_record, source_reflection, as_scoped_source: source_scoped)
292
+ end
293
+ end
294
+
295
+ # Whether the block returns true for any loaded record of `chain_reflection` on `record`. When a through
296
+ # association isn't loaded, its records are looked for in what's loaded at each level of its chain.
297
+ def any_loaded_record?(record, chain_reflection, &block)
298
+ if loaded_association?(record, chain_reflection.name)
299
+ target = record.association(chain_reflection.name).target
300
+ target.is_a?(Array) ? target.any?(&block) : !target.nil? && yield(target)
301
+ elsif chain_reflection.through_reflection?
302
+ any_loaded_record?(record, chain_reflection.through_reflection) do |through_record|
303
+ any_loaded_record?(through_record, chain_reflection.source_reflection, &block)
304
+ end
305
+ else
306
+ false
307
+ end
308
+ end
309
+
310
+ # Checks association_cached? first so that no association gets instantiated
311
+ def loaded_association?(record, name)
312
+ record.association_cached?(name) && record.association(name).loaded?
313
+ end
203
314
  end
204
315
  ::ActiveRecord::Associations::HasManyThroughAssociation.prepend(::Goldiloader::ThroughAssociationPatch)
205
316
  ::ActiveRecord::Associations::HasOneThroughAssociation.prepend(::Goldiloader::ThroughAssociationPatch)
@@ -2,6 +2,8 @@
2
2
 
3
3
  module Goldiloader
4
4
  class AutoIncludeContext
5
+ EMPTY_HASH = {}.freeze
6
+
5
7
  attr_reader :models
6
8
 
7
9
  delegate :size, to: :models
@@ -11,8 +13,12 @@ module Goldiloader
11
13
  end
12
14
 
13
15
  def self.register_models(models, included_associations = nil)
16
+ # A lone model builds the same context lazily, so loading one record allocates none upfront
17
+ return if models.size <= 1 && included_associations.blank?
18
+
14
19
  auto_include_context = Goldiloader::AutoIncludeContext.new
15
20
  auto_include_context.register_models(models)
21
+ return if included_associations.blank?
16
22
 
17
23
  Array.wrap(included_associations).each do |included_association|
18
24
  associations = if included_association.is_a?(Hash)
@@ -23,13 +29,14 @@ module Goldiloader
23
29
  nested_associations = if included_association.is_a?(Hash)
24
30
  included_association
25
31
  else
26
- Hash.new([])
32
+ EMPTY_HASH
27
33
  end
28
34
 
29
35
  associations.each do |association|
30
36
  nested_models = models.flat_map do |model|
31
37
  model.association(association).target
32
- end.compact
38
+ end
39
+ nested_models.compact!
33
40
 
34
41
  register_models(nested_models, nested_associations[association])
35
42
  end
@@ -0,0 +1,79 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Goldiloader
4
+ # Gives models, and the models of their loaded associations, new auto include contexts as if they had been
5
+ # loaded with includes: the models passed share one per class, and so do the loaded targets of each association.
6
+ module AutoIncludeContextReset
7
+ extend self
8
+
9
+ def reset(models)
10
+ visited_models = Set.new.compare_by_identity
11
+ reflections = Hash.new { |cache, model_class| cache[model_class] = model_class.reflect_on_all_associations }
12
+ disabled_scopes = {}.compare_by_identity
13
+ groups = [models]
14
+
15
+ until groups.empty?
16
+ groups = groups.flat_map do |group|
17
+ group = group.select { |model| model && !model.new_record? && visited_models.add?(model) }
18
+ # Models of unrelated classes are never loaded together, a polymorphic belongs_to loads one class at a time
19
+ group.group_by { |model| model.class.base_class }.values.flat_map do |class_group|
20
+ Goldiloader::AutoIncludeContext.new.register_models(class_group)
21
+ loaded_target_groups(class_group, reflections, disabled_scopes)
22
+ end
23
+ end
24
+ end
25
+
26
+ models
27
+ end
28
+
29
+ private
30
+
31
+ # The loaded targets of each association share a context, as when preloaded, unless its scope uses
32
+ # auto_include(false): each target then gets its own
33
+ def loaded_target_groups(models, reflections, disabled_scopes)
34
+ targets_by_reflection = {}.compare_by_identity
35
+ single_groups = []
36
+
37
+ models.each do |model|
38
+ reflections[model.class].each do |reflection|
39
+ next unless model.association_cached?(reflection.name)
40
+
41
+ association = model.association(reflection.name)
42
+ next unless association.loaded?
43
+
44
+ # Don't use Array.wrap(), see AutoIncludeContext#register_models
45
+ target = association.target
46
+ next if target.blank?
47
+
48
+ targets = target.is_a?(Array) ? target : [target]
49
+
50
+ if auto_include_disabled?(association, disabled_scopes)
51
+ targets.each { |target_model| single_groups << [target_model] }
52
+ else
53
+ (targets_by_reflection[reflection] ||= []).concat(targets)
54
+ end
55
+ end
56
+ end
57
+
58
+ targets_by_reflection.values.concat(single_groups)
59
+ end
60
+
61
+ # Read from the scope once per class and call, as in AssociationReflectionPatch#eager_loadable?. A scope
62
+ # taking the owner is never evaluated.
63
+ def auto_include_disabled?(association, disabled_scopes)
64
+ # Not the listed reflection, which for a HABTM keeps a scope Rails never calls as is
65
+ reflection = association.reflection
66
+ scope = reflection.scope
67
+ return false if scope.nil? || scope.arity > 0
68
+
69
+ klass = association.klass
70
+ return false if klass.nil?
71
+
72
+ by_class = disabled_scopes[reflection] ||= {}.compare_by_identity
73
+ by_class.fetch(klass) do
74
+ by_class[klass] = !reflection.eager_loadable?(klass) &&
75
+ !Goldiloader::ScopeInfo.new(reflection.scope_for(klass.unscoped)).auto_include?
76
+ end
77
+ end
78
+ end
79
+ end
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Goldiloader
4
+ # Reads models from Rails.cache with their automatic eager loading reset on a cache hit
5
+ module Cache
6
+ extend self
7
+
8
+ # Rails.cache.fetch for a block returning a model, an array of models or nil
9
+ def fetch(name, options = nil)
10
+ cache_hit = true
11
+ result = Rails.cache.fetch(name, options) do |*args|
12
+ cache_hit = false
13
+ value = yield(*args)
14
+ # Checked before Rails caches it
15
+ models(value)
16
+ value
17
+ end
18
+ Goldiloader.reset_auto_include_context(models(result)) if cache_hit
19
+ result
20
+ end
21
+
22
+ private
23
+
24
+ def models(value)
25
+ models = value.is_a?(Array) ? value : [value]
26
+ invalid = models.find { |model| !model.nil? && !model.is_a?(::ActiveRecord::Base) }
27
+ unless invalid.nil?
28
+ raise ArgumentError.new('Goldiloader::Cache.fetch supports a model, an array of models or nil, ' \
29
+ "not #{invalid.class}")
30
+ end
31
+
32
+ models
33
+ end
34
+ end
35
+ end
@@ -2,6 +2,11 @@
2
2
 
3
3
  module Goldiloader
4
4
  module Compatibility
5
- # Currently no Rails version compatibility issues to handle
5
+ # Memoized since it's checked on every through association load, once Active Record is loaded
6
+ def self.pre_rails_8_2?
7
+ return @pre_rails_8_2 if defined?(@pre_rails_8_2)
8
+
9
+ @pre_rails_8_2 = ::ActiveRecord.gem_version < ::Gem::Version.new('8.2.0.alpha')
10
+ end
6
11
  end
7
12
  end
@@ -8,7 +8,8 @@ module Goldiloader
8
8
  end
9
9
 
10
10
  def preloaded(model, cache_name:, key:, &block)
11
- unless preloaded?(cache_name)
11
+ @custom_preloads ||= {}
12
+ preloaded_hash = @custom_preloads.fetch(cache_name) do
12
13
  ids = models.map do |record|
13
14
  key_from_record(record, key)
14
15
  end
@@ -17,11 +18,9 @@ module Goldiloader
17
18
  # given block does not have any references to the model instance as this might
18
19
  # lead to unexpected results. The block will be executed in the context of the
19
20
  # class of the model instead.
20
- block_context = models.first.class
21
- preloaded_hash = block_context.instance_exec(ids, &block)
22
- store_preloaded(cache_name, preloaded_hash)
21
+ @custom_preloads[cache_name] = model.class.instance_exec(ids, &block)
23
22
  end
24
- fetch_preloaded(cache_name, model, key: key)
23
+ preloaded_hash[key_from_record(model, key)]
25
24
  end
26
25
 
27
26
  private
@@ -36,18 +35,5 @@ module Goldiloader
36
35
  record.public_send(key_or_key_list)
37
36
  end
38
37
  end
39
-
40
- def store_preloaded(cache_name, preloaded_hash)
41
- @custom_preloads ||= {}
42
- @custom_preloads[cache_name] = preloaded_hash
43
- end
44
-
45
- def fetch_preloaded(cache_name, instance, key:)
46
- @custom_preloads&.dig(cache_name, key_from_record(instance, key))
47
- end
48
-
49
- def preloaded?(cache_name)
50
- @custom_preloads&.key?(cache_name)
51
- end
52
38
  end
53
39
  end
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Goldiloader
4
- VERSION = '6.0.1'
4
+ VERSION = '6.1.0'
5
5
  end
data/lib/goldiloader.rb CHANGED
@@ -7,6 +7,8 @@ require 'goldiloader/auto_include_context'
7
7
  require 'goldiloader/scope_info'
8
8
  require 'goldiloader/association_options'
9
9
  require 'goldiloader/association_loader'
10
+ require 'goldiloader/auto_include_context_reset'
11
+ require 'goldiloader/cache'
10
12
 
11
13
  ActiveSupport.on_load(:active_record) do
12
14
  # Defer referencing ActiveRecord class until it's loaded
@@ -43,6 +45,13 @@ module Goldiloader
43
45
  ensure
44
46
  self.enabled = old_enabled
45
47
  end
48
+
49
+ # Gives an array of models, and the models of their loaded associations, new auto include contexts as if they
50
+ # had been loaded with includes. Meant for models read back from a cache, which lose theirs, and not for models
51
+ # that were just loaded: see Goldiloader::Cache.fetch.
52
+ def reset_auto_include_context(models)
53
+ Goldiloader::AutoIncludeContextReset.reset(models)
54
+ end
46
55
  end
47
56
 
48
57
  self.globally_enabled = true
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: goldiloader
3
3
  version: !ruby/object:Gem::Version
4
- version: 6.0.1
4
+ version: 6.1.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Joel Turkel
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2026-10-26 00:00:00.000000000 Z
11
+ date: 2026-12-01 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: activerecord
@@ -120,6 +120,20 @@ dependencies:
120
120
  - - ">="
121
121
  - !ruby/object:Gem::Version
122
122
  version: 0.18.0
123
+ - !ruby/object:Gem::Dependency
124
+ name: json
125
+ requirement: !ruby/object:Gem::Requirement
126
+ requirements:
127
+ - - "<"
128
+ - !ruby/object:Gem::Version
129
+ version: '3'
130
+ type: :development
131
+ prerelease: false
132
+ version_requirements: !ruby/object:Gem::Requirement
133
+ requirements:
134
+ - - "<"
135
+ - !ruby/object:Gem::Version
136
+ version: '3'
123
137
  - !ruby/object:Gem::Dependency
124
138
  name: rails
125
139
  requirement: !ruby/object:Gem::Requirement
@@ -251,6 +265,8 @@ files:
251
265
  - lib/goldiloader/association_loader.rb
252
266
  - lib/goldiloader/association_options.rb
253
267
  - lib/goldiloader/auto_include_context.rb
268
+ - lib/goldiloader/auto_include_context_reset.rb
269
+ - lib/goldiloader/cache.rb
254
270
  - lib/goldiloader/compatibility.rb
255
271
  - lib/goldiloader/custom_preloads.rb
256
272
  - lib/goldiloader/scope_info.rb