mongoid 8.0.12 → 8.0.14

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.
Files changed (57) hide show
  1. checksums.yaml +4 -4
  2. data/lib/config/locales/en.yml +26 -0
  3. data/lib/mongoid/association/depending.rb +8 -4
  4. data/lib/mongoid/association/nested/many.rb +38 -3
  5. data/lib/mongoid/association/nested/nested_buildable.rb +14 -0
  6. data/lib/mongoid/association/referenced/has_many/proxy.rb +103 -2
  7. data/lib/mongoid/attributes/readonly.rb +19 -1
  8. data/lib/mongoid/changeable.rb +22 -4
  9. data/lib/mongoid/config.rb +62 -0
  10. data/lib/mongoid/contextual/aggregable/memory.rb +5 -2
  11. data/lib/mongoid/contextual/memory.rb +19 -8
  12. data/lib/mongoid/contextual/none.rb +51 -0
  13. data/lib/mongoid/criteria/queryable/mergeable.rb +12 -0
  14. data/lib/mongoid/criteria/queryable/selectable.rb +109 -0
  15. data/lib/mongoid/criteria/scopable.rb +7 -1
  16. data/lib/mongoid/criteria.rb +45 -1
  17. data/lib/mongoid/document.rb +10 -0
  18. data/lib/mongoid/errors/in_memory_regexp_timeout.rb +26 -0
  19. data/lib/mongoid/errors.rb +1 -0
  20. data/lib/mongoid/field_readable.rb +70 -0
  21. data/lib/mongoid/matchable.rb +6 -1
  22. data/lib/mongoid/matcher/eq_impl_with_regexp.rb +3 -5
  23. data/lib/mongoid/matcher/regex.rb +8 -9
  24. data/lib/mongoid/matcher/regexp_budget.rb +389 -0
  25. data/lib/mongoid/matcher.rb +1 -0
  26. data/lib/mongoid/reloadable.rb +1 -0
  27. data/lib/mongoid/threaded.rb +3 -0
  28. data/lib/mongoid/version.rb +1 -1
  29. data/lib/mongoid/warnings.rb +1 -0
  30. data/spec/integration/app_spec.rb +8 -0
  31. data/spec/integration/associations/has_and_belongs_to_many_spec.rb +17 -2
  32. data/spec/integration/dots_and_dollars_spec.rb +12 -2
  33. data/spec/integration/matcher_operator_data/regex.yml +21 -0
  34. data/spec/integration/matcher_regexp_timeout_spec.rb +215 -0
  35. data/spec/integration/query_operator_guard_spec.rb +89 -0
  36. data/spec/mongoid/association/referenced/has_and_belongs_to_many/proxy_spec.rb +96 -0
  37. data/spec/mongoid/association/referenced/has_many/proxy_spec.rb +228 -0
  38. data/spec/mongoid/attributes/nested_spec.rb +204 -10
  39. data/spec/mongoid/attributes/readonly_dotted_spec.rb +332 -0
  40. data/spec/mongoid/attributes/readonly_spec.rb +387 -0
  41. data/spec/mongoid/changeable_spec.rb +18 -0
  42. data/spec/mongoid/config_spec.rb +7 -0
  43. data/spec/mongoid/contextual/aggregable/memory_spec.rb +91 -0
  44. data/spec/mongoid/contextual/memory_spec.rb +202 -0
  45. data/spec/mongoid/contextual/none_spec.rb +18 -0
  46. data/spec/mongoid/criteria/queryable/selectable_logical_spec.rb +2 -0
  47. data/spec/mongoid/criteria/queryable/selectable_where_spec.rb +235 -0
  48. data/spec/mongoid/criteria_spec.rb +19 -0
  49. data/spec/mongoid/findable_spec.rb +14 -0
  50. data/spec/mongoid/matcher/regexp_budget_spec.rb +576 -0
  51. data/spec/mongoid/scopable_spec.rb +116 -2
  52. data/spec/spec_helper.rb +8 -0
  53. data/spec/support/models/delete_all_account.rb +10 -0
  54. data/spec/support/models/delete_all_item.rb +9 -0
  55. data/spec/support/models/delete_all_scoped_item.rb +11 -0
  56. data/spec/support/models/delete_all_tag.rb +7 -0
  57. metadata +1862 -1826
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: f08452ead2923923372a78e2e981543ced23f0353ece5109a3f19411e29a9e29
4
- data.tar.gz: 2ec3d115f4be09f2ca9b04704b965bdffc266eb047ca2701ecdc7018353be5fc
3
+ metadata.gz: 25cd7a90ef28bbf811d80c2f11edb549f48a9b038775b7487dec2a3c10a320a0
4
+ data.tar.gz: 4f3a7ab5cb3f2315d78631e8c8e7bc4007e17ebd26c9cda0fcc4d8bb8572458a
5
5
  SHA512:
