mongoid 9.1.2 → 9.1.3

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 (53) hide show
  1. checksums.yaml +4 -4
  2. data/lib/config/locales/en.yml +13 -0
  3. data/lib/mongoid/association/accessors.rb +4 -1
  4. data/lib/mongoid/association/referenced/belongs_to/buildable.rb +19 -15
  5. data/lib/mongoid/association/referenced/belongs_to.rb +11 -3
  6. data/lib/mongoid/association/referenced/has_and_belongs_to_many/buildable.rb +21 -7
  7. data/lib/mongoid/association/referenced/has_and_belongs_to_many.rb +12 -0
  8. data/lib/mongoid/association/referenced/has_many/buildable.rb +17 -7
  9. data/lib/mongoid/association/referenced/has_many/proxy.rb +4 -2
  10. data/lib/mongoid/association/referenced/has_one/buildable.rb +20 -6
  11. data/lib/mongoid/association.rb +15 -0
  12. data/lib/mongoid/attributes/readonly.rb +19 -1
  13. data/lib/mongoid/changeable.rb +19 -1
  14. data/lib/mongoid/config/encryption.rb +5 -3
  15. data/lib/mongoid/contextual/none.rb +51 -0
  16. data/lib/mongoid/criteria/scopable.rb +5 -0
  17. data/lib/mongoid/criteria.rb +45 -1
  18. data/lib/mongoid/document.rb +10 -0
  19. data/lib/mongoid/encryptable.rb +1 -1
  20. data/lib/mongoid/errors/invalid_encrypted_association.rb +28 -0
  21. data/lib/mongoid/errors.rb +1 -0
  22. data/lib/mongoid/factory.rb +1 -1
  23. data/lib/mongoid/fields/encrypted.rb +14 -3
  24. data/lib/mongoid/fields/foreign_key.rb +9 -0
  25. data/lib/mongoid/fields/standard.rb +10 -0
  26. data/lib/mongoid/fields/validators/macro.rb +29 -0
  27. data/lib/mongoid/fields.rb +42 -2
  28. data/lib/mongoid/reloadable.rb +1 -0
  29. data/lib/mongoid/version.rb +1 -1
  30. data/spec/integration/encryption_spec.rb +269 -0
  31. data/spec/mongoid/association/referenced/belongs_to/buildable_spec.rb +35 -6
  32. data/spec/mongoid/association/referenced/encrypted_foreign_key_spec.rb +142 -0
  33. data/spec/mongoid/association/referenced/has_and_belongs_to_many/buildable_spec.rb +25 -5
  34. data/spec/mongoid/association/referenced/has_and_belongs_to_many/proxy_spec.rb +48 -0
  35. data/spec/mongoid/association/referenced/has_many/buildable_spec.rb +24 -6
  36. data/spec/mongoid/association/referenced/has_many/proxy_spec.rb +81 -0
  37. data/spec/mongoid/association/referenced/has_one/buildable_spec.rb +18 -3
  38. data/spec/mongoid/attributes/readonly_dotted_spec.rb +334 -0
  39. data/spec/mongoid/attributes/readonly_spec.rb +389 -0
  40. data/spec/mongoid/changeable_spec.rb +18 -0
  41. data/spec/mongoid/config/encryption_spec.rb +227 -0
  42. data/spec/mongoid/contextual/none_spec.rb +18 -0
  43. data/spec/mongoid/criteria_spec.rb +17 -0
  44. data/spec/mongoid/factory_spec.rb +8 -0
  45. data/spec/mongoid/fields_spec.rb +29 -0
  46. data/spec/mongoid/findable_spec.rb +14 -0
  47. data/spec/mongoid/scopable_spec.rb +102 -0
  48. data/spec/support/crypt/models.rb +42 -0
  49. data/spec/support/models/delete_all_account.rb +10 -0
  50. data/spec/support/models/delete_all_item.rb +9 -0
  51. data/spec/support/models/delete_all_scoped_item.rb +11 -0
  52. data/spec/support/models/delete_all_tag.rb +7 -0
  53. metadata +2045 -2011
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 0f94dec89da2023d081f5c08eed8a5ee4f61fd511b7f8eaea3dd8afde665829d
4
- data.tar.gz: cb6e13ef1c7e708620d747a31f4cfff15088bd451c41259c2ade7b9bf4b26bdb
3
+ metadata.gz: 049c589b71cab5be4a47ad8e5c2023f8f5aa00c67ee033d971a87061b587fee7
4
+ data.tar.gz: 3482ca9833b805cdccd5a193492892afa99a6a73be26eefac7bb0301b676322b
5
5
  SHA512:
