Skip to content

Commit

Permalink
MONGOID-5805 Short-circuit the logic in extract_attribute to fix perf…
Browse files Browse the repository at this point in the history
…ormance regression (backport to 8.1-stable) (#5869)

* short-circuit the logic in extract_attribute to fix performance regression

* short circuit on anything that's not a document or hash

* handle hash/string keys
  • Loading branch information
jamis authored Sep 23, 2024
1 parent a549de2 commit 9e2d6ff
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
16 changes: 15 additions & 1 deletion lib/mongoid/matcher.rb
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,25 @@ module Matcher
# from and behaves identically to association traversal for the purposes
# of, for example, subsequent array element retrieval.
#
# @param [ Document | Hash ] document The document to extract from.
# @param [ Document | Hash | String ] document The document to extract from.
# @param [ String ] key The key path to extract.
#
# @return [ Object | Array ] Field value or values.
module_function def extract_attribute(document, key)
# The matcher system will wind up sending atomic values to this as well,
# when attepting to match more complex types. If anything other than a
# Document or a Hash is given, we'll short-circuit the logic and just
# return an empty array.
return [] unless document.is_a?(Hash) || document.is_a?(Document)

# Performance optimization; if the key does not include a '.' character,
# it must reference an immediate attribute of the document.
unless key.include?('.')
hash = document.respond_to?(:attributes) ? document.attributes : document
key = find_exact_key(hash, key)
return key ? [ hash[key] ] : []
end

if document.respond_to?(:as_attributes, true)
# If a document has hash fields, as_attributes would keep those fields
# as Hash instances which do not offer indifferent access.
Expand Down
4 changes: 4 additions & 0 deletions spec/mongoid/association/referenced/belongs_to/proxy_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -749,6 +749,10 @@
person.save!
end

# NOTE: there as a bad interdependency here, with the auto_save_spec.rb
# file. If auto_save_spec.rb runs before this, the following specs fail
# with "undefined method `nullify' for an instance of Person".

context "when parent exists" do

context "when child is destroyed" do
Expand Down

0 comments on commit 9e2d6ff

Please sign in to comment.