6
- metadata.gz: 88300684eb21ca82ff1a43c58dcb5dbe0d45d8d5c187d569c31b6e1653293ffedbcc699bccf92941a47eb83ce9d11a9dcb1c1c51a2db5af70d1a1ed0db459a3a
7
- data.tar.gz: 2b6207d2c5b2d94bcd24b7299ed4dc47bc1f5df5035c887253b4aa456dabe4653b19de6da5db094b109aea5ea2455754c15c8e19a6c84231102fe613d562948f
6
+ metadata.gz: 938ed265403968f8f571b3be0452dcebd51fd855c724023d438217fd2130e449e410e83b0babbe44aa6757aaaa2f01d906fd40fabdea7f6f558375ef2640ef12
7
+ data.tar.gz: b3975411c3e49d8549a9bc5ef145d819f76c563510037245065719c5767871fe1c3419fcba125568917b59d08c01e455655650f6bdf9846d0f2a3cff77ac2a04
@@ -105,6 +105,32 @@ en:
105
105
  A collation option is only supported if the query is executed on a MongoDB server
106
106
  with version >= 3.4."
107
107
  resolution: "Remove the collation option from the query."
108
+ in_memory_regexp_timeout:
109
+ message: "Evaluating this query in memory exceeded the %{limit} second
110
+ limit that applies to conditions containing a regular expression."
111
+ summary: "Mongoid evaluates some conditions in the calling thread
112
+ rather than sending them to the server: queries against an embedded
113
+ association, removing documents from an association by condition,
114
+ and Document#_matches?. A regular expression in such a condition
115
+ runs locally. Mongoid limits the total time one in-memory
116
+ evaluation may spend matching, because both the cost of a single
117
+ match and the number of matches performed grow with the condition,
118
+ and a pattern built from end-user input can be made to consume an
119
+ unbounded amount of CPU. The limit is cumulative over the whole
120
+ evaluation rather than per match. Where the Ruby in use offers no
121
+ per-Regexp timeout the limit is enforced as wall clock over the
122
+ whole in-memory evaluation, so there it can be exceeded by a large
123
+ scan even when the pattern itself is cheap."
124
+ resolution: "Check whether the pattern in this query comes from user
125
+ input; if it does, validate it before querying. If the query is
126
+ legitimate and simply large, raise
127
+ Mongoid::Config.in_memory_regexp_time_limit, or set it to nil to
128
+ remove the limit entirely. The limit in force is the smaller of
129
+ that setting and any global Regexp.timeout the application has set,
130
+ so check both. On JRuby, and on MRI before 3.2, there is no
131
+ per-Regexp timeout, so what the limit bounds there is the elapsed
132
+ time of the whole in-memory evaluation rather than the time spent
133
+ matching."
108
134
  invalid_config_file:
109
135
  message: "Invalid configuration file: %{path}."
110
136
  summary: "Your mongoid.yml configuration file does not contain the
@@ -11,11 +11,15 @@ module Mongoid
11
11
  included do
12
12
  class_attribute :dependents
13
13
 
14
+ # Note the leading underscore: without it, ActiveSupport's
15
+ # class_attribute would generate a helper method for this attribute
16
+ # that collides with one it generates for :dependents.
17
+ #
14
18
  # @api private
15
- class_attribute :dependents_owner
19
+ class_attribute :_dependents_owner
16
20
 
17
21
  self.dependents = []
18
- self.dependents_owner = self
22
+ self._dependents_owner = self
19
23
  end