6
- metadata.gz: e4695df34902c08d6c0bb8f95f9e128f0a154b5a859b3e97181646cb6cd9f24a2d138be0721c2bba761e1db5327d7b207ce104c8d6edad1b9336f6dc62aa2e39
7
- data.tar.gz: 99cb2aa72fcdf82ecd8f43d2a5bae06113a1af687d1e01d7a54f12e6b996c517c817b7b9b72c0418ddbd8e09af6e692159852cf8acafa3166166db5174acf34d
6
+ metadata.gz: af7a00edbd50604d1f1defda36e046410965cdfe373c3f1e1fb6943d4eb084edf459eed8778ae8ad0fb12fd247d0ec7de706b7370733643284d4314ad10fd28a
7
+ data.tar.gz: 72aed484d484da020d180fa0fddf5b31d3d0a9a137a32f9bca32b9cd16c8cc1efa38abe477fbc5b030ee3f6515dbb1736ae8879347a11cd4cb818ec403dfcafe
@@ -239,6 +239,19 @@ en:
239
239
  Mongoid does not support."
240
240
  resolution: "Valid field operators are: %{valid_operators}.
241
241
  Ensure you are using one of these operators."
242
+ invalid_encrypted_association:
243
+ message: "The %{association} association of %{klass} uses the encrypted
244
+ field %{field} as its foreign key."
245
+ summary: "Client-side field level encryption can encrypt an array
246
+ only as a whole, using the random algorithm; the deterministic
247
+ algorithm does not support arrays at all. A
248
+ has_and_belongs_to_many association stores its foreign key in an
249
+ array and queries and atomically updates individual elements of
250
+ it, which encryption does not support. Mongoid raises this error
251
+ when the association or the field is defined, whichever comes
252
+ first, rather than defining a key the association cannot manage."
253
+ resolution: "Remove the encryption from %{field}, or store a single
254
+ encrypted value with a belongs_to association instead."
242
255
  invalid_encryption_schema:
243
256
  message: "The encryption schema for %{namespace} is invalid."
244
257
  summary: "Two models writing to %{namespace} describe %{path}
@@ -92,6 +92,9 @@ module Mongoid
92
92
  # it returns, including those of a sibling subclass that has no such
93
93
  # association.
94
94
  #
95
+ # The documents are wrapped in PreloadedDocuments so that the builders
96
+ # know where they came from.
97
+ #
95
98
  # @param [ Hash ] preloaded The preloaded documents by the field they
96
99
  # travelled in.
97
100
  #
@@ -100,7 +103,7 @@ module Mongoid
100
103
  preloaded.each do |field, documents|
101
104
  name = field.delete_prefix(PRELOADED_PREFIX)
102
105
  association = relations[name]
103
- __build__(name, documents, association) if association
106
+ __build__(name, PreloadedDocuments.new(documents), association) if association
104
107
  end
105
108
  end
106
109
 
@@ -19,29 +19,33 @@ module Mongoid
19
19
  #
20
20
  # @return [ Document ] A single document.
21
21
  def build(_base, object, type = nil, selected_fields = nil)
22
- return object unless query?(object)
23
-
24
- # Handle array from $lookup aggregation (returns array even for belongs_to)
25
- if object.is_a?(Array)
26
- first = object.first
27
- case first
28
- when nil, Mongoid::Document then return first
29
- when Hash then return Factory.execute_from_db(klass, first, nil, selected_fields,
30
- execute_callbacks: false)
31
- else raise ArgumentError, 'Cannot build belongs_to association from array'
32
- end
22
+ if object.is_a?(PreloadedDocuments)
23
+ return build_preloaded(object.documents, selected_fields)
33
24
  end
