/
collection.py
1380 lines (1097 loc) · 53 KB
/
collection.py
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
# Copyright 2009-2015 The TxMongo Developers. All rights reserved.
# Use of this source code is governed by the Apache License that can be
# found in the LICENSE file.
from __future__ import absolute_import, division
import io
import struct
import collections.abc
import warnings
from bson import BSON, ObjectId
from bson.code import Code
from bson.son import SON
from bson.codec_options import CodecOptions
from pymongo.bulk import _Bulk, _COMMANDS
from pymongo.errors import InvalidName, BulkWriteError, InvalidOperation, OperationFailure
from pymongo.message import _OP_MAP, _INSERT
from pymongo.results import InsertOneResult, InsertManyResult, UpdateResult, \
DeleteResult, BulkWriteResult
from pymongo.common import validate_ok_for_update, validate_ok_for_replace, \
validate_is_mapping, validate_boolean
from pymongo.collection import ReturnDocument
from pymongo.write_concern import WriteConcern
from txmongo.filter import _QueryFilter
from txmongo.protocol import DELETE_SINGLE_REMOVE, UPDATE_UPSERT, UPDATE_MULTI, \
Query, Getmore, Insert, Update, Delete, KillCursors
from txmongo.pymongo_internals import _check_write_command_response, _merge_command, _check_command_response
from txmongo.utils import check_deadline, timeout
from txmongo import filter as qf
from twisted.internet import defer
from twisted.python.compat import comparable
@comparable
class Collection(object):
"""Creates new :class:`Collection` object
:param database:
the :class:`Database` instance to get collection from
:param name:
the name of the collection to get
:param write_concern:
An instance of :class:`~pymongo.write_concern.WriteConcern`.
If ``None``, ``database.write_concern`` is used.
:param codec_options:
An instance of :class:`~bson.codec_options.CodecOptions`.
If ``None``, ``database.codec_options`` is used.
"""
def __init__(self, database, name, write_concern=None, codec_options=None):
if not isinstance(name, (bytes, str)):
raise TypeError("TxMongo: name must be an instance of (bytes, str).")
if not name or ".." in name:
raise InvalidName("TxMongo: collection names cannot be empty.")
if "$" in name and not (name.startswith("oplog.$main") or
name.startswith("$cmd")):
msg = "TxMongo: collection names must not contain '$', '{0}'".format(repr(name))
raise InvalidName(msg)
if name[0] == "." or name[-1] == ".":
msg = "TxMongo: collection names must not start or end with '.', '{0}'".format(repr(name))
raise InvalidName(msg)
if "\x00" in name:
raise InvalidName("TxMongo: collection names must not contain the null character.")
self._database = database
self._collection_name = str(name)
self.__write_concern = write_concern
self.__codec_options = codec_options
def __str__(self):
return "%s.%s" % (str(self._database), self._collection_name)
def __repr__(self):
return "Collection(%s, %s)" % (self._database, self._collection_name)
@property
def full_name(self):
"""Full name of this :class:`Collection`, i.e.
`db_name.collection_name`"""
return '{0}.{1}'.format(str(self._database), self._collection_name)
@property
def name(self):
"""Name of this :class:`Collection` (without database name)."""
return self._collection_name
@property
def database(self):
"""The :class:`~txmongo.database.Database` that this :class:`Collection`
is a part of."""
return self._database
def __getitem__(self, collection_name):
"""Get a sub-collection of this collection by name."""
return Collection(self._database,
"%s.%s" % (self._collection_name, collection_name))
def __cmp__(self, other):
if isinstance(other, Collection):
def cmp(a, b):
return (a > b) - (a < b)
return cmp((self._database, self._collection_name),
(other._database, other._collection_name))
return NotImplemented
def __getattr__(self, collection_name):
"""Get a sub-collection of this collection by name."""
return self[collection_name]
def __call__(self, collection_name):
"""Get a sub-collection of this collection by name."""
return self[collection_name]
@property
def codec_options(self):
"""Read only access to the :class:`~bson.codec_options.CodecOptions`
of this instance.
Use ``coll.with_options(codec_options=CodecOptions(...))`` to change
codec options.
"""
return self.__codec_options or self._database.codec_options
@property
def write_concern(self):
"""Read only access to the :class:`~pymongo.write_concern.WriteConcern`
of this instance.
Use ``coll.with_options(write_concern=WriteConcern(...))`` to change
the Write Concern.
"""
return self.__write_concern or self._database.write_concern
def with_options(self, **kwargs):
"""with_options(*, write_concern=None, codec_options=None)
Get a clone of collection changing the specified settings.
:param write_concern: *(keyword only)*
new :class:`~pymongo.write_concern.WriteConcern` to use.
:param codec_options: *(keyword only)*
new :class:`~bson.codec_options.CodecOptions` to use.
"""
# PyMongo's method gets several positional arguments. We support
# only write_concern for now which is the 3rd positional argument.
# So we are using **kwargs here to force user's code to specify
# write_concern as named argument, so adding other args in future
# won't break compatibility
write_concern = kwargs.get("write_concern") or self.__write_concern
codec_options = kwargs.get("codec_options") or self.codec_options
return Collection(self._database, self._collection_name,
write_concern=write_concern,
codec_options=codec_options)
@staticmethod
def _normalize_fields_projection(fields):
"""
transform a list of fields from ["a", "b"] to {"a":1, "b":1}
"""
if fields is None:
return None
if isinstance(fields, dict):
return fields
# Consider fields as iterable
as_dict = {}
for field in fields:
if not isinstance(field, (bytes, str)):
raise TypeError("TxMongo: fields must be a list of key names.")
as_dict[field] = 1
if not as_dict:
# Empty list should be treated as "_id only"
as_dict = {"_id": 1}
return as_dict
@staticmethod
def _gen_index_name(keys):
return u'_'.join([u"%s_%s" % item for item in keys])
def _list_collections_3_0(self):
def on_ok(response):
assert response["cursor"]["id"] == 0
first_batch = response["cursor"]["firstBatch"]
if first_batch:
return first_batch[0]
else:
return None
return self._database.command(
SON([("listCollections", 1),
("filter", {"name": self.name})])).addCallback(on_ok)
@timeout
def options(self, _deadline=None):
"""options()
Get the options set on this collection.
:returns:
:class:`Deferred` that called back with dictionary of options
and their values or with empty dict if collection doesn't exist.
"""
def on_3_0_fail(failure):
failure.trap(OperationFailure)
return self._database.system.namespaces.find_one({"name": str(self)}, _deadline=_deadline)
def on_ok(result):
if not result:
result = {}
options = result.get("options", {})
if "create" in options:
del options["create"]
return options
return self._list_collections_3_0()\
.addErrback(on_3_0_fail)\
.addCallbacks(on_ok)
@staticmethod
def _find_args_compat(*args, **kwargs):
"""
signature of find() was changed from
(spec=None, skip=0, limit=0, fields=None, filter=None, cursor=False, **kwargs)
to
(filter=None, projection=None, skip=0, limit=0, sort=None, **kwargs)
This function makes it compatible with both
"""
def old(spec=None, skip=0, limit=0, fields=None, filter=None, cursor=False, **kwargs):
warnings.warn("find(), find_with_cursor() and find_one() signatures have "
"changed. Please refer to documentation.", DeprecationWarning)
return new(spec, fields, skip, limit, filter, cursor=cursor, **kwargs)
def new(filter=None, projection=None, skip=0, limit=0, sort=None, **kwargs):
args = {"filter": filter, "projection": projection, "skip": skip, "limit": limit,
"sort": sort}
args.update(kwargs)
return args
old_if = (
"fields" in kwargs,
"spec" in kwargs,
len(args) == 0 and isinstance(kwargs.get("filter"), _QueryFilter),
len(args) >= 1 and "filter" in kwargs,
len(args) >= 2 and isinstance(args[1], int),
)
if any(old_if):
return old(*args, **kwargs)
else:
return new(*args, **kwargs)
@timeout
def find(self, *args, **kwargs):
"""find(filter=None, projection=None, skip=0, limit=0, sort=None, **kwargs)
Find documents in a collection.
Ordering, indexing hints and other query parameters can be set with
`sort` argument. See :mod:`txmongo.filter` for details.
:param filter:
MongoDB query document. To return all documents in a collection,
omit this parameter or pass an empty document (``{}``). You can pass
``{"key": "value"}`` to select documents having ``key`` field
equal to ``"value"`` or use any of `MongoDB's query selectors
<https://docs.mongodb.org/manual/reference/operator/query/#query-selectors>`_.
:param projection:
a list of field names that should be returned for each document
in the result set or a dict specifying field names to include or
exclude. If `projection` is a list ``_id`` fields will always be
returned. Use a dict form to exclude fields:
``projection={"_id": False}``.
:param skip:
the number of documents to omit from the start of the result set.
:param limit:
the maximum number of documents to return. All documents are
returned when `limit` is zero.
:param sort:
query filter. You can specify ordering, indexing hints and other query
parameters with this argument. See :mod:`txmongo.filter` for details.
:returns: an instance of :class:`Deferred` that called back with a list with
all documents found.
"""
new_kwargs = self._find_args_compat(*args, **kwargs)
return self.__real_find(**new_kwargs)
def __real_find(self, filter=None, projection=None, skip=0, limit=0, sort=None, **kwargs):
cursor = kwargs.pop("cursor", False)
rows = []
def on_ok(result, this_func):
docs, dfr = result
if cursor:
warnings.warn("find() with cursor=True is deprecated. Please use"
"find_with_cursor() instead.", DeprecationWarning)
return docs, dfr
if docs:
rows.extend(docs)
return dfr.addCallback(this_func, this_func)
else:
return rows
return self.__real_find_with_cursor(filter, projection, skip, limit, sort,
**kwargs).addCallback(on_ok, on_ok)
@staticmethod
def __apply_find_filter(spec, c_filter):
if c_filter:
if "query" not in spec:
spec = {"$query": spec}
for k, v in c_filter.items():
if isinstance(v, (list, tuple)):
spec['$' + k] = SON(v)
else:
spec['$' + k] = v
return spec
@timeout
def find_with_cursor(self, *args, **kwargs):
"""find_with_cursor(filter=None, projection=None, skip=0, limit=0, sort=None, batch_size=0, **kwargs)
Find documents in a collection and return them in one batch at a time.
Arguments are the same as for :meth:`find()`.
:returns: an instance of :class:`Deferred` that fires with tuple of ``(docs, dfr)``,
where ``docs`` is a partial result, returned by MongoDB in a first batch and
``dfr`` is a :class:`Deferred` that fires with next ``(docs, dfr)``. Last result
will be ``([], None)``. You can iterate over the result set with code like that:
::
@defer.inlineCallbacks
def query():
docs, dfr = yield coll.find(query, cursor=True)
while docs:
for doc in docs:
do_something(doc)
docs, dfr = yield dfr
"""
new_kwargs = self._find_args_compat(*args, **kwargs)
return self.__real_find_with_cursor(**new_kwargs)
def __real_find_with_cursor(self, filter=None, projection=None, skip=0, limit=0, sort=None, batch_size=0,**kwargs):
if filter is None:
filter = SON()
if not isinstance(filter, dict):
raise TypeError("TxMongo: filter must be an instance of dict.")
if not isinstance(projection, (dict, list)) and projection is not None:
raise TypeError("TxMongo: projection must be an instance of dict or list.")
if not isinstance(skip, int):
raise TypeError("TxMongo: skip must be an instance of int.")
if not isinstance(limit, int):
raise TypeError("TxMongo: limit must be an instance of int.")
if not isinstance(batch_size, int):
raise TypeError("TxMongo: batch_size must be an instance of int.")
projection = self._normalize_fields_projection(projection)
filter = self.__apply_find_filter(filter, sort)
as_class = kwargs.get("as_class")
proto = self._database.connection.getprotocol()
def after_connection(protocol):
flags = kwargs.get("flags", 0)
check_deadline(kwargs.pop("_deadline", None))
if batch_size and limit:
n_to_return = min(batch_size,limit)
elif batch_size:
n_to_return = batch_size
else:
n_to_return = limit
query = Query(flags=flags, collection=str(self),
n_to_skip=skip, n_to_return=n_to_return,
query=filter, fields=projection)
deferred_query = protocol.send_QUERY(query)
deferred_query.addCallback(after_reply, protocol, after_reply)
return deferred_query
# this_func argument is just a reference to after_reply function itself.
# after_reply can reference to itself directly but this will create a circular
# reference between closure and function object which will add unnecessary
# work for GC.
def after_reply(reply, protocol, this_func, fetched=0):
documents = reply.documents
docs_count = len(documents)
if limit > 0:
docs_count = min(docs_count, limit - fetched)
fetched += docs_count
options = self.codec_options
if as_class is not None:
options = options._replace(document_class=as_class)
out = [document.decode(codec_options=options) for document in documents[:docs_count]]
if reply.cursor_id:
# please note that this will not be the case if batch_size = 1
# it is documented (parameter numberToReturn for OP_QUERY)
# https://docs.mongodb.com/manual/reference/mongodb-wire-protocol/#wire-op-query
if limit == 0:
to_fetch = 0 # no limit
if batch_size:
to_fetch = batch_size
elif limit < 0:
# We won't actually get here because MongoDB won't
# create cursor when limit < 0
to_fetch = None
else:
to_fetch = limit - fetched
if to_fetch <= 0:
to_fetch = None # close cursor
elif batch_size:
to_fetch = min(batch_size,to_fetch)
if to_fetch is None:
protocol.send_KILL_CURSORS(KillCursors(cursors=[reply.cursor_id]))
return out, defer.succeed(([], None))
next_reply = protocol.send_GETMORE(Getmore(
collection=str(self), cursor_id=reply.cursor_id,
n_to_return=to_fetch
))
next_reply.addCallback(this_func, protocol, this_func, fetched)
return out, next_reply
return out, defer.succeed(([], None))
proto.addCallback(after_connection)
return proto
@timeout
def find_one(self, *args, **kwargs):
"""find_one(filter=None, projection=None, **kwargs)
Get a single document from the collection.
All arguments to :meth:`find()` are also valid for :meth:`find_one()`,
although `limit` will be ignored.
:returns:
a :class:`Deferred` that called back with single document
or ``None`` if no matching documents is found.
"""
new_kwargs = self._find_args_compat(*args, **kwargs)
if isinstance(new_kwargs["filter"], ObjectId):
new_kwargs["filter"] = {"_id": new_kwargs["filter"]}
new_kwargs["limit"] = 1
return self.__real_find(**new_kwargs)\
.addCallback(lambda result: result[0] if result else None)
@timeout
def count(self, filter=None, **kwargs):
"""Get the number of documents in this collection.
:param filter:
argument is a query document that selects which documents to
count in the collection.
:param hint: *(keyword only)*
:class:`~txmongo.filter.hint` instance specifying index to use.
:param int limit: *(keyword only)*
The maximum number of documents to count.
:param int skip: *(keyword only)*
The number of matching documents to skip before returning results.
:returns: a :class:`Deferred` that called back with a number of
documents matching the criteria.
"""
if "spec" in kwargs:
filter = kwargs["spec"]
if "hint" in kwargs:
hint = kwargs["hint"]
if not isinstance(hint, qf.hint):
raise TypeError("hint must be an instance of txmongo.filter.hint")
kwargs["hint"] = SON(kwargs["hint"]["hint"])
return self._database.command("count", self._collection_name,
query=filter or SON(), **kwargs)\
.addCallback(lambda result: int(result['n']))
@timeout
def group(self, keys, initial, reduce, condition=None, finalize=None, **kwargs):
body = {
"ns": self._collection_name,
"initial": initial,
"$reduce": Code(reduce),
}
if isinstance(keys, (bytes, str)):
body["$keyf"] = Code(keys)
else:
body["key"] = self._normalize_fields_projection(keys)
if condition:
body["cond"] = condition
if finalize:
body["finalize"] = Code(finalize)
return self._database.command("group", body, **kwargs)
@timeout
def filemd5(self, spec, **kwargs):
if not isinstance(spec, ObjectId):
raise ValueError("TxMongo: filemd5 expected an objectid for its non-keyword argument.")
return self._database.command("filemd5", spec, root=self._collection_name, **kwargs)\
.addCallback(lambda result: result.get("md5"))
def _get_write_concern(self, safe=None, **options):
from_opts = WriteConcern(options.get("w"),
options.get("wtimeout"),
options.get("j"),
options.get("fsync"))
if from_opts.document:
return from_opts
if safe is None:
return self.write_concern
elif safe:
if self.write_concern.acknowledged:
return self.write_concern
else:
# Edge case: MongoConnection(w=0).db.coll.insert(..., safe=True)
# In this case safe=True must issue getLastError without args
# even if connection-level write concern was unacknowledged
return WriteConcern()
return WriteConcern(w=0)
@timeout
def insert(self, docs, safe=None, flags=0, **kwargs):
"""Insert a document(s) into this collection.
*Please consider using new-style* :meth:`insert_one()` *or*
:meth:`insert_many()` *methods instead.*
If document doesn't have ``"_id"`` field, :meth:`insert()` will generate
new :class:`~bson.ObjectId` and set it to ``"_id"`` field of the document.
:param docs:
Document or a list of documents to insert into a collection.
:param safe:
``True`` or ``False`` forces usage of respectively acknowledged or
unacknowledged Write Concern. If ``None``, :attr:`write_concern` is
used.
:param flags:
If zero (default), inserting will stop after the first error
encountered. When ``flags`` set to
:const:`txmongo.protocol.INSERT_CONTINUE_ON_ERROR`, MongoDB will
try to insert all documents passed even if inserting some of
them will fail (for example, because of duplicate ``_id``). Not
that :meth:`insert()` won't raise any errors when this flag is
used.
:returns:
:class:`Deferred` that fires with single ``_id`` field or a list of
``_id`` fields of inserted documents.
"""
if isinstance(docs, dict):
ids = docs.get("_id", ObjectId())
docs["_id"] = ids
docs = [docs]
elif isinstance(docs, list):
ids = []
for doc in docs:
if isinstance(doc, dict):
oid = doc.get("_id", ObjectId())
ids.append(oid)
doc["_id"] = oid
else:
raise TypeError("TxMongo: insert takes a document or a list of documents.")
else:
raise TypeError("TxMongo: insert takes a document or a list of documents.")
docs = [BSON.encode(d) for d in docs]
insert = Insert(flags=flags, collection=str(self), documents=docs)
def on_proto(proto):
check_deadline(kwargs.pop("_deadline", None))
proto.send_INSERT(insert)
write_concern = self._get_write_concern(safe, **kwargs)
if write_concern.acknowledged:
return proto.get_last_error(str(self._database), **write_concern.document)\
.addCallback(lambda _: ids)
return ids
return self._database.connection.getprotocol().addCallback(on_proto)
def _insert_one(self, document, _deadline):
if self.write_concern.acknowledged:
command = SON([("insert", self._collection_name),
("documents", [document]),
("ordered", True),
("writeConcern", self.write_concern.document)])
return self._database.command(command, _deadline=_deadline)
else:
# falling back to OP_INSERT in case of unacknowledged op
return self.insert([document], _deadline=_deadline)\
.addCallback(lambda _: None)
@timeout
def insert_one(self, document, _deadline=None):
"""insert_one(document)
Insert a single document into collection
:param document: Document to insert
:returns:
:class:`Deferred` that called back with
:class:`pymongo.results.InsertOneResult`
"""
if "_id" not in document:
document["_id"] = ObjectId()
inserted_id = document["_id"]
def on_ok(result):
response = result
if response:
_check_write_command_response(response)
return InsertOneResult(inserted_id, self.write_concern.acknowledged)
return self._insert_one(document, _deadline).addCallback(on_ok)
@staticmethod
def _generate_batch_commands(collname, command, docs_field, documents, ordered,
write_concern, max_bson, max_count):
# Takes a list of documents and generates one or many `insert` commands
# with documents list in each command is less or equal to max_bson bytes
# and contains less or equal documents than max_count
# Manually composing command in BSON form because this way we can
# perform costly documents serialization only once
msg = SON([(command, collname),
("ordered", ordered),
("writeConcern", write_concern.document)])
buf = io.BytesIO()
buf.write(BSON.encode(msg))
buf.seek(-1, io.SEEK_END) # -1 because we don't need final NUL from partial command
buf.write(docs_field) # type, name and length placeholder of 'documents' array
docs_start = buf.tell() - 4
def prepare_command():
docs_end = buf.tell() + 1 # +1 for final NUL for 'documents'
buf.write(b'\x00\x00') # final NULs for 'documents' and the command itself
total_length = buf.tell()
# writing 'documents' length
buf.seek(docs_start)
buf.write(struct.pack('<i', docs_end - docs_start))
# writing total message length
buf.seek(0)
buf.write(struct.pack('<i', total_length))
return BSON(buf.getvalue())
idx = 0
idx_offset = 0
for doc in documents:
key = str(idx).encode('ascii')
value = BSON.encode(doc)
enough_size = buf.tell() + len(key)+2 + len(value) - docs_start > max_bson
enough_count = idx >= max_count
if enough_size or enough_count:
yield idx_offset, prepare_command()
buf.seek(docs_start + 4)
buf.truncate()
idx_offset += idx
idx = 0
key = b'0'
buf.write(b'\x03' + key + b'\x00') # type and key of document
buf.write(value)
idx += 1
yield idx_offset, prepare_command()
@timeout
def insert_many(self, documents, ordered=True, _deadline=None):
"""insert_many(documents, ordered=True)
Insert an iterable of documents into collection
:param documents:
An iterable of documents to insert (``list``,
``tuple``, ...)
:param ordered:
If ``True`` (the default) documents will be inserted on the server
serially, in the order provided. If an error occurs, all remaining
inserts are aborted. If ``False``, documents will be inserted on
the server in arbitrary order, possibly in parallel, and all
document inserts will be attempted.
:returns:
:class:`Deferred` that called back with
:class:`pymongo.results.InsertManyResult`
"""
inserted_ids = []
for doc in documents:
if isinstance(doc, collections.abc.Mapping):
inserted_ids.append(doc.setdefault("_id", ObjectId()))
else:
raise TypeError("TxMongo: insert_many takes list of documents.")
bulk = _Bulk(self, ordered, bypass_document_validation=False)
bulk.ops = [(_INSERT, doc) for doc in documents]
result = InsertManyResult(inserted_ids, self.write_concern.acknowledged)
return self._execute_bulk(bulk).addCallback(lambda _: result)
@timeout
def update(self, spec, document, upsert=False, multi=False, safe=None, flags=0, **kwargs):
"""Update document(s) in this collection
*Please consider using new-style* :meth:`update_one()`, :meth:`update_many()`
and :meth:`replace_one()` *methods instead.*
:raises TypeError:
if `spec` or `document` are not instances of `dict`
or `upsert` is not an instance of `bool`.
:param spec:
query document that selects documents to be updated
:param document:
update document to be used for updating or upserting. See
`MongoDB Update docs
<https://docs.mongodb.org/manual/tutorial/modify-documents/>`_
for the format of this document and allowed operators.
:param upsert:
perform an upsert if ``True``
:param multi:
update all documents that match `spec`, rather than just the first
matching document. The default value is ``False``.
:param safe:
``True`` or ``False`` forces usage of respectively acknowledged or
unacknowledged Write Concern. If ``None``, :attr:`write_concern` is
used.
:returns:
:class:`Deferred` that is called back when request is sent to
MongoDB or confirmed by MongoDB (depending on selected Write Concern).
"""
if not isinstance(spec, dict):
raise TypeError("TxMongo: spec must be an instance of dict.")
if not isinstance(document, dict):
raise TypeError("TxMongo: document must be an instance of dict.")
if not isinstance(upsert, bool):
raise TypeError("TxMongo: upsert must be an instance of bool.")
if multi:
flags |= UPDATE_MULTI
if upsert:
flags |= UPDATE_UPSERT
spec = BSON.encode(spec)
document = BSON.encode(document)
update = Update(flags=flags, collection=str(self),
selector=spec, update=document)
def on_proto(proto):
check_deadline(kwargs.pop("_deadline", None))
proto.send_UPDATE(update)
write_concern = self._get_write_concern(safe, **kwargs)
if write_concern.acknowledged:
return proto.get_last_error(str(self._database), **write_concern.document)
return self._database.connection.getprotocol().addCallback(on_proto)
def _update(self, filter, update, upsert, multi, _deadline):
validate_is_mapping("filter", filter)
validate_boolean("upsert", upsert)
if self.write_concern.acknowledged:
updates = [SON([('q', filter), ('u', update),
("upsert", upsert), ("multi", multi)])]
command = SON([("update", self._collection_name),
("updates", updates),
("writeConcern", self.write_concern.document)])
def on_ok(raw_response):
_check_write_command_response(raw_response)
# Extract upserted_id from returned array
if raw_response.get("upserted"):
raw_response["upserted"] = raw_response["upserted"][0]["_id"]
return raw_response
return self._database.command(command, _deadline=_deadline).addCallback(on_ok)
else:
return self.update(filter, update, upsert=upsert, multi=multi,
_deadline=_deadline).addCallback(lambda _: None)
@timeout
def update_one(self, filter, update, upsert=False, _deadline=None):
"""update_one(filter, update, upsert=False)
Update a single document matching the filter.
:raises ValueError:
if `update` document is empty.
:raises ValueError:
if `update` document has any fields that don't start with `$` sign.
This method only allows *modification* of document (with `$set`,
`$inc`, etc.), not *replacing* it. For replacing use
:meth:`replace_one()` instead.
:param filter:
A query that matches the document to update.
:param update:
update document to be used for updating or upserting. See `MongoDB
Update docs <https://docs.mongodb.org/manual/tutorial/modify-documents/>`_
for allowed operators.
:param upsert:
If ``True``, perform an insert if no documents match the `filter`.
:returns:
deferred instance of :class:`pymongo.results.UpdateResult`.
"""
validate_ok_for_update(update)
def on_ok(raw_response):
return UpdateResult(raw_response, self.write_concern.acknowledged)
return self._update(filter, update, upsert, False, _deadline).addCallback(on_ok)
@timeout
def update_many(self, filter, update, upsert=False, _deadline=None):
"""update_many(filter, update, upsert=False)
Update one or more documents that match the filter.
:raises ValueError:
if `update` document is empty.
:raises ValueError:
if `update` document has fields that don't start with `$` sign.
This method only allows *modification* of document (with `$set`,
`$inc`, etc.), not *replacing* it. For replacing use
:meth:`replace_one()` instead.
:param filter:
A query that matches the documents to update.
:param update:
update document to be used for updating or upserting. See `MongoDB
Update docs <https://docs.mongodb.org/manual/tutorial/modify-documents/>`_
for allowed operators.
:param upsert:
If ``True``, perform an insert if no documents match the `filter`.
:returns:
deferred instance of :class:`pymongo.results.UpdateResult`.
"""
validate_ok_for_update(update)
def on_ok(raw_response):
return UpdateResult(raw_response, self.write_concern.acknowledged)
return self._update(filter, update, upsert, True, _deadline).addCallback(on_ok)
@timeout
def replace_one(self, filter, replacement, upsert=False, _deadline=None):
"""replace_one(filter, replacement, upsert=False)
Replace a single document matching the filter.
:raises ValueError:
if `update` document is empty
:raises ValueError:
if `update` document has fields that starts with `$` sign.
This method only allows *replacing* document completely. Use
:meth:`update_one()` for modifying existing document.
:param filter:
A query that matches the document to replace.
:param replacement:
The new document to replace with.
:param upsert:
If ``True``, perform an insert if no documents match the filter.
:returns:
deferred instance of :class:`pymongo.results.UpdateResult`.
"""
validate_ok_for_replace(replacement)
def on_ok(raw_response):
return UpdateResult(raw_response, self.write_concern.acknowledged)
return self._update(filter, replacement, upsert, False, _deadline).addCallback(on_ok)
@timeout
def save(self, doc, safe=None, **kwargs):
if not isinstance(doc, dict):
raise TypeError("TxMongo: cannot save objects of type {0}".format(type(doc)))
oid = doc.get("_id")
if oid:
return self.update({"_id": oid}, doc, safe=safe, upsert=True, **kwargs)
else:
return self.insert(doc, safe=safe, **kwargs)
@timeout
def remove(self, spec, safe=None, single=False, flags=0, **kwargs):
if isinstance(spec, ObjectId):
spec = SON(dict(_id=spec))
if not isinstance(spec, dict):
raise TypeError("TxMongo: spec must be an instance of dict, not {0}".format(type(spec)))
if single:
flags |= DELETE_SINGLE_REMOVE
spec = BSON.encode(spec)
delete = Delete(flags=flags, collection=str(self), selector=spec)
def on_proto(proto):
check_deadline(kwargs.pop("_deadline", None))
proto.send_DELETE(delete)
write_concern = self._get_write_concern(safe, **kwargs)
if write_concern.acknowledged:
return proto.get_last_error(str(self._database), **write_concern.document)
return self._database.connection.getprotocol().addCallback(on_proto)
def _delete(self, filter, multi, _deadline):
validate_is_mapping("filter", filter)
if self.write_concern.acknowledged:
deletes = [SON([('q', filter), ("limit", 0 if multi else 1)])]
command = SON([("delete", self._collection_name),
("deletes", deletes),
("writeConcern", self.write_concern.document)])
def on_ok(raw_response):
_check_write_command_response(raw_response)
return raw_response
return self._database.command(command, _deadline=_deadline).addCallback(on_ok)
else:
return self.remove(filter, single=not multi, _deadline=_deadline)\
.addCallback(lambda _: None)
@timeout
def delete_one(self, filter, _deadline=None):
"""delete_one(filter)"""
def on_ok(raw_response):
return DeleteResult(raw_response, self.write_concern.acknowledged)
return self._delete(filter, False, _deadline).addCallback(on_ok)