20
24
 
21
25
  class_methods do
@@ -50,9 +54,9 @@ module Mongoid
50
54
  def self.define_dependency!(association)
51
55
  validate!(association)
52
56
  association.inverse_class.tap do |klass|
53
- if klass.dependents_owner != klass
57
+ if klass._dependents_owner != klass
54
58
  klass.dependents = []
55
- klass.dependents_owner = klass
59
+ klass._dependents_owner = klass
56
60
  end
57
61
 
58
62
  if association.dependent && !klass.dependents.include?(association)
@@ -169,7 +169,7 @@ module Mongoid
169
169
  # @param [ Hash ] attrs The single document attributes to process.
170
170
  def update_nested_relation(parent, id, attrs)
171
171
  first = existing.first
172
- converted = first ? convert_id(first.class, id) : id
172
+ converted = convert_id(first ? first.class : association.klass, id)
173
173
 
174
174
  if existing.where(_id: converted).exists?
175
175
  # document exists in association
@@ -179,11 +179,46 @@ module Mongoid
179
179
  else
180
180
  update_document(doc, attrs)
181
181
  end
182
- else
182
+ elsif association.embedded?
183
+ raise Errors::DocumentNotFound.new(association.klass, id)
184
+ elsif destroyable?(attrs)
185
+ # A destroy of a document that is not in the association is
186
+ # ignored, rather than reaching for it outside the association.
187
+ nil
188
+ elsif Mongoid.allow_reparenting_via_nested_attributes?
189
+ Mongoid::Warnings.warn_reparenting_via_nested_attributes
190
+
183
191
  # push existing document to association
184
192
  doc = association.klass.unscoped.find(converted)
193
+ # find returns nil instead of raising when
194
+ # Mongoid.raise_not_found_error is false; a missing document
195
+ # must still be an error here, consistent with the other
196
+ # not-found branches.
197
+ raise Errors::DocumentNotFound.new(association.klass, id) if doc.nil?
198
+
185
199
  update_document(doc, attrs)
186
- existing.push(doc) unless destroyable?(attrs)
200
+ existing.push(doc)
201
+ else
202
+ raise Errors::DocumentNotFound.new(association.klass, not_found_params(parent, id))
203
+ end
204
+ end
205
+
206
+ # The params to report when an id in the nested attributes could not
207
+ # be resolved within the association.
208
+ #
209
+ # @api private
210
+ #
211
+ # @param [ Document ] parent The parent document.
212
+ # @param [ String | BSON::ObjectId ] id of the related document.
213
+ #
214
+ # @return [ Hash | Object ] The params for the not found error.
215
+ def not_found_params(parent, id)
216
+ if association.is_a?(Association::Referenced::HasAndBelongsToMany)
217
+ # A many-to-many association has no foreign key on the child, so
218
+ # the id is only ever resolved within the association itself.
219
+ id
220
+ else
221
+ { _id: id, association.foreign_key => parent.id }
187
222
  end
188
223
  end
189
224
  end
@@ -53,12 +53,26 @@ module Mongoid
53
53
  # @example Convert the id.
54
54
  # builder.convert_id(Person, "4d371b444835d98b8b000010")
55
55
  #
56
+ # Ids arriving from a form are always scalars. A Hash or an Array
57
+ # here means the parameters were crafted, and letting one through
58
+ # would turn the id into a query operator, so they are rejected.
59
+ #
56
60
  # @param [ Class ] klass The class we're trying to convert for.
57
61
  # @param [ String ] id The id, usually coming from the form.
58
62
  #
59
63
  # @return [ BSON::ObjectId | String | Object ] The converted id.
64
+ #
65
+ # @raise [ Errors::DocumentNotFound ] if the id is not a scalar, or
66
+ # cannot be converted to the type the class uses for its ids.
67
+ # The BSON::Error rescue is defensive: a value that reaches
68
+ # BSON::ObjectId.mongoize and raises there must not surface as an
69
+ # unhandled BSON error in the caller.
60
70
  def convert_id(klass, id)
