mongoid 8.0.11 → 8.0.13

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 (47) 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 +100 -1
  7. data/lib/mongoid/clients/factory.rb +4 -0
  8. data/lib/mongoid/config.rb +62 -0
  9. data/lib/mongoid/contextual/aggregable/memory.rb +5 -2
  10. data/lib/mongoid/contextual/memory.rb +18 -7
  11. data/lib/mongoid/criteria/queryable/mergeable.rb +12 -0
  12. data/lib/mongoid/criteria/queryable/selectable.rb +109 -0
  13. data/lib/mongoid/errors/in_memory_regexp_timeout.rb +26 -0
  14. data/lib/mongoid/errors.rb +1 -0
  15. data/lib/mongoid/extensions/hash.rb +27 -1
  16. data/lib/mongoid/field_readable.rb +70 -0
  17. data/lib/mongoid/matchable.rb +6 -1
  18. data/lib/mongoid/matcher/eq_impl_with_regexp.rb +3 -5
  19. data/lib/mongoid/matcher/regex.rb +8 -9
  20. data/lib/mongoid/matcher/regexp_budget.rb +389 -0
  21. data/lib/mongoid/matcher.rb +1 -0
  22. data/lib/mongoid/threaded.rb +3 -0
  23. data/lib/mongoid/version.rb +1 -1
  24. data/lib/mongoid/warnings.rb +1 -0
  25. data/spec/integration/app_spec.rb +8 -0
  26. data/spec/integration/associations/has_and_belongs_to_many_spec.rb +17 -2
  27. data/spec/integration/dots_and_dollars_spec.rb +12 -2
  28. data/spec/integration/matcher_operator_data/regex.yml +21 -0
  29. data/spec/integration/matcher_regexp_timeout_spec.rb +215 -0
  30. data/spec/integration/query_operator_guard_spec.rb +89 -0
  31. data/spec/mongoid/association/referenced/has_and_belongs_to_many/proxy_spec.rb +48 -0
  32. data/spec/mongoid/association/referenced/has_many/proxy_spec.rb +145 -0
  33. data/spec/mongoid/attributes/nested_spec.rb +204 -10
  34. data/spec/mongoid/clients/factory_spec.rb +30 -0
  35. data/spec/mongoid/contextual/aggregable/memory_spec.rb +91 -0
  36. data/spec/mongoid/contextual/memory_spec.rb +177 -0
  37. data/spec/mongoid/criteria/queryable/extensions/bignum_spec.rb +2 -1
  38. data/spec/mongoid/criteria/queryable/extensions/fixnum_spec.rb +2 -1
  39. data/spec/mongoid/criteria/queryable/selectable_logical_spec.rb +2 -0
  40. data/spec/mongoid/criteria/queryable/selectable_where_spec.rb +235 -0
  41. data/spec/mongoid/criteria_spec.rb +2 -0
  42. data/spec/mongoid/extensions/hash_spec.rb +236 -0
  43. data/spec/mongoid/matcher/regexp_budget_spec.rb +570 -0
  44. data/spec/shared/CANDIDATE.md +28 -0
  45. data/spec/shared/lib/mrss/spec_organizer.rb +32 -3
  46. data/spec/shared/shlib/server.sh +1 -1
  47. metadata +13 -2
@@ -135,6 +135,27 @@
135
135
  $regex: bar
136
136
  matches: false
137
137
 
138
+ # Object#=~ is gone as of Ruby 3.2, so an element that cannot be matched
139
+ # against has to be skipped rather than passed to =~.
140
+ - name: array field value - element that cannot be matched against
141
+ document:
142
+ title:
143
+ - 42
144
+ - foo
145
+ query:
146
+ title:
147
+ $regex: foo
148
+ matches: true
149
+
150
+ - name: array field value - no element can be matched against
151
+ document:
152
+ title:
153
+ - 42
154
+ query:
155
+ title:
156
+ $regex: foo
157
+ matches: false
158
+
138
159
  - name: true field value
139
160
  document:
140
161
  title: true