34
25
 
35
- # Handle single hash from $lookup with $unwind
36
- if object.is_a?(Hash)
37
- return Factory.execute_from_db(klass, object, nil, selected_fields, execute_callbacks: false)
38
- end
26
+ return object unless query?(object)
39
27
 
40
28
  execute_query(object, type)
41
29
  end
42
30
 
43
31
  private
44
32
 
33
+ # Builds the document from the documents a $lookup preloaded for this
34
+ # association. The lookup returns an array, even for belongs_to, and
35
+ # may be unwound to a single document.
36
+ #
37
+ # @param [ Array<Hash> | Hash | nil ] documents The preloaded documents.
38
+ # @param [ Hash | nil ] selected_fields Fields which were retrieved via #only.
39
+ #
40
+ # @return [ Document | nil ] The built document.
41
+ def build_preloaded(documents, selected_fields)
42
+ document = documents.is_a?(Array) ? documents.first : documents
43
+ return document if document.nil? || document.is_a?(Mongoid::Document)
44
+
45
+ Factory.execute_from_db(klass, document, nil, selected_fields,
46
+ execute_callbacks: false)
47
+ end
48
+
45
49
  def execute_query(object, type)
46
50
  query_criteria(object, type).take
47
51
  end
@@ -233,14 +233,22 @@ module Mongoid
233
233
  end
234
234
 
235
235
  def create_foreign_key_field!
236
- @owner_class.field(
237
- foreign_key,
236
+ options = {
238
237
  type: FOREIGN_KEY_FIELD_TYPE,
239
238
  identity: true,
240
239
  overwrite: true,
241
240
  association: self,
242
241
  default: nil
243
- )
242
+ }
243
+ # The association must not replace an encrypted field with a plain
244
+ # foreign key: the key would then be stored in the clear. Keep the
245
+ # declared type as well, so the encryption schema describes it
246
+ # correctly.
247
+ if (existing = @owner_class.fields[foreign_key])&.encrypted?
248
+ options[:type] = existing.type
249
+ options[:encrypt] = existing.options[:encrypt]
250
+ end
251
+ @owner_class.field(foreign_key, options)
244
252
  end
245
253
  end
246
254
  end
@@ -19,6 +19,10 @@ module Mongoid
19
19
  #
20
20
  # @return [ Array<Document> ] The documents.
21
21
  def build(_base, object, _type = nil, selected_fields = nil)
22
+ if object.is_a?(PreloadedDocuments)
23
+ return build_preloaded(object.documents, selected_fields)
24
+ end
25
+
22
26
  if query?(object)
23
27
  if object.is_a?(Array) && object.empty?
24
28
  # An empty stored key array is not $lookup output. Build a none
@@ -26,13 +30,6 @@ module Mongoid
26
30
  return query_criteria(nil)
27
31
  end
28
32
 
29
- # Handle array of hashes from $lookup aggregation
30
- if object.is_a?(Array) && object.all? { |o| o.is_a?(Hash) }
31
- return object.map do |attrs|
32
- Factory.execute_from_db(klass, attrs, nil, selected_fields, execute_callbacks: false)
33
- end
34
- end
35
-
36
33
  query_criteria(object)
37
34
  else
38
35
  object.try(:dup)
@@ -41,6 +38,23 @@ module Mongoid
41
38
 
42
39
  private
43
40
 
41
+ # Builds the documents a $lookup preloaded for this association. An
42
+ # empty result builds a none criteria, like an empty key does, so that
43
+ # reset, empty?, and size do not query the database.
44
+ #
45
+ # @param [ Array<Hash> ] documents The preloaded documents.
46
+ # @param [ Hash | nil ] selected_fields Fields which were retrieved via #only.
47
+ #
48
+ # @return [ Array<Document> | Mongoid::Criteria ] The documents.
49
+ def build_preloaded(documents, selected_fields)
50
+ return query_criteria(nil) if documents.empty?
51
+
52
+ documents.map do |attrs|
53
+ Factory.execute_from_db(klass, attrs, nil, selected_fields,
54
+ execute_callbacks: false)
55
+ end
56
+ end
57
+
44
58
  def query?(object)