71
+ raise Errors::DocumentNotFound.new(klass, id) if id.is_a?(::Hash) || id.is_a?(::Array)
72
+
61
73
  klass.using_object_ids? ? BSON::ObjectId.mongoize(id) : id
74
+ rescue BSON::Error
75
+ raise Errors::DocumentNotFound.new(klass, id)
62
76
  end
63
77
  end
64
78
  end
@@ -476,13 +476,114 @@ module Mongoid
476
476
  #
477
477
  # @return [ Integer ] The number of documents deleted.
478
478
  def remove_all(conditions = nil, method = :delete_all)
479
- selector = conditions || {}
480
- removed = klass.send(method, selector.merge!(criteria.selector))
479
+ # Conjoin the conditions with the association selector so that a
480
+ # key present in both is intersected rather than overwritten. This
481
+ # also leaves the caller's Hash alone.
482
+ selector = criteria.where(conditions || {}).selector
483
+
484
+ # Scanning before the delete means scanning only what is already in
485
+ # memory, so it is only done where there is a pattern whose cost has
486
+ # to be bounded. Everywhere else the delete comes first and the scan
487
+ # sees the survivors, which is what this association has always
488
+ # done.
489
+ #
490
+ # The limit is read once and carried into whichever branch is taken.
491
+ # Letting the branch below ask again would read it a second time,
492
+ # across a server round trip, and a limit that had become positive
493
+ # in the meantime would put a deadline on the delete_if -- a query,
494
+ # and an unbind of every match -- which is the arrangement this
495
+ # branch exists to avoid.
496
+ limit = Matcher::RegexpBudget.limit_for(selector)
497
+ return remove_all_bounded(selector, method, limit) if limit
498
+
499
+ removed = klass.send(method, selector)
500
+
501
+ # No scope around this. The scan runs after the delete, so the
502
+ # association this loads comes back holding only what the delete did
503
+ # not match, and there is no pattern here to bound in any case.
504
+ # Opening a scope would save _matches? from deciding once per
505
+ # document -- 0.48us against 1.74us for the match itself -- but a
506
+ # scope with nothing to bound suppresses that decision for
507
+ # everything nested inside it, and loading the association runs
508
+ # find callbacks. A pattern in a selector one of those evaluates
509
+ # would go unguarded, which costs more than the saving is worth on a
510
+ # path that has just made two round trips.
481
511
  _target.delete_if do |doc|
482
512
  doc._matches?(selector).tap do |b|
483
513
  unbind_one(doc) if b
484
514
  end
485
515
  end