@@ -0,0 +1,215 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'benchmark'
4
+ require 'spec_helper'
5
+
6
+ describe 'in-memory regexp time limit' do
7
+ # See the comment in spec/mongoid/matcher/regexp_budget_spec.rb: costly to
8
+ # match but bounded on every supported Ruby. A pattern relying on nested
9
+ # quantifiers would hang before Ruby 3.2, where the examples that have no
10
+ # interrupt available could not stop it.
11
+ let(:slow_pattern) { "(?:#{(1..300).map { |i| "a#{i}" }.join('|')})Z" }
12
+ let(:slow_street) { 'a' * 5_000 }
13
+
14
+ let(:person) do
15
+ # Address derives its _id from the street, so the streets have to differ or
16
+ # the embedded association collapses to a single document.
17
+ Person.new(addresses: Array.new(30) { |i| Address.new(street: "#{slow_street}#{i}") })
18
+ end
19
+
20
+ let(:one_address) { Person.new(addresses: [ Address.new(street: slow_street) ]) }
21
+
22
+ # What one match of the fixture costs on the machine running the suite. It
23
+ # varies by more than an order of magnitude between implementations - around
24
+ # 6ms on MRI, 110ms on JRuby - so the examples below calibrate against a
25
+ # measurement instead of hard-coding a threshold that only holds on one.
26
+ let(:single_match_cost) do
27
+ regexp = Regexp.new(slow_pattern)
28
+ 3.times { slow_street =~ regexp }
29
+ Benchmark.realtime { slow_street =~ regexp }
30
+ end
31
+
32
+ # Comfortably more than one match, comfortably less than twenty. The examples
33
+ # only need the ordering to hold, so the margin either side is wide.
34
+ let(:calibrated_limit) { single_match_cost * 5 }
35
+
36
+ context 'when the limit is disabled' do
37
+ config_override :in_memory_regexp_time_limit, nil
38
+
39
+ it 'evaluates the query without a bound' do
40
+ expect(person.addresses.where(street: { '$regex' => slow_pattern }).to_a).to eq([])
41
+ end
42
+ end
43
+
44
+ context 'when a limit is configured' do
45
+ config_override :in_memory_regexp_time_limit, nil
46
+
47
+ before { Mongoid::Config.in_memory_regexp_time_limit = calibrated_limit }
48
+
49
+ it 'leaves ordinary queries alone' do
50
+ person = Person.new(addresses: [ Address.new(street: 'Clarkson') ])
51
+ expect(person.addresses.where(street: { '$regex' => '\AClark' }).to_a.size).to eq(1)
52
+ end
53
+
54
+ it 'does not raise for a single document' do
55
+ # The counterpart to the example below, and what makes it meaningful: one
56
+ # document stays under the limit, so a scan that raises can only have got
57
+ # there by accumulating cost across documents.
58
+ expect do
59
+ one_address.addresses.where(street: { '$regex' => slow_pattern }).to_a
60
+ end.not_to raise_error
61
+ end
62
+
63
+ it 'raises for a scan over many documents under that same limit' do
64
+ expect do
65
+ person.addresses.where(street: { '$regex' => slow_pattern }).to_a
66
+ end.to raise_error(Mongoid::Errors::InMemoryRegexpTimeout)
67
+ end
68
+
69
+ it 'raises when $in multiplies the cost within a single document' do
70
+ conditions = Array.new(20) { BSON::Regexp::Raw.new(slow_pattern) }
71
+
72
+ expect do
73
+ one_address.addresses.where(street: { '$in' => conditions }).to_a
74
+ end.to raise_error(Mongoid::Errors::InMemoryRegexpTimeout)
75
+ end
76
+
77
+ it 'raises through the public _matches? API' do
78
+ # 20 conditions rather than one, because a single match is deliberately
79
+ # kept well under the limit by the calibration above.
80
+ conditions = Array.new(20) { BSON::Regexp::Raw.new(slow_pattern) }
81
+
82
+ expect do
83
+ person.addresses.first._matches?('street' => { '$in' => conditions })
84
+ end.to raise_error(Mongoid::Errors::InMemoryRegexpTimeout)
85
+ end
86
+ end
87
+
88
+ context 'when the pattern is pathological' do
89
+ config_override :in_memory_regexp_time_limit, 0.2
90
+
91
+ # The ticket's Case 1, verbatim. It backtracks exponentially and is the
92
+ # reason the guard exists, so every entry point that evaluates a selector
93
+ # in memory has to bound it. The subject is kept short enough that the
94
+ # match still finishes on its own in a few seconds, so an entry point that
95
+ # fails to bound it shows up as a failing example rather than a hung run.
96
+ let(:evil_pattern) { '^(a+)+\1?$' }
97
+ let(:evil_subject) { "#{'a' * 28}X" }
98
+
99
+ it 'bounds a scan over an embedded association' do
100
+ person = Person.new(addresses: [ Address.new(street: evil_subject) ])
101
+
102
+ expect do
103
+ person.addresses.where(street: { '$regex' => evil_pattern }).to_a
104
+ end.to raise_error(Mongoid::Errors::InMemoryRegexpTimeout)
105
+ end
106
+
107
+ it 'bounds the public _matches? API' do
108
+ expect do
109
+ Address.new(street: evil_subject)._matches?('street' => { '$regex' => evil_pattern })
110
+ end.to raise_error(Mongoid::Errors::InMemoryRegexpTimeout)
111
+ end
112
+
113
+ it 'bounds removal from a referenced association' do
114
+ owner = Person.create!
115
+ owner.posts.create!(title: evil_subject)
116
+
117
+ expect do
118
+ owner.posts.delete_all(title: { '$regex' => evil_pattern })
119
+ end.to raise_error(Mongoid::Errors::InMemoryRegexpTimeout)
120
+ end
121
+
122
+ it 'deletes nothing when removal is bounded' do
123
+ # The scan runs before the delete, so the error means what a caller would
124
+ # take it to mean: the documents are still there.
125
+ owner = Person.create!
126
+ owner.posts.create!(title: evil_subject)
127
+
128
+ expect do
129
+ owner.posts.delete_all(title: { '$regex' => evil_pattern })
130
+ end.to raise_error(Mongoid::Errors::InMemoryRegexpTimeout)
131
+
132
+ expect(Post.count).to eq(1)
133
+ expect(owner.reload.posts.size).to eq(1)
134
+ end
135
+ end
136
+
137
+ context 'when the association being removed from has not been loaded' do
138
+ config_override :in_memory_regexp_time_limit, 0.2
139
+
140
+ let!(:owner) do
141
+ person = Person.create!
142
+ person.posts.create!(title: 'Testing')
143
+ Person.find(person._id)
144
+ end
145
+
146
+ # The query that loads the association, which removal has to run before it
147
+ # has anything to match against.
148
+ let(:load_query) { owner.posts._target._unloaded }
149
+
150
+ # A stall standing in for a slow network. It is longer than the limit, and
151
+ # none of it is time spent on regular expressions.
152
+ before do
153
+ allow(load_query).to receive(:each).and_wrap_original do |original, *args, &block|
154
+ sleep(0.3)
155
+ original.call(*args, &block)
156
+ end
157
+ end
158
+
159
+ it 'does not load it, so no query can be counted against the limit' do
160
+ # On the Timeout path a deadline covering the fetch failed a slow query
161
+ # with an error about regular expressions, and the asynchronous exception
162
+ # could land inside the driver's socket read, leaving the connection with
163
+ # unconsumed bytes. Nothing is fetched now: the scan sees only what the
164
+ # association already holds.
165
+ stub_const('Mongoid::Matcher::RegexpBudget::PER_REGEXP_TIMEOUT', false)
166
+
167
+ expect do
168
+ owner.posts.delete_all(title: { '$regex' => '\Azzz' })
169
+ end.not_to raise_error
170
+
171
+ expect(load_query).not_to have_received(:each)
172
+ end
173
+
174
+ it 'runs no pattern against documents it never loaded' do
175
+ # The counterpart to the referenced-association examples below, where the
176
+ # documents are in memory and the pattern is run against every one of
177
+ # them. Here there is nothing to run it against, and the server applies
178
+ # the same selector for the delete, so nothing is missed by not looking.
179
+ expect(Mongoid::Matcher::RegexpBudget).not_to receive(:match?)
180
+
181
+ owner.posts.delete_all(title: { '$regex' => '\Azzz' })
182
+ end
183
+
184
+ it 'still removes the documents that match' do
185
+ expect(owner.posts.delete_all(title: { '$regex' => '\ATest' })).to eq(1)
186
+ expect(Post.count).to eq(0)
187
+ expect(owner.posts.size).to eq(0)
188
+ end
189
+ end
190
+
191
+ context 'when removing documents from a referenced association' do
192
+ config_override :in_memory_regexp_time_limit, nil
193
+
194
+ let!(:owner) { Person.create! }
195
+
196
+ before do
197
+ 30.times { owner.posts.create!(title: slow_street) }
198
+ Mongoid::Config.in_memory_regexp_time_limit = calibrated_limit
199
+ end
200
+
201
+ it 'raises rather than scanning every loaded document' do
202
+ expect do
203
+ owner.posts.delete_all(title: { '$regex' => slow_pattern })
204
+ end.to raise_error(Mongoid::Errors::InMemoryRegexpTimeout)
205
+ end
206
+
207
+ it 'leaves the documents in place' do
208
+ expect do
209
+ owner.posts.delete_all(title: { '$regex' => slow_pattern })
210
+ end.to raise_error(Mongoid::Errors::InMemoryRegexpTimeout)
211
+
212
+ expect(Post.count).to eq(30)
213
+ end
214
+ end
215
+ end
@@ -0,0 +1,89 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'spec_helper'
4
+
5
+ describe 'query operator injection guard' do
6
+ let(:js) { 'this.name == "admin"' }
7
+
8
+ let(:nested_function) do
9
+ { '$expr' => { '$function' => { 'body' => 'function() { return true; }', 'args' => [], 'lang' => 'js' } } }
10
+ end
11
+
12
+ let(:band) { Band.create!(name: 'Depeche Mode') }
13
+
14
+ context 'with default configuration' do
15
+ it 'rejects unsafe operators without any opt-out' do
16
+ expect(Mongoid.allow_unsafe_query_operators).to be false
17
+ end
18
+
19
+ context 'when querying with where' do
20
+ it 'rejects a top-level $where' do
21
+ expect { Band.where('$where' => js).first }.to raise_error(Mongoid::Errors::InvalidQuery)
22
+ end
23
+
24
+ it 'rejects a $function nested in $expr' do
25
+ expect { Band.where(nested_function).first }.to raise_error(Mongoid::Errors::InvalidQuery)
26
+ end
27
+
28
+ it 'permits an ordinary query' do
29
+ expect(Band.where(name: band.name).first).to eq(band)
30
+ end
31
+ end
32
+
33
+ context 'when querying with find_by' do
34
+ it 'rejects a top-level $where' do
35
+ expect { Band.find_by('$where' => js) }.to raise_error(Mongoid::Errors::InvalidQuery)
36
+ end
37
+
38
+ it 'rejects a $function nested in $expr' do
39
+ expect { Band.find_by(nested_function) }.to raise_error(Mongoid::Errors::InvalidQuery)
40
+ end
41
+ end
42
+
43
+ context 'when querying with find_or_create_by' do
44
+ it 'rejects a top-level $where' do
45
+ expect { Band.find_or_create_by('$where' => js) }.to raise_error(Mongoid::Errors::InvalidQuery)
46
+ end
47
+ end
48
+
49
+ context 'when querying with find_or_initialize_by' do
50
+ it 'rejects a top-level $where' do
51
+ expect { Band.find_or_initialize_by('$where' => js) }.to raise_error(Mongoid::Errors::InvalidQuery)
52
+ end
53
+ end
54
+
55
+ context 'when querying an association with find_or_create_by' do
56
+ it 'rejects a top-level $where' do
57
+ expect do
58
+ band.records.find_or_create_by('$where' => js)
59
+ end.to raise_error(Mongoid::Errors::InvalidQuery)
60
+ end
61
+ end
62
+
63
+ context 'when querying with a logical operator' do
64
+ it 'rejects a $where smuggled through or' do
65
+ expect { Band.or('$where' => js).first }.to raise_error(Mongoid::Errors::InvalidQuery)
66
+ end
67
+
68
+ it 'rejects a $where smuggled through any_of' do
69
+ expect { Band.any_of('$where' => js).first }.to raise_error(Mongoid::Errors::InvalidQuery)
70
+ end
71
+ end
72
+ end
73
+
74
+ context 'when allow_unsafe_query_operators is true' do
75
+ config_override :allow_unsafe_query_operators, true
76
+
77
+ it 'permits a top-level $where' do
78
+ expect(Band.where('$where' => "this.name == '#{band.name}'").first).to eq(band)
79
+ end
80
+
81
+ it 'permits a $function nested in $expr' do
82
+ expect { Band.where(nested_function).first }.not_to raise_error
83
+ end
84
+
85
+ it 'permits a $where smuggled through or' do
86
+ expect { Band.or('$where' => js).first }.not_to raise_error
87
+ end
88
+ end
89
+ end
@@ -2268,6 +2268,13 @@ describe Mongoid::Association::Referenced::HasAndBelongsToMany::Proxy do
2268
2268
  end
2269
2269
  end
2270
2270
 
2271
+ # Whether the conditions carry a pattern decides which branch of remove_all
2272
+ # runs, so anything that has to behave the same on both is exercised twice.
2273
+ conditions_variants = [
2274
+ [ 'no regular expression', nil ],
2275
+ [ 'a regular expression', { name: /Test/ } ]
2276
+ ].freeze
2277
+
2271
2278
  %i[ delete_all destroy_all ].each do |method|
2272
2279
  describe "\##{method}" do
2273
2280
  context 'when the relation is not polymorphic' do
@@ -2339,6 +2346,47 @@ describe Mongoid::Association::Referenced::HasAndBelongsToMany::Proxy do
2339
2346
  expect(person.preferences).to eq([])
2340
2347
  end
2341
2348
  end
2349
+
2350
+ context 'when the base holds the foreign keys' do
2351
+ # unbind_one pulls ids out of the base's foreign key array and marks
2352
+ # the base dirty, so which documents get unbound is visible here.
2353
+ # Only what the association already held is unbound, and that has to
2354
+ # hold whether or not the conditions carry a regular expression:
2355
+ # scanning under a regexp budget loads the association first, and
2356
+ # that load must not turn into an unbind of its own. See the note in
2357
+ # HasMany::Proxy#remove_all_bounded.
2358
+ let!(:person) do
2359
+ Person.create!.tap do |base|
2360
+ base.preferences.create!(name: 'Testing')
2361
+ base.preferences.create!(name: 'Test')
2362
+ end
2363
+ end
2364
+
2365
+ let(:ids) { person.preference_ids.dup }
2366
+
2367
+ conditions_variants.each do |description, conditions|
2368
+ context "when the conditions carry #{description}" do
2369
+ context 'when the association is already in memory' do
2370
+ it 'unbinds the deleted documents' do
2371
+ person.preferences.send(method, conditions)
2372
+ expect(person.preference_ids).to eq([])
2373
+ expect(person).to be_changed
2374
+ end
2375
+ end
2376
+
2377
+ context 'when the association has not been loaded' do
2378
+ let(:cold) { Person.find(person._id) }
2379
+
2380
+ it 'leaves the foreign keys alone' do
2381
+ expect(ids.length).to eq(2)
2382
+ cold.preferences.send(method, conditions)
2383
+ expect(cold.preference_ids).to eq(ids)
2384
+ expect(cold).not_to be_changed
2385
+ end
2386
+ end
2387
+ end
2388
+ end
2389
+ end
2342
2390
  end
2343
2391
  end
2344
2392
  end
@@ -2281,6 +2281,151 @@ describe Mongoid::Association::Referenced::HasMany::Proxy do
2281
2281
  expect(person.posts).to eq([])
2282
2282
  end
2283
2283
  end
2284
+
2285
+ context 'when a document is appended with an id that is already loaded' do
2286
+ # Iterating the association moves an appended document out of _added
2287
+ # without adding it to _loaded, so the scan for matches and the
2288
+ # removal that follows see different instances for the same id.
2289
+ let(:person) { Person.create! }
2290
+ let!(:post) { person.posts.create!(title: 'Testing') }
2291
+ let(:reloaded) { Person.find(person._id) }
2292
+
2293
+ before do
2294
+ reloaded.posts.to_a
2295
+ reloaded.posts._target.push(
2296
+ Post.new(_id: post._id, title: 'Testing', person_id: reloaded._id)
2297
+ )
2298
+ end
2299
+
2300
+ shared_examples 'removes the document once' do
2301
+ it 'sets the association locally' do
2302
+ reloaded.posts.send(method, conditions)
2303
+ expect(reloaded.posts).to eq([])
2304
+ end
2305
+
2306
+ it 'deletes the documents from the database' do
2307
+ reloaded.posts.send(method, conditions)
2308
+ expect(Post.count).to eq(0)
2309
+ end
2310
+ end
2311
+
2312
+ context 'when the conditions carry no regular expression' do
2313
+ let(:conditions) { { title: 'Testing' } }
2314
+
2315
+ it_behaves_like 'removes the document once'
2316
+ end
2317
+
2318
+ context 'when the conditions carry a regular expression' do
2319
+ let(:conditions) { { title: /Testing/ } }
2320
+
2321
+ it_behaves_like 'removes the document once'
2322
+ end
2323
+ end
2324
+
2325
+ context 'when an appended document disagrees with the loaded one' do
2326
+ # Only the appended instance matches, so the removal has to drop that
2327
+ # id from both _loaded and _added. Removing by id and stopping at the
2328
+ # first hash that has it would take the loaded instance instead and
2329
+ # leave the unbound one behind.
2330
+ let(:person) { Person.create! }
2331
+ let!(:post) { person.posts.create!(title: 'Other') }
2332
+ let(:reloaded) { Person.find(person._id) }
2333
+
2334
+ before do
2335
+ reloaded.posts.to_a
2336
+ reloaded.posts._target.push(
2337
+ Post.new(_id: post._id, title: 'Testing', person_id: reloaded._id)
2338
+ )
2339
+ end
2340
+
2341
+ it 'deletes nothing from the database' do
2342
+ expect(reloaded.posts.send(method, { title: /Testing/ })).to eq(0)
2343
+ expect(Post.where(title: 'Other').count).to eq(1)
2344
+ end
2345
+
2346
+ it 'leaves no unbound document in the association' do
2347
+ reloaded.posts.send(method, { title: /Testing/ })
2348
+ expect(reloaded.posts._target.in_memory.map(&:person_id)).not_to include(nil)
2349
+ end
2350
+ end
2351
+
2352
+ context 'when a nested selector is evaluated while the association loads' do
2353
+ # Loading the association runs find callbacks, and application code in
2354
+ # one of those can evaluate a selector of its own. A scope opened
2355
+ # around the load would mark it as having nothing to bound, and that
2356
+ # suppresses the decision for the nested selector too, leaving any
2357
+ # pattern in it unguarded.
2358
+ config_override :in_memory_regexp_time_limit, 5.0
2359
+
2360
+ let(:person) { Person.create! }
2361
+ let(:reloaded) { Person.find(person._id) }
2362
+
2363
+ before do
2364
+ person.posts.create!(title: 'Testing')
2365
+ person.posts.create!(title: 'Keep')
2366
+ reloaded
2367
+ end
2368
+
2369
+ it 'leaves the nested scope free to establish its own budget' do
2370
+ seen = []
2371
+ allow(Mongoid::Factory).to receive(:from_db).and_wrap_original do |original, *args|
2372
+ Mongoid::Matcher::RegexpBudget.open('title' => /Testing/) do
2373
+ seen << Mongoid::Matcher::RegexpBudget.remaining
2374
+ end
2375
+ original.call(*args)
2376
+ end
2377
+
2378
+ reloaded.posts.send(method, { title: 'Testing' })
2379
+
2380
+ expect(seen).not_to be_empty
2381
+ expect(seen).not_to include(nil)
2382
+ end
2383
+ end
2384
+
2385
+ if method == :delete_all
2386
+ context 'when the association has not been loaded' do
2387
+ let(:person) { Person.create! }
2388
+ let(:reloaded) { Person.find(person._id) }
2389
+ let(:subscriber) { Mrss::EventSubscriber.new }
2390
+
2391
+ before do
2392
+ person.posts.create!(title: 'Testing')
2393
+ person.posts.create!(title: 'Test')
2394
+ reloaded
2395
+ end
2396
+
2397
+ def commands_for(conditions)
2398
+ Person.collection.client.subscribe(Mongo::Monitoring::COMMAND, subscriber)
2399
+ reloaded.posts.delete_all(conditions)
2400
+ subscriber.started_events.map(&:command_name)
2401
+ ensure
2402
+ Person.collection.client.unsubscribe(Mongo::Monitoring::COMMAND, subscriber)
2403
+ end
2404
+
2405
+ context 'when the conditions carry no regular expression' do
2406
+ # Nothing to bound, so the scan for matches stays where it was,
2407
+ # after the delete, where the association it loads comes back
2408
+ # empty. Moving it ahead of the delete would transfer the whole
2409
+ # association for an operation that need send nothing over the
2410
+ # wire.
2411
+ it 'deletes before loading the association' do
2412
+ expect(commands_for(nil)).to eq(%w[ delete find ])
2413
+ end
2414
+ end
2415
+
2416
+ context 'when the conditions carry a regular expression' do
2417
+ # The scan has to run under a budget, and before anything is
2418
+ # deleted, so that a budget which runs out leaves the database
2419
+ # untouched. What it scans is what is already in memory: loading
2420
+ # would trade the matching cost the budget exists to bound for an
2421
+ # unbounded amount of memory, since /.*/ is both cheap to supply
2422
+ # and matches every document in the association.
2423
+ it 'deletes without loading the association' do
2424
+ expect(commands_for({ title: /Test/ })).to eq(%w[ delete ])
2425
+ end
2426
+ end
2427
+ end
2428
+ end
2284
2429
  end
2285
2430
 
2286
2431
  context "when the association is polymorphic" do