45
59
  object.nil? || Array(object).all? { |d| !d.is_a?(Mongoid::Document) }
46
60
  end
@@ -238,6 +238,18 @@ module Mongoid
238
238
  end
239
239
 
240
240
  def create_foreign_key_field!
241
+ # An encrypted array field cannot be used as the foreign key:
242
+ # encryption protects the array only as a whole, while this
243
+ # association queries and atomically updates its elements. Reject
244
+ # the association rather than replace the field and store the key in
245
+ # plaintext. The field may already be declared on a parent, whose
246
+ # declaration is propagated to the descendants.
247
+ ([ @owner_class ] + @owner_class.descendants).each do |candidate|
248
+ next unless candidate.fields[foreign_key]&.encrypted?
249
+
250
+ raise Errors::InvalidEncryptedAssociation.new(candidate, name, foreign_key)
251
+ end
252
+
241
253
  inverse_class.aliased_associations[foreign_key] = name.to_s
242
254
  @owner_class.field(
243
255
  foreign_key,
@@ -19,15 +19,12 @@ module Mongoid
19
19
  #
20
20
  # @return [ Document ] A single document.
21
21
  def build(base, object, _type = nil, selected_fields = nil)
22
- return object || [] unless query?(object)
23
-
24
- # Handle array of hashes from $lookup aggregation
25
- if object.is_a?(Array) && object.all? { |o| o.is_a?(Hash) }
26
- return object.map do |attrs|
27
- Factory.execute_from_db(klass, attrs, nil, selected_fields, execute_callbacks: false)
28
- end
22
+ if object.is_a?(PreloadedDocuments)
23
+ return build_preloaded(object.documents, selected_fields)
29
24
  end
30
25
 
26
+ return object || [] unless query?(object)
27
+
31
28
  return [] if object.is_a?(Array)
32
29
 
33
30
  query_criteria(object, base)
@@ -35,6 +32,19 @@ module Mongoid
35
32
 
36
33
  private
37
34
 
35
+ # Builds the documents a $lookup preloaded for this association.
36
+ #
37
+ # @param [ Array<Hash> ] documents The preloaded documents.
38
+ # @param [ Hash | nil ] selected_fields Fields which were retrieved via #only.
39
+ #
40
+ # @return [ Array<Document> ] The built documents.
41
+ def build_preloaded(documents, selected_fields)
42
+ documents.map do |attrs|
43
+ Factory.execute_from_db(klass, attrs, nil, selected_fields,
44
+ execute_callbacks: false)
45
+ end
46
+ end
47
+
38
48
  def query?(object)
39
49
  object && Array(object).all? { |d| !d.is_a?(Mongoid::Document) }
40
50
  end
@@ -537,8 +537,10 @@ module Mongoid
537
537
  #
538
538
  # @return [ Integer ] The number of documents deleted.
539
539
  def remove_all(conditions = nil, method = :delete_all)
540
- selector = conditions || {}
541
- selector.merge!(criteria.selector)
540
+ # Conjoin the conditions with the association selector so that a
541
+ # key present in both is intersected rather than overwritten. This
542
+ # also leaves the caller's Hash alone.
543
+ selector = criteria.where(conditions || {}).selector
542
544
 
543
545
  # Scanning before the delete means scanning only what is already in
544
546
  # memory, so it is only done where there is a pattern whose cost has
@@ -21,13 +21,11 @@ module Mongoid
21
21
  #
22
22
  # @return [ Document ] A single document.
23
23
  def build(base, object, _type = nil, selected_fields = nil)
24
- if query?(object)
25
- # Handle array of hashes from $lookup aggregation
26
- if object.is_a?(Array) && object.all? { |o| o.is_a?(Hash) }
27
- doc = object.first
28
- return doc ? Factory.execute_from_db(klass, doc, nil, selected_fields, execute_callbacks: false) : nil
29
- end
24
+ if object.is_a?(PreloadedDocuments)
25
+ return build_preloaded(object.documents, selected_fields)
26
+ end
30
27
 
28
+ if query?(object)
31
29
  execute_query(object, base) unless base.new_record?
32
30
  else
33
31
  clear_associated(object)
@@ -37,6 +35,22 @@ module Mongoid
37
35
 
38
36
  private
39
37
 
38
+ # Builds the document from the documents a $lookup preloaded for this
39
+ # association. A has_one lookup returns an array with at most one
40
+ # document.
41
+ #
42
+ # @param [ Array<Hash> ] documents The preloaded documents.
43
+ # @param [ Hash | nil ] selected_fields Fields which were retrieved via #only.
44
+ #
45
+ # @return [ Document | nil ] The built document.
46
+ def build_preloaded(documents, selected_fields)
47
+ document = documents.first
48
+ return unless document
49
+
50
+ Factory.execute_from_db(klass, document, nil, selected_fields,
51
+ execute_callbacks: false)
52
+ end
53
+
40
54
  def clear_associated(object)
41
55
  unless inverse
42
56
  raise Errors::InverseNotFound.new(
@@ -41,6 +41,21 @@ module Mongoid
41
41
  # @api private
42
42
  PRELOADED_PREFIX = '__mongoid_eager_loaded_'
43
43
 
44
+ # The documents a $lookup preloaded for an association. The wrapper tells
45
+ # the builders that these documents come from eager loading, so that a key
46
+ # that happens to be an array of hashes is not built into documents.
47
+ #
48
+ # @api private
49
+ class PreloadedDocuments
50
+ # @return [ Array<Hash> ] The documents the $lookup returned.
51
+ attr_reader :documents
52
+
53
+ # @param [ Array<Hash> ] documents The documents the $lookup returned.
54
+ def initialize(documents)
55
+ @documents = documents || []
56
+ end
57
+ end
58
+
44
59
  # Map the macros to their corresponding Association classes.
45
60
  #
46
61
  # @return [ Hash ] The mapping from macros to their Association class.
@@ -21,7 +21,25 @@ module Mongoid
21
21
  # @return [ true | false ] If the document is new, or if the field is not
22
22
  # readonly.
23
23
  def attribute_writable?(name)
24
- new_record? || (!self.class.readonly_attributes.include?(name) && _loaded?(name))
24
+ return true if new_record?
25
+
26
+ readonly = self.class.readonly_attributes
27
+ return _loaded?(name) if readonly.empty?
28
+
29
+ path = name.to_s
30
+ return false if readonly.include?(path)
31
+
32
+ readonly.each do |field|
33
+ # A readonly attribute that is a declared field with a dotted name
34
+ # is that literal field, not a path prefix.
35
+ next if field.include?('.') && self.class.fields.key?(field)
36
+
37
+ # A path that is a declared field with a dotted name addresses that
38
+ # literal field, not a descendant of the readonly attribute.
39
+ return false if path.start_with?("#{field}.") && !self.class.fields.key?(path)
40
+ end
41
+
42
+ _loaded?(name)
25
43
  end
26
44
 
27
45
  private
@@ -80,6 +80,7 @@ module Mongoid
80
80
  @children_may_have_changed = false
81
81
  reset_atomic_updates!
82
82
  changed_attributes.clear
83
+ @pre_create_changed_attributes = nil
83
84
  end
84
85
 
85
86
  # Things that need to execute after a document has been persisted.
@@ -266,6 +267,13 @@ module Mongoid
266
267
  def attribute_changed?(attr, from: ATTRIBUTE_UNCHANGED, to: ATTRIBUTE_UNCHANGED)
267
268
  attr = database_field_name(attr)
268
269
  return false unless changed_attributes.key?(attr)
270
+ # An in-place change to a readonly attribute of a persisted document
271
+ # is not part of the dirty tracking API and will not be persisted. A
272
+ # change tracked while the document was new initializes the document,
273
+ # and new documents may set readonly attributes, so it is still
274
+ # reported as a saved change.
275
+ return false if !new_record? && self.class.readonly_attributes.include?(attr) &&
276
+ !@pre_create_changed_attributes&.include?(attr)
269
277
  return false if changed_attributes[attr] == attributes[attr]
270
278
  return false if from != changed_attributes[attr]
271
279
  return false if to != attributes[attr]
@@ -328,6 +336,13 @@ module Mongoid
328
336
  def attribute_will_change!(attr)
329
337
  return if changed_attributes.key?(attr)
330
338
 
339
+ # The snapshot is taken for readonly attributes as well. Their changes
340
+ # are hidden from the dirty tracking API (see #attribute_changed?), but
341
+ # the snapshot is needed to reset an in-place change. Changes tracked
342
+ # while the document is new initialize it, and new documents may set
343
+ # readonly attributes, so they are remembered here and still reported
344
+ # when the document is created.
345
+ (@pre_create_changed_attributes ||= ::Set.new).add(attr) if new_record?
331
346
  changed_attributes[attr] = read_raw_attribute(attr).__deep_copy__
332
347
  end
333
348
 
@@ -341,7 +356,10 @@ module Mongoid
341
356
  # @return [ Object ] The old value.
342
357
  def reset_attribute!(attr)
343
358
  attr = database_field_name(attr)
344
- attributes[attr] = changed_attributes.delete(attr) if attribute_changed?(attr)
359
+ return unless changed_attributes.key?(attr)
360
+ return if changed_attributes[attr] == attributes[attr]
361
+
362
+ attributes[attr] = changed_attributes.delete(attr)
345
363
  end
346
364
 
347
365
  def reset_attribute_to_default!(attr)
@@ -152,7 +152,7 @@ module Mongoid
152
152
  # @return [ Hash ] The encryption properties.
153
153
  def properties_for_fields(model)
154
154
  model.fields.each_with_object({}) do |(name, field), props|
155
- next unless field.is_a?(Mongoid::Fields::Encrypted)
155
+ next unless field.encrypted?
156
156
 
157
157
  props[name] = {
158
158
  'encrypt' => {
@@ -181,7 +181,7 @@ module Mongoid
181
181
  #
182
182
  # @return [ Hash ] The encryption properties.
183
183
  def properties_for_relations(model, path, namespace = nil)
184
- model.relations.each_with_object({}) do |(name, relation), props|
184
+ model.relations.each_with_object({}) do |(_name, relation), props|
185
185
  # relation_class constantizes, and a polymorphic embedded_in has no
186
186
  # class to resolve, so the relation type has to be checked first.
187
187
  next unless relation.is_a?(Association::Embedded::EmbedsOne)
@@ -210,7 +210,9 @@ module Mongoid
210
210
  namespace
211
211
  )
212
212
  end
213
- props[name] = { 'bsonType' => 'object' }.merge(properties) unless properties.empty?
213
+ # The document is persisted under the store_as key, not under the
214
+ # name of the association, so that is the key the schema needs.
215
+ props[relation.store_as] = { 'bsonType' => 'object' }.merge(properties) unless properties.empty?
214
216
  end
215
217
  end
216
218
 
@@ -26,6 +26,31 @@ module Mongoid
26
26
  other.is_a?(None)
27
27
  end
28
28
 
29
+ # Delete all documents in the database that match the selector. There
30
+ # are no documents in the null context, so nothing is deleted.
31
+ #
32
+ # @example Delete all the documents.
33
+ # context.delete
34
+ #
35
+ # @return [ Integer ] Always zero.
36
+ def delete
37
+ 0
38
+ end
39
+ alias delete_all delete
40
+
41
+ # Destroy all documents in the database that match the selector. There
42
+ # are no documents in the null context, so nothing is destroyed and no
43
+ # callbacks are run.
44
+ #
45
+ # @example Destroy all the documents.
46
+ # context.destroy
47
+ #
48
+ # @return [ Integer ] Always zero.
49
+ def destroy
50
+ 0
51
+ end
52
+ alias destroy_all destroy
53
+
29
54
  # Get the distinct field values in null context.
30
55
  #
31
56
  # @example Get the distinct values in null context.
@@ -111,6 +136,32 @@ module Mongoid
111
136
  {}
112
137
  end
113
138
 
139
+ # Update the first matching document atomically. There are no documents
140
+ # in the null context, so nothing is updated.
141
+ #
142
+ # @example Update the matching document.
143
+ # context.update(name: "Smiths")
144
+ #
145
+ # @param [ Hash ] attributes The new attributes for the document.
146
+ #
147
+ # @return [ nil | false ] False if no attributes were provided.
148
+ def update(attributes = nil, _opts = {})
149
+ attributes ? nil : false
150
+ end
151
+
152
+ # Update all the matching documents atomically. There are no documents
153
+ # in the null context, so nothing is updated.
154
+ #
155
+ # @example Update all the matching documents.
156
+ # context.update_all(name: "Smiths")
157
+ #
158
+ # @param [ Hash ] attributes The new attributes for each document.
159
+ #
160
+ # @return [ nil | false ] False if no attributes were provided.
161
+ def update_all(attributes = nil, _opts = {})
162
+ attributes ? nil : false
163
+ end
164
+
114
165
  # Create the new null context.
115
166
  #
116
167
  # @example Create the new context.
@@ -13,9 +13,13 @@ module Mongoid
13
13
  #
14
14
  # @return [ Criteria ] The criteria.
15
15
  def apply_default_scope
16
+ explicit_none = none_state == true
16
17
  klass.without_default_scope do
17
18
  merge!(klass.default_scoping.call)
18
19
  end
20
+ # A none coming from the default scope is not an explicit none, so it
21
+ # may be removed by unscoping.
22
+ @none = :default if !explicit_none && @none
19
23
  self.scoping_options = true, false
20
24
  end
21
25
 
@@ -100,6 +104,7 @@ module Mongoid
100
104
  crit.scoping_options = false, true
101
105
  crit.selector.clear
102
106
  crit.options.clear
107
+ crit.send(:clear_default_scope_none)
103
108
  end
104
109
  crit
105
110
  end
@@ -371,6 +371,20 @@ module Mongoid
371
371
  self.inclusions = (inclusions + other.inclusions).uniq
372
372
  self._raw_results = _raw_results || other._raw_results
373
373
  @use_lookup ||= other.use_lookup?
374
+ if other.empty_and_chainable?
375
+ # An explicit none wins over a none that only came from a default
376
+ # scope. Association proxies forward is_a? to their target, so the
377
+ # runtime class is checked instead; anything that is not a criteria is
378
+ # treated as an explicit none.
379
+ explicit = if Criteria === other # rubocop:disable Style/CaseEquality
380
+ other.send(:none_state) == true
381
+ else
382
+ true
383
+ end
384
+ @none = true if @none == true || explicit
385
+ @none ||= :default
386
+ @context = nil
387
+ end
374
388
  self
375
389
  end
376
390
 
@@ -382,7 +396,9 @@ module Mongoid
382
396
  #
383
397
  # @return [ Criteria ] The none criteria.
384
398
  def none
385
- @none = true and self
399
+ @none = true
400
+ @context = nil
401
+ self
386
402
  end
387
403
 
388
404
  # Is the criteria an empty but chainable criteria?
@@ -563,6 +579,34 @@ module Mongoid
563
579
 
564
580
  private
565
581
 
582
+ # The kind of none on this criteria, if any. An explicit none is +true+,
583
+ # a none coming only from the default scope is +:default+, and a criteria
584
+ # that is not none returns +nil+.
585
+ #
586
+ # @api private
587
+ #
588
+ # @example Get the none state.
589
+ # criteria.send(:none_state)
590
+ #
591
+ # @return [ true | :default | nil ] The none state.
592
+ def none_state
593
+ @none
594
+ end
595
+
596
+ # Removes the none flag if it was set only by the default scope. An
597
+ # explicitly requested none is never removed.
598
+ #
599
+ # @api private
600
+ #
601
+ # @example Clear a default scope none.
602
+ # criteria.send(:clear_default_scope_none)
603
+ #
604
+ # @return [ Criteria ] The criteria.
605
+ def clear_default_scope_none
606
+ @none = nil if @none == :default
607
+ self
608
+ end
609
+
566
610
  # Are documents in the query missing, and are we configured to raise an
567
611
  # error?
568
612
  #
@@ -166,6 +166,12 @@ module Mongoid
166
166
  def internal_state=(state)
167
167
  self._id = state[:id]
168
168
  @changed_attributes = state[:changed_attributes]
169
+ # The document was constructed as new in #becomes, collecting
170
+ # pre-create change markers. Drop them when the copied state is that
171
+ # of a persisted document: its pending changes were all tracked after
172
+ # the document was persisted, and stale markers would let in-place
173
+ # changes to readonly attributes bypass the dirty filter.
174
+ @pre_create_changed_attributes = nil unless state[:new_record]
169
175
  @errors = ActiveModel::Errors.new(self).tap { |e| e.copy!(state[:errors]) }
170
176
  @new_record = state[:new_record]
171
177
  @destroyed = state[:destroyed]
@@ -337,6 +343,10 @@ module Mongoid
337
343
  relation = __send__(name)
338
344
  Array.wrap(relation).each do |r|
339
345
  r.instance_variable_set(:@new_record, new_record)
346
+ # The embedded documents were also constructed as new; drop
347
+ # their pre-create change markers when they are marked as
348
+ # persisted, as #internal_state= does for the parent document.
349
+ r.instance_variable_set(:@pre_create_changed_attributes, nil) unless new_record
340
350
  end
341
351
  end
342
352
  end
@@ -33,7 +33,7 @@ module Mongoid
33
33
  #
34
34
  # @return [ true | false ] Whether the model is encrypted.
35
35
  def encrypted?
36
- !encrypt_metadata.empty? || fields.any? { |_, field| field.is_a?(Mongoid::Fields::Encrypted) }
36
+ !encrypt_metadata.empty? || fields.any? { |_, field| field.encrypted? }
37
37
  end
38
38
 
39
39
  # Whether an encryption schema has to be generated for this model.
@@ -0,0 +1,28 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Mongoid
4
+ module Errors
5
+ # This error is raised when an encrypted field is used as the foreign key
6
+ # of a has_and_belongs_to_many association. Encryption protects an array
7
+ # only as a whole, while the association queries and atomically updates
8
+ # individual elements of it, so the association cannot manage the key.
9
+ class InvalidEncryptedAssociation < MongoidError
10
+ # Create the new error.
11
+ #
12
+ # @example Create the error.
13
+ # InvalidEncryptedAssociation.new(Person, :preferences, 'preference_ids')
14
+ #
15
+ # @param [ Class ] klass The model declaring the association.
16
+ # @param [ Symbol | String ] association The association name.
17
+ # @param [ String ] field The encrypted foreign key field.
18
+ def initialize(klass, association, field)
19
+ super(
20
+ compose_message(
21
+ 'invalid_encrypted_association',
22
+ { klass: klass.name, association: association, field: field }
23
+ )
24
+ )
25
+ end
26
+ end
27
+ end
28
+ end
@@ -20,6 +20,7 @@ require 'mongoid/errors/invalid_collection'
20
20
  require 'mongoid/errors/invalid_config_file'
21
21
  require 'mongoid/errors/invalid_config_option'
22
22
  require 'mongoid/errors/invalid_dependent_strategy'
23
+ require 'mongoid/errors/invalid_encrypted_association'
23
24
  require 'mongoid/errors/invalid_encryption_schema'
24
25
  require 'mongoid/errors/invalid_field'
25
26
  require 'mongoid/errors/invalid_field_option'
@@ -109,7 +109,7 @@ module Mongoid
109
109
  constantized = klass.get_discriminator_mapping(type) || constantize(type)
110
110
 
111
111
  # Check if the class is a Document class
112
- raise Errors::UnknownModel.new(camelized, type) unless constantized.respond_to?(:instantiate)
112
+ raise Errors::UnknownModel.new(type.camelize, type) unless constantized.respond_to?(:instantiate)
113
113
 
114
114
  constantized
115
115
  end