516
+
517
+ removed
518
+ end
519
+
520
+ # Deletes all related documents matching a selector that carries a
521
+ # regular expression, with the whole scan under one regexp budget.
522
+ #
523
+ # The scan runs before anything is deleted, so a budget that runs out
524
+ # leaves both the database and the association untouched rather than
525
+ # reporting a failure for a delete that has already happened. It also
526
+ # means the budget is closed by the time the association is mutated,
527
+ # so where the budget is enforced with Timeout there is no window for
528
+ # the exception to land in the middle of an unbind.
529
+ #
530
+ # @param [ Hash ] selector The selector to delete with.
531
+ # @param [ Symbol ] method The deletion method to call.
532
+ # @param [ Float ] limit The seconds the scan may spend, as read by
533
+ # the caller when it chose this path.
534
+ #
535
+ # @return [ Integer ] The number of documents deleted.
536
+ def remove_all_bounded(selector, method, limit)
537
+ # Only what the association already holds. Iterating it instead
538
+ # would load the whole association before the delete, and for a
539
+ # broad pattern that is every document the association has: /.*/ is
540
+ # both the cheapest pattern an attacker can supply and the one that
541
+ # matches everything, so bounding the cost of the matching would
542
+ # have been paid for with an unbounded amount of memory. Nothing is
543
+ # missed by not loading, because the server evaluates the same
544
+ # selector for the delete itself.
545
+ #
546
+ # It also means the scan runs no query, so no deadline of ours can
547
+ # land on one. Where the budget is enforced with Timeout, covering
548
+ # a query would report a slow network as a regexp timeout and could
549
+ # deliver the asynchronous exception inside the driver's socket
550
+ # read.
551
+ documents = _target.in_memory
552
+
553
+ matching = Matcher::RegexpBudget.open_with(limit) do
554
+ documents.select { |doc| doc._matches?(selector) }
555
+ end
556
+
557
+ removed = klass.send(method, selector)
558
+
559
+ # The ids are already known to be in memory, so the loaded and added
560
+ # documents can be dropped directly. Enumerable#delete would look
561
+ # each one up by id and stop at the first hash that has it, which
562
+ # removes the wrong instance when both hashes hold one for the same
563
+ # id. Enumerable#delete_if drops it from both, as this does, but
564
+ # only after load_all!, which is the load this scan exists to avoid.
565
+ #
566
+ # Which documents get unbound has always depended on which ones
567
+ # happened to be in memory, and scanning only what is in memory
568
+ # keeps that. It matters for has_and_belongs_to_many, whose
569
+ # unbind_one pulls the id out of the foreign key array on _base and
570
+ # marks it dirty; the scan used to run after the delete, against an
571
+ # association that a cold proxy had just reloaded as holding only
572
+ # the survivors, so nothing matched and nothing was unbound.
573
+ #
574
+ # TODO: unbinding should not depend on what was in memory. Every
575
+ # matched document leaves the association, so every one of them
576
+ # should be unbound, which would also stop _base's foreign key
577
+ # array from keeping ids that no longer resolve. That is a
578
+ # behaviour change for has_and_belongs_to_many and belongs in a
579
+ # ticket of its own, with a release note; it should not ride along
580
+ # on this one.
581
+ matching.each do |doc|
582
+ unbind_one(doc)
583
+ _target._loaded.delete(doc._id)
584
+ _target._added.delete(doc._id)
585
+ end
586
+
486
587
  removed
487
588
  end
488
589
 
@@ -22,7 +22,25 @@ module Mongoid
22
22
  # @return [ true | false ] If the document is new, or if the field is not
23
23
  # readonly.
24
24
  def attribute_writable?(name)
25
- new_record? || (!readonly_attributes.include?(name) && _loaded?(name))
25
+ return true if new_record?
26
+
27
+ readonly = self.class.readonly_attributes
28
+ return _loaded?(name) if readonly.empty?
29
+
30
+ path = name.to_s
31
+ return false if readonly.include?(path)
32
+
33
+ readonly.each do |field|
34
+ # A readonly attribute that is a declared field with a dotted name
35
+ # is that literal field, not a path prefix.
36
+ next if field.include?('.') && self.class.fields.key?(field)
37
+
38
+ # A path that is a declared field with a dotted name addresses that
39
+ # literal field, not a descendant of the readonly attribute.
40
+ return false if path.start_with?("#{field}.") && !self.class.fields.key?(path)
41
+ end
42
+
43
+ _loaded?(name)
26
44
  end
27
45
 
28
46
  private
@@ -72,6 +72,7 @@ module Mongoid
72
72
  @previous_attributes = attributes.dup
73
73
  reset_atomic_updates!
74
74
  changed_attributes.clear
75
+ @pre_create_changed_attributes = nil
75
76
  end
76
77
 
77
78
  # Things that need to execute after a document has been persisted.
@@ -164,6 +165,13 @@ module Mongoid
164
165
  def attribute_changed?(attr)
165
166
  attr = database_field_name(attr)
166
167
  return false unless changed_attributes.key?(attr)
168
+ # An in-place change to a readonly attribute of a persisted document
169
+ # is not part of the dirty tracking API and will not be persisted. A
170
+ # change tracked while the document was new initializes the document,
171
+ # and new documents may set readonly attributes, so it is still
172
+ # reported as a saved change.
173
+ return false if !new_record? && self.class.readonly_attributes.include?(attr) &&
174
+ !@pre_create_changed_attributes&.include?(attr)
167
175
  changed_attributes[attr] != attributes[attr]
168
176
  end
169
177
 
@@ -220,9 +228,16 @@ module Mongoid
220
228
  #
221
229
  # @return [ Object ] The old value.
222
230
  def attribute_will_change!(attr)
