Skip to content
Navigation Menu
{{ message }}
-
Notifications
You must be signed in to change notification settings - Fork 358
Expand file tree
/
Copy pathcollection.py
More file actions
2478 lines (2170 loc) · 91.7 KB
/
Copy pathcollection.py
File metadata and controls
2478 lines (2170 loc) · 91.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import collections
import copy
import functools
import itertools
import json
import math
import time
import warnings
from collections import OrderedDict
from collections.abc import Iterable
from collections.abc import Mapping
from collections.abc import MutableMapping
from packaging import version
try:
from bson import BSON
from bson import json_util
from bson import SON
from bson.codec_options import CodecOptions
from bson.errors import InvalidDocument
except ImportError:
json_utils = SON = BSON = None
CodecOptions = None
try:
import execjs
except ImportError:
execjs = None
try:
from pymongo import ReadPreference
from pymongo import ReturnDocument
from pymongo.operations import IndexModel
_READ_PREFERENCE_PRIMARY = ReadPreference.PRIMARY
except ImportError:
class IndexModel:
pass
class ReturnDocument:
BEFORE = False
AFTER = True
from mongomock.read_preferences import PRIMARY as _READ_PREFERENCE_PRIMARY
from sentinels import NOTHING
import mongomock # Used for utcnow - please see https://github.com/mongomock/mongomock#utcnow
from mongomock import aggregate
from mongomock import BulkWriteError
from mongomock import codec_options as mongomock_codec_options
from mongomock import ConfigurationError
from mongomock import DuplicateKeyError
from mongomock import filtering
from mongomock import helpers
from mongomock import InvalidOperation
from mongomock import ObjectId
from mongomock import OperationFailure
from mongomock import WriteError
from mongomock.filtering import filter_applies
from mongomock.not_implemented import raise_for_feature as raise_not_implemented
from mongomock.results import BulkWriteResult
from mongomock.results import DeleteResult
from mongomock.results import InsertManyResult
from mongomock.results import InsertOneResult
from mongomock.results import UpdateResult
from mongomock.write_concern import WriteConcern
try:
from pymongo.read_concern import ReadConcern
except ImportError:
from mongomock.read_concern import ReadConcern
_KwargOption = collections.namedtuple('KwargOption', ['typename', 'default', 'attrs'])
_WITH_OPTIONS_KWARGS = {
'read_preference': _KwargOption(
'pymongo.read_preference.ReadPreference',
_READ_PREFERENCE_PRIMARY,
('document', 'mode', 'mongos_mode', 'max_staleness'),
),
'write_concern': _KwargOption(
'pymongo.write_concern.WriteConcern', WriteConcern(), ('acknowledged', 'document')
),
}
VALID_UPDATE_PIPELINE_STAGES = (
'$addFields',
'$set',
'$project',
'$unset',
'$replaceRoot',
'$replaceWith',
)
def validate_list_or_mapping(option, value):
if not isinstance(value, (Mapping, list)):
raise TypeError(
f'{option} must either be a list or an instance of dict, '
'bson.son.SON, or any other type that inherits from '
'collections.Mapping'
)
def _bson_encode(document, check_keys, codec_options):
if codec_options:
if isinstance(codec_options, mongomock_codec_options.CodecOptions):
codec_options = codec_options.to_pymongo()
if isinstance(codec_options, CodecOptions):
BSON.encode(document, check_keys=check_keys, codec_options=codec_options)
else:
BSON.encode(document, check_keys=check_keys)
def validate_is_mapping(option, value):
if not isinstance(value, Mapping):
raise TypeError(
f'{option} must be an instance of dict, bson.son.SON, or '
'other type that inherits from '
'collections.Mapping'
)
def validate_is_mutable_mapping(option, value):
if not isinstance(value, MutableMapping):
raise TypeError(
f'{option} must be an instance of dict, bson.son.SON, or '
'other type that inherits from '
'collections.MutableMapping'
)
def validate_ok_for_replace(replacement):
validate_is_mapping('replacement', replacement)
if replacement:
first = next(iter(replacement))
if first.startswith('$'):
raise ValueError('replacement can not include $ operators')
def validate_ok_for_update(update):
validate_list_or_mapping('update', update)
if not update:
raise ValueError('update cannot be empty')
is_document = not isinstance(update, list)
first = next(iter(update))
if is_document and not first.startswith('$'):
raise ValueError('update only works with $ operators')
def validate_write_concern_params(**params):
if params:
WriteConcern(**params)
class BulkWriteOperation:
def __init__(self, builder, selector, is_upsert=False):
self.builder = builder
self.selector = selector
self.is_upsert = is_upsert
def upsert(self):
assert not self.is_upsert
return BulkWriteOperation(self.builder, self.selector, is_upsert=True)
def register_remove_op(self, multi, hint=None):
collection = self.builder.collection
selector = self.selector
def exec_remove():
if multi:
op_result = collection.delete_many(selector, hint=hint).raw_result
else:
op_result = collection.delete_one(selector, hint=hint).raw_result
if op_result.get('ok'):
return {'nRemoved': op_result.get('n')}
err = op_result.get('err')
if err:
return {'writeErrors': [err]}
return {}
self.builder.executors.append(exec_remove)
def remove(self):
assert not self.is_upsert
self.register_remove_op(multi=True)
def remove_one(
self,
):
assert not self.is_upsert
self.register_remove_op(multi=False)
def register_update_op(self, document, multi, **extra_args):
if not extra_args.get('remove'):
validate_ok_for_update(document)
collection = self.builder.collection
selector = self.selector
def exec_update():
result = collection._update(
spec=selector, document=document, multi=multi, upsert=self.is_upsert, **extra_args
)
ret_val = {}
if result.get('upserted'):
ret_val['upserted'] = result.get('upserted')
ret_val['nUpserted'] = result.get('n')
else:
matched = result.get('n')
if matched is not None:
ret_val['nMatched'] = matched
modified = result.get('nModified')
if modified is not None:
ret_val['nModified'] = modified
if result.get('err'):
ret_val['err'] = result.get('err')
return ret_val
self.builder.executors.append(exec_update)
def update(self, document, hint=None, sort=None):
self.register_update_op(document, multi=True, hint=hint, sort=sort)
def update_one(self, document, hint=None, sort=None):
self.register_update_op(document, multi=False, hint=hint, sort=sort)
def replace_one(self, document, hint=None, sort=None):
self.register_update_op(document, multi=False, remove=True, hint=hint, sort=sort)
def _combine_projection_spec(projection_fields_spec):
"""Re-format a projection fields spec into a nested dictionary.
e.g: {'a': 1, 'b.c': 1, 'b.d': 1} => {'a': 1, 'b': {'c': 1, 'd': 1}}
"""
tmp_spec = OrderedDict()
for f, v in projection_fields_spec.items():
if '.' not in f:
if isinstance(tmp_spec.get(f), dict):
if not v:
raise NotImplementedError(
f'Mongomock does not support overriding excluding '
f'projection: {projection_fields_spec}'
)
raise OperationFailure(f'Path collision at {f}')
tmp_spec[f] = v
else:
split_field = f.split('.', 1)
base_field, new_field = tuple(split_field)
if not isinstance(tmp_spec.get(base_field), dict):
if base_field in tmp_spec:
raise OperationFailure(f'Path collision at {f} remaining portion {new_field}')
tmp_spec[base_field] = OrderedDict()
tmp_spec[base_field][new_field] = v
combined_spec = OrderedDict()
for f, v in tmp_spec.items():
if isinstance(v, dict):
combined_spec[f] = _combine_projection_spec(v)
else:
combined_spec[f] = v
return combined_spec
def _project_by_spec(doc, combined_projection_spec, is_include, container):
if '$' in combined_projection_spec:
if is_include:
raise NotImplementedError('Positional projection is not implemented in mongomock')
raise OperationFailure('Cannot exclude array elements with the positional operator')
doc_copy = container()
for key, val in doc.items():
spec = combined_projection_spec.get(key, NOTHING)
if isinstance(spec, dict):
if isinstance(val, (list, tuple)):
doc_copy[key] = [
_project_by_spec(sub_doc, spec, is_include, container) for sub_doc in val
]
elif isinstance(val, dict):
doc_copy[key] = _project_by_spec(val, spec, is_include, container)
elif (is_include and spec is not NOTHING) or (not is_include and spec is NOTHING):
doc_copy[key] = _copy_field(val, container)
return doc_copy
def _copy_field(obj, container):
if isinstance(obj, list):
new = []
for item in obj:
new.append(_copy_field(item, container))
return new
if isinstance(obj, dict):
new = container()
for key, value in obj.items():
new[key] = _copy_field(value, container)
return new
return copy.copy(obj)
def _recursive_key_check_null_character(data):
for key, value in data.items():
if '\0' in key:
raise InvalidDocument(f'Field names cannot contain the null character (found: {key})')
if isinstance(value, Mapping):
_recursive_key_check_null_character(value)
def _validate_data_fields(data):
_recursive_key_check_null_character(data)
for key in data:
if key.startswith('$'):
raise InvalidDocument(
f'Top-level field names cannot start with the "$" sign (found: {key})'
)
def _validate_document_stages(document):
for stage in document:
for stage_name in stage:
aggregate.validate_stage_name(stage_name)
if stage_name not in VALID_UPDATE_PIPELINE_STAGES:
raise WriteError(f'{stage_name} is not allowed to be used within an update')
class BulkOperationBuilder:
def __init__(self, collection, ordered=False, bypass_document_validation=False):
self.collection = collection
self.ordered = ordered
self.results = {}
self.executors = []
self.done = False
self._insert_returns_nModified = True
self._update_returns_nModified = True
self._bypass_document_validation = bypass_document_validation
def find(self, selector):
return BulkWriteOperation(self, selector)
def insert(self, doc):
def exec_insert():
self.collection.insert_one(
doc, bypass_document_validation=self._bypass_document_validation
)
return {'nInserted': 1}
self.executors.append(exec_insert)
def __aggregate_operation_result(self, total_result, key, value):
agg_val = total_result.get(key)
assert agg_val is not None, f'Unknow operation result {key}={value} (unrecognized key)'
if isinstance(agg_val, int):
total_result[key] += value
elif isinstance(agg_val, list):
if key == 'upserted':
new_element = {'index': len(agg_val), '_id': value}
agg_val.append(new_element)
else:
agg_val.append(value)
else:
raise AssertionError(
f'Fixme: missed aggreation rule for type: {type(agg_val)} '
f'for key {key}={agg_val}'
)
def _set_nModified_policy(self, insert, update): # noqa: N802
self._insert_returns_nModified = insert
self._update_returns_nModified = update
def execute(self, write_concern=None):
if not self.executors:
raise InvalidOperation('Bulk operation empty!')
if self.done:
raise InvalidOperation('Bulk operation already executed!')
self.done = True
result = {
'nModified': 0,
'nUpserted': 0,
'nMatched': 0,
'writeErrors': [],
'upserted': [],
'writeConcernErrors': [],
'nRemoved': 0,
'nInserted': 0,
}
has_update = False
has_insert = False
broken_nModified_info = False # noqa: N806
for index, execute_func in enumerate(self.executors):
exec_name = execute_func.__name__
try:
op_result = execute_func()
except WriteError as error:
result['writeErrors'].append(
{
'index': index,
'code': error.code,
'errmsg': str(error),
}
)
if self.ordered:
break
continue
for key, value in op_result.items():
self.__aggregate_operation_result(result, key, value)
if exec_name == 'exec_update':
has_update = True
if 'nModified' not in op_result:
broken_nModified_info = True # noqa: N806
has_insert |= exec_name == 'exec_insert'
if broken_nModified_info:
result.pop('nModified')
elif (
has_insert
and self._insert_returns_nModified
or has_update
and self._update_returns_nModified
or self._update_returns_nModified
and self._insert_returns_nModified
):
pass
else:
result.pop('nModified')
if result.get('writeErrors'):
raise BulkWriteError(result)
return result
def add_insert(self, doc):
self.insert(doc)
def add_update(
self,
selector,
doc,
multi=False,
upsert=False,
collation=None,
array_filters=None,
hint=None,
sort=None,
):
if array_filters:
raise_not_implemented(
'array_filters', 'Array filters are not implemented in mongomock yet.'
)
write_operation = BulkWriteOperation(self, selector, is_upsert=upsert)
write_operation.register_update_op(doc, multi, hint=hint, sort=sort)
def add_replace(self, selector, doc, upsert, collation=None, hint=None, sort=None):
write_operation = BulkWriteOperation(self, selector, is_upsert=upsert)
write_operation.replace_one(doc, hint=hint, sort=sort)
def add_delete(self, selector, just_one, collation=None, hint=None):
write_operation = BulkWriteOperation(self, selector, is_upsert=False)
write_operation.register_remove_op(not just_one, hint=hint)
class Collection:
def __init__(
self,
database,
name,
_db_store,
write_concern=None,
read_concern=None,
read_preference=None,
codec_options=None,
):
self.database = database
self._name = name
self._db_store = _db_store
self._write_concern = write_concern or WriteConcern()
if read_concern and not isinstance(read_concern, ReadConcern):
raise TypeError('read_concern must be an instance of pymongo.read_concern.ReadConcern')
self._read_concern = read_concern or ReadConcern()
self._read_preference = read_preference or _READ_PREFERENCE_PRIMARY
self._codec_options = codec_options or mongomock_codec_options.CodecOptions()
def __repr__(self):
return f"Collection({self.database}, '{self.name}')"
def __getitem__(self, name):
return self.database[self.name + '.' + name]
def __getattr__(self, attr):
if attr.startswith('_'):
raise AttributeError(
f"{self.__class__.__name__} has no attribute '{attr}'. "
f"To access the {self.name}.{attr} collection, use database['{self.name}.{attr}']."
)
return self.__getitem__(attr)
def __call__(self, *args, **kwargs):
name = self._name if '.' not in self._name else self._name.split('.')[-1]
raise TypeError(
f"'Collection' object is not callable. If you meant to call the '{name}' method on a "
"'Collection' object it is failing because no such method exists."
)
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.database == other.database and self.name == other.name
return NotImplemented
if version.parse('3.12') <= helpers.PYMONGO_VERSION:
def __hash__(self):
return hash((self.database, self.name))
@property
def full_name(self):
return f'{self.database.name}.{self._name}'
@property
def name(self):
return self._name
@property
def write_concern(self):
return self._write_concern
@property
def read_concern(self):
return self._read_concern
@property
def read_preference(self):
return self._read_preference
@property
def codec_options(self):
return self._codec_options
def initialize_unordered_bulk_op(self, bypass_document_validation=False):
return BulkOperationBuilder(
self, ordered=False, bypass_document_validation=bypass_document_validation
)
def initialize_ordered_bulk_op(self, bypass_document_validation=False):
return BulkOperationBuilder(
self, ordered=True, bypass_document_validation=bypass_document_validation
)
if version.parse('4.0') > helpers.PYMONGO_VERSION:
def insert(self, data, manipulate=True, check_keys=True, continue_on_error=False, **kwargs):
warnings.warn(
'insert is deprecated. Use insert_one or insert_many ' 'instead.',
DeprecationWarning,
stacklevel=2,
)
validate_write_concern_params(**kwargs)
return self._insert(data)
def insert_one(self, document, bypass_document_validation=False, session=None):
if not bypass_document_validation:
validate_is_mutable_mapping('document', document)
return InsertOneResult(self._insert(document, session), acknowledged=True)
def insert_many(self, documents, ordered=True, bypass_document_validation=False, session=None):
if not isinstance(documents, Iterable) or not documents:
raise TypeError('documents must be a non-empty list')
documents = list(documents)
if not bypass_document_validation:
for document in documents:
validate_is_mutable_mapping('document', document)
return InsertManyResult(
self._insert(documents, session, ordered=ordered), acknowledged=True
)
@property
def _store(self):
return self._db_store[self._name]
def _insert(self, data, session=None, ordered=True):
if session:
raise_not_implemented('session', 'Mongomock does not handle sessions yet')
if not isinstance(data, Mapping):
results = []
write_errors = []
num_inserted = 0
for index, item in enumerate(data):
try:
results.append(self._insert(item))
except WriteError as error:
write_errors.append(
{
'index': index,
'code': error.code,
'errmsg': str(error),
'op': item,
}
)
if ordered:
break
else:
continue
num_inserted += 1
if write_errors:
raise BulkWriteError(
{
'writeErrors': write_errors,
'nInserted': num_inserted,
}
)
return results
if not all(isinstance(k, str) for k in data):
raise ValueError('Document keys must be strings')
if BSON:
# bson validation
check_keys = version.parse('3.6') > helpers.PYMONGO_VERSION
if not check_keys:
_validate_data_fields(data)
_bson_encode(data, check_keys=check_keys, codec_options=self._codec_options)
# Like pymongo, we should fill the _id in the inserted dict (odd behavior,
# but we need to stick to it), so we must patch in-place the data dict
if '_id' not in data:
data['_id'] = ObjectId()
object_id = data['_id']
if isinstance(object_id, dict):
object_id = helpers.hashdict(object_id)
if object_id in self._store:
raise DuplicateKeyError('E11000 Duplicate Key Error', 11000)
data = helpers.patch_datetime_awareness_in_document(data)
self._store[object_id] = data
try:
self._ensure_uniques(data)
except DuplicateKeyError:
# Rollback
del self._store[object_id]
raise
return data['_id']
def _ensure_uniques(self, new_data):
# Note we consider new_data is already inserted in db
for index in self._store.indexes.values():
if not index.get('unique'):
continue
unique = index.get('key')
is_sparse = index.get('sparse')
partial_filter_expression = index.get('partialFilterExpression')
find_kwargs = {}
for key, _ in unique:
try:
find_kwargs[key] = helpers.get_value_by_dot(new_data, key)
except KeyError:
find_kwargs[key] = None
if is_sparse and set(find_kwargs.values()) == {None}:
continue
if partial_filter_expression is not None:
find_kwargs = {'$and': [partial_filter_expression, find_kwargs]}
answer_count = len(list(self._iter_documents(find_kwargs)))
if answer_count > 1:
raise DuplicateKeyError('E11000 Duplicate Key Error', 11000)
def _internalize_dict(self, d):
return {k: copy.deepcopy(v) for k, v in d.items()}
def _has_key(self, doc, key):
key_parts = key.split('.')
sub_doc = doc
for part in key_parts:
if part not in sub_doc:
return False
sub_doc = sub_doc[part]
return True
def update_one(
self,
filter,
update,
upsert=False,
bypass_document_validation=False,
collation=None,
array_filters=None,
hint=None,
session=None,
let=None,
sort=None,
):
if not bypass_document_validation:
validate_ok_for_update(update)
return UpdateResult(
self._update(
filter,
update,
upsert=upsert,
hint=hint,
session=session,
collation=collation,
array_filters=array_filters,
let=let,
sort=sort,
),
acknowledged=True,
)
def update_many(
self,
filter,
update,
upsert=False,
array_filters=None,
bypass_document_validation=False,
collation=None,
hint=None,
session=None,
let=None,
):
if not bypass_document_validation:
validate_ok_for_update(update)
return UpdateResult(
self._update(
filter,
update,
upsert=upsert,
multi=True,
hint=hint,
session=session,
collation=collation,
array_filters=array_filters,
let=let,
),
acknowledged=True,
)
def replace_one(
self,
filter,
replacement,
upsert=False,
bypass_document_validation=False,
session=None,
hint=None,
sort=None,
):
if not bypass_document_validation:
validate_ok_for_replace(replacement)
return UpdateResult(
self._update(filter, replacement, upsert=upsert, hint=hint, session=session, sort=sort),
acknowledged=True,
)
if version.parse('4.0') > helpers.PYMONGO_VERSION:
def update(
self,
spec,
document,
upsert=False,
manipulate=False,
multi=False,
check_keys=False,
**kwargs,
):
warnings.warn(
'update is deprecated. Use replace_one, update_one or ' 'update_many instead.',
DeprecationWarning,
stacklevel=2,
)
return self._update(spec, document, upsert, manipulate, multi, check_keys, **kwargs)
def _update(
self,
spec,
document,
upsert=False,
manipulate=False,
multi=False,
check_keys=False,
hint=None,
session=None,
collation=None,
let=None,
array_filters=None,
**kwargs,
):
if session:
raise_not_implemented('session', 'Mongomock does not handle sessions yet')
if hint:
raise NotImplementedError(
'The hint argument of update is valid but has not been implemented in '
'mongomock yet'
)
if collation:
raise_not_implemented(
'collation',
'The collation argument of update is valid but has not been implemented in '
'mongomock yet',
)
if array_filters:
raise_not_implemented(
'array_filters', 'Array filters are not implemented in mongomock yet.'
)
if let:
raise_not_implemented(
'let',
'The let argument of update is valid but has not been implemented in mongomock '
'yet',
)
spec = helpers.patch_datetime_awareness_in_document(spec)
document = helpers.patch_datetime_awareness_in_document(document)
validate_is_mapping('spec', spec)
validate_list_or_mapping('document', document)
if isinstance(document, list):
_validate_document_stages(document)
if self.database.client.server_info()['versionArray'] < [5]:
for operator in _updaters:
if not document.get(operator, True):
raise WriteError(
f"'{operator}' is empty. You must specify a field like so: "
'{' + operator + ': {<field>: ...}}'
)
updated_existing = False
upserted_id = None
num_updated = 0
num_matched = 0
for existing_document in itertools.chain(self._iter_documents(spec), [None]):
# we need was_insert for the setOnInsert update operation
was_insert = False
# the sentinel document means we should do an upsert
if existing_document is None:
if not upsert or num_matched:
continue
# For upsert operation we have first to create a fake existing_document,
# update it like a regular one, then finally insert it
if spec.get('_id') is not None:
_id = spec['_id']
elif not isinstance(document, list) and document.get('_id') is not None:
_id = document['_id']
else:
_id = ObjectId()
to_insert = dict(spec, _id=_id)
to_insert = self._expand_dots(to_insert)
to_insert, _ = self._discard_operators(to_insert)
existing_document = to_insert
was_insert = True
else:
original_document_snapshot = copy.deepcopy(existing_document)
updated_existing = True
num_matched += 1
if isinstance(document, list):
self._apply_update_pipeline(existing_document, document, session)
else:
self._apply_update_document(existing_document, spec, document, was_insert)
if was_insert:
upserted_id = self._insert(existing_document)
num_updated += 1
elif existing_document != original_document_snapshot:
# Document has been modified in-place.
# Make sure the ID was not change.
if original_document_snapshot.get('_id') != existing_document.get('_id'):
# Rollback.
self._store[original_document_snapshot['_id']] = original_document_snapshot
raise WriteError(
"After applying the update, the (immutable) field '_id' was found to have "
'been altered to _id: {}'.format(existing_document.get('_id'))
)
# Make sure it still respect the unique indexes and, if not, to
# revert modifications
try:
self._ensure_uniques(existing_document)
num_updated += 1
except DuplicateKeyError:
# Rollback.
self._store[original_document_snapshot['_id']] = original_document_snapshot
raise
if not multi:
break
return {
'connectionId': self.database.client._id,
'err': None,
'n': num_matched,
'nModified': num_updated if updated_existing else 0,
'ok': 1,
'upserted': upserted_id,
'updatedExisting': updated_existing,
}
def _apply_update_pipeline(self, existing_document, pipeline, session):
"""Apply the aggregation pipeline to a single document.
This method updates existing_document in-place.
"""
[new_document] = aggregate.process_pipeline(
[existing_document], self.database, pipeline, session
)
existing_document.clear()
existing_document.update(new_document)
def _apply_update_document(self, existing_document, spec, document, was_insert): # noqa: C901
"""Apply document, which is an update document, to existing_document.
This method updates existing_document in-place.
"""
first = True
subdocument = None
for k, v in document.items():
if k in _updaters:
updater = _updaters[k]
subdocument = self._update_document_fields_with_positional_awareness(
existing_document, v, spec, updater, subdocument
)
elif k == '$rename':
for src, dst in v.items():
if '.' in src or '.' in dst:
raise NotImplementedError(
'Using the $rename operator with dots is a valid MongoDB '
'operation, but it is not yet supported by mongomock'
)
if self._has_key(existing_document, src):
existing_document[dst] = existing_document.pop(src)
elif k == '$setOnInsert':
if not was_insert:
continue
subdocument = self._update_document_fields_with_positional_awareness(
existing_document, v, spec, _set_updater, subdocument
)
elif k == '$currentDate':
subdocument = self._update_document_fields_with_positional_awareness(
existing_document, v, spec, _current_date_updater, subdocument
)
elif k == '$addToSet':
for field, value in v.items():
nested_field_list = field.rsplit('.')
if len(nested_field_list) == 1:
if field not in existing_document:
existing_document[field] = []
# document should be a list append to it
if isinstance(value, dict) and '$each' in value:
# append the list to the field
existing_document[field] += [
obj
for obj in list(value['$each'])
if obj not in existing_document[field]
]
continue
if value not in existing_document[field]:
existing_document[field].append(value)
continue
# push to array in a nested attribute
else:
# create nested attributes if they do not exist
subdocument = existing_document
for field_part in nested_field_list[:-1]:
if field_part == '$':
break
if field_part not in subdocument:
subdocument[field_part] = {}
subdocument = subdocument[field_part]
# get subdocument with $ oprator support
subdocument, _ = self._get_subdocument(
existing_document, spec, nested_field_list
)
# we're pushing a list
push_results = []
if nested_field_list[-1] in subdocument:
# if the list exists, then use that list
push_results = subdocument[nested_field_list[-1]]
if isinstance(value, dict) and '$each' in value:
push_results += [
obj for obj in list(value['$each']) if obj not in push_results
You can’t perform that action at this time.