223
- unless changed_attributes.key?(attr)
224
- changed_attributes[attr] = read_raw_attribute(attr).__deep_copy__
225
- end
231
+ return if changed_attributes.key?(attr)
232
+
233
+ # The snapshot is taken for readonly attributes as well. Their changes
234
+ # are hidden from the dirty tracking API (see #attribute_changed?), but
235
+ # the snapshot is needed to reset an in-place change. Changes tracked
236
+ # while the document is new initialize it, and new documents may set
237
+ # readonly attributes, so they are remembered here and still reported
238
+ # when the document is created.
239
+ (@pre_create_changed_attributes ||= ::Set.new).add(attr) if new_record?
240
+ changed_attributes[attr] = read_raw_attribute(attr).__deep_copy__
226
241
  end
227
242
 
228
243
  # Set the attribute back to its old value.
@@ -235,7 +250,10 @@ module Mongoid
235
250
  # @return [ Object ] The old value.
236
251
  def reset_attribute!(attr)
237
252
  attr = database_field_name(attr)
238
- attributes[attr] = changed_attributes.delete(attr) if attribute_changed?(attr)
253
+ return unless changed_attributes.key?(attr)
254
+ return if changed_attributes[attr] == attributes[attr]
255
+
256
+ attributes[attr] = changed_attributes.delete(attr)
239
257
  end
240
258
 
241
259
  def reset_attribute_to_default!(attr)
@@ -165,6 +165,68 @@ module Mongoid
165
165
  # See https://jira.mongodb.org/browse/MONGOID-5658 for more details.
166
166
  option :around_callbacks_for_embeds, default: true
167
167
 
168
+ # The maximum number of seconds that evaluating a single query in memory
169
+ # may spend executing regular expressions. Queries against an embedded
170
+ # association are evaluated in the calling thread, so a pattern built from
171
+ # user input runs locally and can otherwise consume unbounded CPU. The
172
+ # limit is cumulative over the whole query, since cost grows with the
173
+ # number of documents and conditions as well as with the pattern.
174
+ #
175
+ # Set to nil to remove the limit. On Ruby 3.2 and later the remaining
176
+ # budget is compiled into the pattern, so the limit counts only the time
177
+ # spent matching. Earlier Rubies have no per-Regexp timeout, so the query
178
+ # is bounded with Timeout instead and the limit is wall clock over the
179
+ # whole in-memory evaluation.
180
+ #
181
+ # See https://jira.mongodb.org/browse/MONGOID-5981 for details.
182
+ option :in_memory_regexp_time_limit, default: 5.0
183
+
184
+ # When false (default), query operators are restricted when building a
185
+ # selector, so that user-supplied input reaching the query builder cannot
186
+ # make MongoDB execute arbitrary JavaScript. Two rules are enforced:
187
+ #
188
+ # - An operator at the top level of an expression must appear in
189
+ # +Criteria::Queryable::Selectable::ALLOWED_QUERY_OPERATORS+.
190
+ # - +$where+, +$function+, and +$accumulator+ are rejected at any depth,
191
+ # including inside +$expr+ and the logical operators.
192
+ #
193
+ # This applies to every query method that accepts an expression, including
194
+ # +where+, +find_by+, +and+, +or+, +nor+, +not+, +any_of+, and +none_of+.
195
+ # It also governs the string form of +where+, e.g.
196
+ # +where("this.name == 'admin'")+, which the server evaluates as +$where+.
197
+ # Applications relying on that form must set this option to true.
198
+ #
199
+ # The APIs that request JavaScript explicitly, +Criteria#for_js+ and
200
+ # +js_query+, are unaffected: there the developer has asked for it.
201
+ #
202
+ # Set to true to restore the unrestricted pass-through behavior.
203
+ #
204
+ # Note that this option is deliberately not tied to +load_defaults+: an
205
+ # application that has opted into older defaults still gets the guard, and
206
+ # must set this option explicitly to turn it off.
207
+ #
208
+ # See https://jira.mongodb.org/browse/MONGOID-5939,
209
+ # https://jira.mongodb.org/browse/MONGOID-5993,
210
+ # https://jira.mongodb.org/browse/MONGOID-5994 for details.
211
+ option :allow_unsafe_query_operators, default: false
212
+
213
+ # When this flag is true, it will be possible to add a record to a
214
+ # "has_many" or "has_and_belongs_to_many" association by passing that
215
+ # record's id in the nested attributes for another parent record, even
216
+ # when the record does not already belong to that association. For a
217
+ # "has_many" association this moves the record to the new parent.
218
+ #
219
+ # When this flag is false, an id in nested attributes is only resolved
220
+ # within the association itself, and anything else raises an error.
221
+ #
222
+ # The default is `false`. Note that allowing reparenting via nested attributes
223
+ # is a potential security risk, since it could allow a malicious user to move
224
+ # records that they do not own to a parent record that they do own.
225
+ #
226
+ # This option will be removed in Mongoid 10, and the only behavior will be
227
+ # as if this option were set to false.
228
+ option :allow_reparenting_via_nested_attributes, default: false
229
+
168
230
  # Has Mongoid been configured? This is checking that at least a valid
169
231
  # client config exists.
170
232
  #
@@ -1,10 +1,13 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require 'mongoid/field_readable'
4
+
3
5
  module Mongoid
4
6
  module Contextual
5
7
  module Aggregable
6
8
  # Contains behavior for aggregating values in memory.
7
9
  module Memory
10
+ include FieldReadable
8
11
 
9
12
  # Get all the aggregate values for the provided field.
10
13
  # Provided for interface consistency with Aggregable::Mongo.
@@ -29,7 +32,7 @@ module Mongoid
29
32
  #
30
33
  # @return [ Numeric ] The average.
31
34
  def avg(field)
32
- total = count { |doc| !doc.send(field).nil? }
35
+ total = count { |doc| !read_field_value(doc, field).nil? }
33
36
  return nil unless total > 0
34
37
 
35
38
  total = total.to_f if total.is_a?(Integer)
@@ -114,7 +117,7 @@ module Mongoid
114
117
  def aggregate_by(field, method)
115
118
  return nil unless any?
116
119
 
117
- map { |doc| doc.public_send(field) }.compact.public_send(method)
120
+ map { |doc| read_field_value(doc, field) }.compact.public_send(method)
118
121
  end
119
122
  end
120
123
  end
@@ -2,6 +2,7 @@
2
2
 
3
3
  require "mongoid/contextual/aggregable/memory"
4
4
  require "mongoid/association/eager_loadable"
5
+ require "mongoid/field_readable"
5
6
 
6
7
  module Mongoid
7
8
  module Contextual
@@ -11,6 +12,7 @@ module Mongoid
11
12
  include Association::EagerLoadable
12
13
  include Queryable
13
14
  include Positional
15
+ include FieldReadable
14
16
 
15
17
  # @attribute [r] root The root document.
16
18
  # @attribute [r] path The atomic path.
@@ -79,7 +81,7 @@ module Mongoid
79
81
  # @return [ Array<Object> ] The distinct values for the field.
80
82
  def distinct(field)
81
83
  if Mongoid.legacy_pluck_distinct
82
- documents.map{ |doc| doc.send(field) }.uniq
84
+ documents.map { |doc| read_field_value(doc, field) }.uniq
83
85
  else
84
86
  pluck(field).uniq
85
87
  end
@@ -141,10 +143,20 @@ module Mongoid
141
143
  # @param [ Criteria ] criteria The criteria.
142
144
  def initialize(criteria)
143
145
  @criteria, @klass = criteria, criteria.klass
144
- @documents = criteria.documents.select do |doc|
145
- @root ||= doc._root
146
- @collection ||= root.collection
147
- doc._matches?(criteria.selector)
146
+
147
+ # Resolving the collection can build a Mongo::Client the first time it
148
+ # runs, so it happens before the budget opens. Where the budget is
149
+ # enforced with Timeout the exception is asynchronous, and landing in
150
+ # the middle of that would leave a half-built client behind.
151
+ if (first = criteria.documents.first)
152
+ @root = first._root
153
+ @collection = @root.collection
154
+ end
155
+
156
+ # One regexp budget covers the whole scan, so that the limit bounds the
157
+ # query rather than each document individually.
158
+ @documents = Matcher::RegexpBudget.open(criteria.selector) do
159
+ criteria.documents.select { |doc| doc._matches?(criteria.selector) }
148
160
  end
149
161
  apply_sorting
150
162
  apply_options
@@ -534,11 +546,10 @@ module Mongoid
534
546
  # _translations hash so that we can get the specified translation in
535
547
  # the remaining
536
548
  if field&.localized?
537
- document.send("#{segment}_translations")
549
+ document.public_send("#{segment}_translations")
538
550
  end
539
551
  end
540
- meth = klass.aliased_associations[segment] || segment
541
- res.nil? ? document.try(meth) : res
552
+ res.nil? ? read_field_value(document, segment) : res
542
553
  elsif document.is_a?(Hash)
543
554
  # TODO: Remove the indifferent access when implementing MONGOID-5410.
544
555
  document.key?(segment.to_s) ?
@@ -45,6 +45,31 @@ module Mongoid
45
45
  other.is_a?(None)
46
46
  end
47
47
 
48
+ # Delete all documents in the database that match the selector. There
49
+ # are no documents in the null context, so nothing is deleted.
50
+ #
51
+ # @example Delete all the documents.
52
+ # context.delete
53
+ #
54
+ # @return [ Integer ] Always zero.
55
+ def delete
56
+ 0
57
+ end
58
+ alias delete_all delete
59
+
60
+ # Destroy all documents in the database that match the selector. There
61
+ # are no documents in the null context, so nothing is destroyed and no
62
+ # callbacks are run.
63
+ #
64
+ # @example Destroy all the documents.
65
+ # context.destroy
66
+ #
67
+ # @return [ Integer ] Always zero.
68
+ def destroy
69
+ 0
70
+ end
71
+ alias destroy_all destroy
72
+
48
73
  # Get the distinct field values in null context.
49
74
  #
50
75
  # @example Get the distinct values in null context.
@@ -119,6 +144,32 @@ module Mongoid
119
144
  {}
120
145
  end
121
146
 
147
+ # Update the first matching document atomically. There are no documents
148
+ # in the null context, so nothing is updated.
149
+ #
150
+ # @example Update the matching document.
151
+ # context.update(name: "Smiths")
152
+ #
153
+ # @param [ Hash ] attributes The new attributes for the document.
154
+ #
155
+ # @return [ nil | false ] False if no attributes were provided.
156
+ def update(attributes = nil, _opts = {})
157
+ attributes ? nil : false
158
+ end
159
+
160
+ # Update all the matching documents atomically. There are no documents
161
+ # in the null context, so nothing is updated.
162
+ #
163
+ # @example Update all the matching documents.
164
+ # context.update_all(name: "Smiths")
165
+ #
166
+ # @param [ Hash ] attributes The new attributes for each document.
167
+ #
168
+ # @return [ nil | false ] False if no attributes were provided.
169
+ def update_all(attributes = nil, _opts = {})
170
+ attributes ? nil : false
171
+ end
172
+
122
173
  # Create the new null context.
123
174
  #
124
175
  # @example Create the new context.
@@ -325,6 +325,10 @@ module Mongoid
325
325
  end
326
326
  end
327
327
  end
328
+ # Every query method that takes a user-supplied expression normalizes
329
+ # it here, so this is where the operator guard is enforced. See
330
+ # Selectable#_mongoid_validate_operators! for what it does not cover.
331
+ _mongoid_validate_operators!(result)
328
332
  result
329
333
  end
330
334
 
@@ -343,6 +347,14 @@ module Mongoid
343
347
  if criterion.is_a?(Selectable)
344
348
  criterion = criterion.selector
345
349
  end
350
+
351
+ # The __override__ path writes to the selector directly, so it
352
+ # bypasses _mongoid_expand_keys where the operator guard normally
353
+ # runs. Enforce the guard here so chained override methods
354
+ # (elem_match, exists, eq, gt, in, etc.) cannot smuggle $where or
355
+ # other JavaScript operators under strict mode.
356
+ _mongoid_validate_operators!(criterion)
357
+
346
358
  selection(criterion) do |selector, field, value|
347
359
  expression = prepare(field, operator, value)
348
360
  existing = selector[field]