/
documents.py
1123 lines (1007 loc) · 37.3 KB
/
documents.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
import asyncio
import warnings
from typing import (
Any,
ClassVar,
Dict,
Iterable,
List,
Mapping,
Optional,
Type,
TypeVar,
Union,
)
from uuid import UUID, uuid4
from bson import DBRef, ObjectId
from lazy_model import LazyModel
from pydantic import (
ConfigDict,
Field,
PrivateAttr,
ValidationError,
)
from pydantic.class_validators import root_validator
from pydantic.main import BaseModel
from pymongo import InsertOne
from pymongo.client_session import ClientSession
from pymongo.errors import DuplicateKeyError
from pymongo.results import (
DeleteResult,
InsertManyResult,
)
from beanie.exceptions import (
CollectionWasNotInitialized,
DocumentNotFound,
DocumentWasNotSaved,
NotSupported,
ReplaceError,
RevisionIdWasChanged,
)
from beanie.odm.actions import (
ActionDirections,
EventTypes,
wrap_with_actions,
)
from beanie.odm.bulk import BulkWriter, Operation
from beanie.odm.cache import LRUCache
from beanie.odm.fields import (
BackLink,
DeleteRules,
ExpressionField,
Link,
LinkInfo,
LinkTypes,
PydanticObjectId,
WriteRules,
)
from beanie.odm.interfaces.aggregate import AggregateInterface
from beanie.odm.interfaces.detector import ModelType
from beanie.odm.interfaces.find import FindInterface
from beanie.odm.interfaces.getters import OtherGettersInterface
from beanie.odm.interfaces.inheritance import InheritanceInterface
from beanie.odm.interfaces.setters import SettersInterface
from beanie.odm.models import (
InspectionError,
InspectionResult,
InspectionStatuses,
)
from beanie.odm.operators.find.comparison import In
from beanie.odm.operators.update.general import (
CurrentDate,
Inc,
SetRevisionId,
Unset,
)
from beanie.odm.operators.update.general import (
Set as SetOperator,
)
from beanie.odm.queries.update import UpdateMany, UpdateResponse
from beanie.odm.settings.document import DocumentSettings
from beanie.odm.utils.dump import get_dict, get_top_level_nones
from beanie.odm.utils.parsing import merge_models
from beanie.odm.utils.pydantic import (
IS_PYDANTIC_V2,
get_extra_field_info,
get_field_type,
get_model_dump,
get_model_fields,
parse_model,
parse_object_as,
)
from beanie.odm.utils.self_validation import validate_self_before
from beanie.odm.utils.state import (
previous_saved_state_needed,
save_state_after,
saved_state_needed,
swap_revision_after,
)
from beanie.odm.utils.typing import extract_id_class
if IS_PYDANTIC_V2:
from pydantic import model_validator
DocType = TypeVar("DocType", bound="Document")
DocumentProjectionType = TypeVar("DocumentProjectionType", bound=BaseModel)
def json_schema_extra(schema: Dict[str, Any], model: Type["Document"]) -> None:
# remove excluded fields from the json schema
properties = schema.get("properties")
if not properties:
return
for k, field in get_model_fields(model).items():
k = field.alias or k
if k not in properties:
continue
field_info = field if IS_PYDANTIC_V2 else field.field_info
if field_info.exclude:
del properties[k]
def document_alias_generator(s: str) -> str:
if s == "id":
return "_id"
return s
class Document(
LazyModel,
SettersInterface,
InheritanceInterface,
FindInterface,
AggregateInterface,
OtherGettersInterface,
):
"""
Document Mapping class.
Fields:
- `id` - MongoDB document ObjectID "_id" field.
Mapped to the PydanticObjectId class
"""
if IS_PYDANTIC_V2:
model_config = ConfigDict(
json_schema_extra=json_schema_extra,
populate_by_name=True,
alias_generator=document_alias_generator,
)
else:
class Config:
json_encoders = {ObjectId: str}
allow_population_by_field_name = True
fields = {"id": "_id"}
schema_extra = staticmethod(json_schema_extra)
id: Optional[PydanticObjectId] = Field(
default=None, description="MongoDB document ObjectID"
)
# State
revision_id: Optional[UUID] = Field(default=None, exclude=True)
_previous_revision_id: Optional[UUID] = PrivateAttr(default=None)
_saved_state: Optional[Dict[str, Any]] = PrivateAttr(default=None)
_previous_saved_state: Optional[Dict[str, Any]] = PrivateAttr(default=None)
# Relations
_link_fields: ClassVar[Optional[Dict[str, LinkInfo]]] = None
# Cache
_cache: ClassVar[Optional[LRUCache]] = None
# Settings
_document_settings: ClassVar[Optional[DocumentSettings]] = None
# Database
_database_major_version: ClassVar[int] = 4
def _swap_revision(self):
if self.get_settings().use_revision:
self._previous_revision_id = self.revision_id
self.revision_id = uuid4()
def __init__(self, *args, **kwargs):
super(Document, self).__init__(*args, **kwargs)
self.get_motor_collection()
@classmethod
def _fill_back_refs(cls, values):
if cls._link_fields:
for field_name, link_info in cls._link_fields.items():
if (
link_info.link_type
in [LinkTypes.BACK_DIRECT, LinkTypes.OPTIONAL_BACK_DIRECT]
and field_name not in values
):
values[field_name] = BackLink[link_info.document_class](
link_info.document_class
)
if (
link_info.link_type
in [LinkTypes.BACK_LIST, LinkTypes.OPTIONAL_BACK_LIST]
and field_name not in values
):
values[field_name] = [
BackLink[link_info.document_class](
link_info.document_class
)
]
return values
if IS_PYDANTIC_V2:
@model_validator(mode="before")
def fill_back_refs(cls, values):
return cls._fill_back_refs(values)
else:
@root_validator(pre=True)
def fill_back_refs(cls, values):
return cls._fill_back_refs(values)
@classmethod
async def get(
cls: Type["DocType"],
document_id: Any,
session: Optional[ClientSession] = None,
ignore_cache: bool = False,
fetch_links: bool = False,
with_children: bool = False,
**pymongo_kwargs,
) -> Optional["DocType"]:
"""
Get document by id, returns None if document does not exist
:param document_id: PydanticObjectId - document id
:param session: Optional[ClientSession] - pymongo session
:param ignore_cache: bool - ignore cache (if it is turned on)
:param **pymongo_kwargs: pymongo native parameters for find operation
:return: Union["Document", None]
"""
if not isinstance(
document_id,
extract_id_class(get_field_type(get_model_fields(cls)["id"])),
):
document_id = parse_object_as(
get_field_type(get_model_fields(cls)["id"]), document_id
)
return await cls.find_one(
{"_id": document_id},
session=session,
ignore_cache=ignore_cache,
fetch_links=fetch_links,
with_children=with_children,
**pymongo_kwargs,
)
@wrap_with_actions(EventTypes.INSERT)
@save_state_after
@swap_revision_after
@validate_self_before
async def insert(
self: DocType,
*,
link_rule: WriteRules = WriteRules.DO_NOTHING,
session: Optional[ClientSession] = None,
skip_actions: Optional[List[Union[ActionDirections, str]]] = None,
) -> DocType:
"""
Insert the document (self) to the collection
:return: Document
"""
if self.get_settings().use_revision:
self.revision_id = uuid4()
if link_rule == WriteRules.WRITE:
link_fields = self.get_link_fields()
if link_fields is not None:
for field_info in link_fields.values():
value = getattr(self, field_info.field_name)
if field_info.link_type in [
LinkTypes.DIRECT,
LinkTypes.OPTIONAL_DIRECT,
]:
if isinstance(value, Document):
await value.save(link_rule=WriteRules.WRITE)
if field_info.link_type in [
LinkTypes.LIST,
LinkTypes.OPTIONAL_LIST,
]:
if isinstance(value, List):
for obj in value:
if isinstance(obj, Document):
await obj.save(link_rule=WriteRules.WRITE)
result = await self.get_motor_collection().insert_one(
get_dict(
self, to_db=True, keep_nulls=self.get_settings().keep_nulls
),
session=session,
)
new_id = result.inserted_id
if not isinstance(
new_id,
extract_id_class(get_field_type(get_model_fields(self)["id"])),
):
new_id = parse_object_as(
get_field_type(get_model_fields(self)["id"]), new_id
)
self.id = new_id
return self
async def create(
self: DocType,
session: Optional[ClientSession] = None,
) -> DocType:
"""
The same as self.insert()
:return: Document
"""
return await self.insert(session=session)
@classmethod
async def insert_one(
cls: Type[DocType],
document: DocType,
session: Optional[ClientSession] = None,
bulk_writer: Optional["BulkWriter"] = None,
link_rule: WriteRules = WriteRules.DO_NOTHING,
) -> Optional[DocType]:
"""
Insert one document to the collection
:param document: Document - document to insert
:param session: ClientSession - pymongo session
:param bulk_writer: "BulkWriter" - Beanie bulk writer
:param link_rule: InsertRules - hot to manage link fields
:return: DocType
"""
if not isinstance(document, cls):
raise TypeError(
"Inserting document must be of the original document class"
)
if bulk_writer is None:
return await document.insert(link_rule=link_rule, session=session)
else:
if link_rule == WriteRules.WRITE:
raise NotSupported(
"Cascade insert with bulk writing not supported"
)
bulk_writer.add_operation(
Operation(
operation=InsertOne,
first_query=get_dict(
document,
to_db=True,
keep_nulls=document.get_settings().keep_nulls,
),
object_class=type(document),
)
)
return None
@classmethod
async def insert_many(
cls: Type[DocType],
documents: Iterable[DocType],
session: Optional[ClientSession] = None,
link_rule: WriteRules = WriteRules.DO_NOTHING,
**pymongo_kwargs,
) -> InsertManyResult:
"""
Insert many documents to the collection
:param documents: List["Document"] - documents to insert
:param session: ClientSession - pymongo session
:param link_rule: InsertRules - how to manage link fields
:return: InsertManyResult
"""
if link_rule == WriteRules.WRITE:
raise NotSupported(
"Cascade insert not supported for insert many method"
)
documents_list = [
get_dict(
document,
to_db=True,
keep_nulls=document.get_settings().keep_nulls,
)
for document in documents
]
return await cls.get_motor_collection().insert_many(
documents_list, session=session, **pymongo_kwargs
)
@wrap_with_actions(EventTypes.REPLACE)
@save_state_after
@swap_revision_after
@validate_self_before
async def replace(
self: DocType,
ignore_revision: bool = False,
session: Optional[ClientSession] = None,
bulk_writer: Optional[BulkWriter] = None,
link_rule: WriteRules = WriteRules.DO_NOTHING,
skip_actions: Optional[List[Union[ActionDirections, str]]] = None,
) -> DocType:
"""
Fully update the document in the database
:param session: Optional[ClientSession] - pymongo session.
:param ignore_revision: bool - do force replace.
Used when revision based protection is turned on.
:param bulk_writer: "BulkWriter" - Beanie bulk writer
:return: self
"""
if self.id is None:
raise ValueError("Document must have an id")
if bulk_writer is not None and link_rule != WriteRules.DO_NOTHING:
raise NotSupported
if link_rule == WriteRules.WRITE:
link_fields = self.get_link_fields()
if link_fields is not None:
for field_info in link_fields.values():
value = getattr(self, field_info.field_name)
if field_info.link_type in [
LinkTypes.DIRECT,
LinkTypes.OPTIONAL_DIRECT,
LinkTypes.BACK_DIRECT,
LinkTypes.OPTIONAL_BACK_DIRECT,
]:
if isinstance(value, Document):
await value.replace(
link_rule=link_rule,
bulk_writer=bulk_writer,
ignore_revision=ignore_revision,
session=session,
)
if field_info.link_type in [
LinkTypes.LIST,
LinkTypes.OPTIONAL_LIST,
LinkTypes.BACK_LIST,
LinkTypes.OPTIONAL_BACK_LIST,
]:
if isinstance(value, List):
for obj in value:
if isinstance(obj, Document):
await obj.replace(
link_rule=link_rule,
bulk_writer=bulk_writer,
ignore_revision=ignore_revision,
session=session,
)
use_revision_id = self.get_settings().use_revision
find_query: Dict[str, Any] = {"_id": self.id}
if use_revision_id and not ignore_revision:
find_query["revision_id"] = self._previous_revision_id
try:
await self.find_one(find_query).replace_one(
self,
session=session,
bulk_writer=bulk_writer,
)
except DocumentNotFound:
if use_revision_id and not ignore_revision:
raise RevisionIdWasChanged
else:
raise DocumentNotFound
return self
@wrap_with_actions(EventTypes.SAVE)
@save_state_after
@validate_self_before
async def save(
self: DocType,
session: Optional[ClientSession] = None,
link_rule: WriteRules = WriteRules.DO_NOTHING,
ignore_revision: bool = False,
**kwargs,
) -> None:
"""
Update an existing model in the database or
insert it if it does not yet exist.
:param session: Optional[ClientSession] - pymongo session.
:param link_rule: WriteRules - rules how to deal with links on writing
:param ignore_revision: bool - do force save.
:return: None
"""
if link_rule == WriteRules.WRITE:
link_fields = self.get_link_fields()
if link_fields is not None:
for field_info in link_fields.values():
value = getattr(self, field_info.field_name)
if field_info.link_type in [
LinkTypes.DIRECT,
LinkTypes.OPTIONAL_DIRECT,
LinkTypes.BACK_DIRECT,
LinkTypes.OPTIONAL_BACK_DIRECT,
]:
if isinstance(value, Document):
await value.save(
link_rule=link_rule, session=session
)
if field_info.link_type in [
LinkTypes.LIST,
LinkTypes.OPTIONAL_LIST,
LinkTypes.BACK_LIST,
LinkTypes.OPTIONAL_BACK_LIST,
]:
if isinstance(value, List):
for obj in value:
if isinstance(obj, Document):
await obj.save(
link_rule=link_rule, session=session
)
if self.get_settings().keep_nulls is False:
return await self.update(
SetOperator(
get_dict(
self,
to_db=True,
keep_nulls=self.get_settings().keep_nulls,
)
),
Unset(get_top_level_nones(self)),
session=session,
ignore_revision=ignore_revision,
upsert=True,
**kwargs,
)
else:
return await self.update(
SetOperator(
get_dict(
self,
to_db=True,
keep_nulls=self.get_settings().keep_nulls,
)
),
session=session,
ignore_revision=ignore_revision,
upsert=True,
**kwargs,
)
@saved_state_needed
@wrap_with_actions(EventTypes.SAVE_CHANGES)
@validate_self_before
async def save_changes(
self,
ignore_revision: bool = False,
session: Optional[ClientSession] = None,
bulk_writer: Optional[BulkWriter] = None,
skip_actions: Optional[List[Union[ActionDirections, str]]] = None,
) -> None:
"""
Save changes.
State management usage must be turned on
:param ignore_revision: bool - ignore revision id, if revision is turned on
:param bulk_writer: "BulkWriter" - Beanie bulk writer
:return: None
"""
if not self.is_changed:
return None
changes = self.get_changes()
if self.get_settings().keep_nulls is False:
return await self.update(
SetOperator(changes),
Unset(get_top_level_nones(self)),
ignore_revision=ignore_revision,
session=session,
bulk_writer=bulk_writer,
)
else:
return await self.set(
changes, # type: ignore #TODO fix typing
ignore_revision=ignore_revision,
session=session,
bulk_writer=bulk_writer,
)
@classmethod
async def replace_many(
cls: Type[DocType],
documents: List[DocType],
session: Optional[ClientSession] = None,
) -> None:
"""
Replace list of documents
:param documents: List["Document"]
:param session: Optional[ClientSession] - pymongo session.
:return: None
"""
ids_list = [document.id for document in documents]
if await cls.find(In(cls.id, ids_list)).count() != len(ids_list):
raise ReplaceError(
"Some of the documents are not exist in the collection"
)
async with BulkWriter(session=session) as bulk_writer:
for document in documents:
await document.replace(
bulk_writer=bulk_writer, session=session
)
@wrap_with_actions(EventTypes.UPDATE)
@save_state_after
async def update(
self,
*args,
ignore_revision: bool = False,
session: Optional[ClientSession] = None,
bulk_writer: Optional[BulkWriter] = None,
skip_actions: Optional[List[Union[ActionDirections, str]]] = None,
skip_sync: Optional[bool] = None,
**pymongo_kwargs,
) -> DocType:
"""
Partially update the document in the database
:param args: *Union[dict, Mapping] - the modifications to apply.
:param session: ClientSession - pymongo session.
:param ignore_revision: bool - force update. Will update even if revision id is not the same, as stored
:param bulk_writer: "BulkWriter" - Beanie bulk writer
:param pymongo_kwargs: pymongo native parameters for update operation
:return: None
"""
arguments = list(args)
if skip_sync is not None:
raise DeprecationWarning(
"skip_sync parameter is not supported. The document get synced always using atomic operation."
)
use_revision_id = self.get_settings().use_revision
if self.id is not None:
find_query: Dict[str, Any] = {"_id": self.id}
else:
find_query = {"_id": PydanticObjectId()}
if use_revision_id and not ignore_revision:
find_query["revision_id"] = self._previous_revision_id
if use_revision_id:
arguments.append(SetRevisionId(self.revision_id))
try:
result = await self.find_one(find_query).update(
*arguments,
session=session,
response_type=UpdateResponse.NEW_DOCUMENT,
bulk_writer=bulk_writer,
**pymongo_kwargs,
)
except DuplicateKeyError:
raise RevisionIdWasChanged
if bulk_writer is None:
if use_revision_id and not ignore_revision and result is None:
raise RevisionIdWasChanged
merge_models(self, result)
return self
@classmethod
def update_all(
cls,
*args: Union[dict, Mapping],
session: Optional[ClientSession] = None,
bulk_writer: Optional[BulkWriter] = None,
**pymongo_kwargs,
) -> UpdateMany:
"""
Partially update all the documents
:param args: *Union[dict, Mapping] - the modifications to apply.
:param session: ClientSession - pymongo session.
:param bulk_writer: "BulkWriter" - Beanie bulk writer
:param **pymongo_kwargs: pymongo native parameters for find operation
:return: UpdateMany query
"""
return cls.find_all().update_many(
*args, session=session, bulk_writer=bulk_writer, **pymongo_kwargs
)
def set(
self,
expression: Dict[Union[ExpressionField, str], Any],
session: Optional[ClientSession] = None,
bulk_writer: Optional[BulkWriter] = None,
skip_sync: Optional[bool] = None,
**kwargs,
):
"""
Set values
Example:
```python
class Sample(Document):
one: int
await Document.find(Sample.one == 1).set({Sample.one: 100})
```
Uses [Set operator](operators/update.md#set)
:param expression: Dict[Union[ExpressionField, str], Any] - keys and
values to set
:param session: Optional[ClientSession] - pymongo session
:param bulk_writer: Optional[BulkWriter] - bulk writer
:param skip_sync: bool - skip doc syncing. Available for the direct instances only
:return: self
"""
return self.update(
SetOperator(expression),
session=session,
bulk_writer=bulk_writer,
skip_sync=skip_sync,
**kwargs,
)
def current_date(
self,
expression: Dict[Union[ExpressionField, str], Any],
session: Optional[ClientSession] = None,
bulk_writer: Optional[BulkWriter] = None,
skip_sync: Optional[bool] = None,
**kwargs,
):
"""
Set current date
Uses [CurrentDate operator](operators/update.md#currentdate)
:param expression: Dict[Union[ExpressionField, str], Any]
:param session: Optional[ClientSession] - pymongo session
:param bulk_writer: Optional[BulkWriter] - bulk writer
:param skip_sync: bool - skip doc syncing. Available for the direct instances only
:return: self
"""
return self.update(
CurrentDate(expression),
session=session,
bulk_writer=bulk_writer,
skip_sync=skip_sync,
**kwargs,
)
def inc(
self,
expression: Dict[Union[ExpressionField, str], Any],
session: Optional[ClientSession] = None,
bulk_writer: Optional[BulkWriter] = None,
skip_sync: Optional[bool] = None,
**kwargs,
):
"""
Increment
Example:
```python
class Sample(Document):
one: int
await Document.find(Sample.one == 1).inc({Sample.one: 100})
```
Uses [Inc operator](operators/update.md#inc)
:param expression: Dict[Union[ExpressionField, str], Any]
:param session: Optional[ClientSession] - pymongo session
:param bulk_writer: Optional[BulkWriter] - bulk writer
:param skip_sync: bool - skip doc syncing. Available for the direct instances only
:return: self
"""
return self.update(
Inc(expression),
session=session,
bulk_writer=bulk_writer,
skip_sync=skip_sync,
**kwargs,
)
@wrap_with_actions(EventTypes.DELETE)
async def delete(
self,
session: Optional[ClientSession] = None,
bulk_writer: Optional[BulkWriter] = None,
link_rule: DeleteRules = DeleteRules.DO_NOTHING,
skip_actions: Optional[List[Union[ActionDirections, str]]] = None,
**pymongo_kwargs,
) -> Optional[DeleteResult]:
"""
Delete the document
:param session: Optional[ClientSession] - pymongo session.
:param bulk_writer: "BulkWriter" - Beanie bulk writer
:param link_rule: DeleteRules - rules for link fields
:param **pymongo_kwargs: pymongo native parameters for delete operation
:return: Optional[DeleteResult] - pymongo DeleteResult instance.
"""
if link_rule == DeleteRules.DELETE_LINKS:
link_fields = self.get_link_fields()
if link_fields is not None:
for field_info in link_fields.values():
value = getattr(self, field_info.field_name)
if field_info.link_type in [
LinkTypes.DIRECT,
LinkTypes.OPTIONAL_DIRECT,
LinkTypes.BACK_DIRECT,
LinkTypes.OPTIONAL_BACK_DIRECT,
]:
if isinstance(value, Document):
await value.delete(
link_rule=DeleteRules.DELETE_LINKS,
**pymongo_kwargs,
)
if field_info.link_type in [
LinkTypes.LIST,
LinkTypes.OPTIONAL_LIST,
LinkTypes.BACK_LIST,
LinkTypes.OPTIONAL_BACK_LIST,
]:
if isinstance(value, List):
for obj in value:
if isinstance(obj, Document):
await obj.delete(
link_rule=DeleteRules.DELETE_LINKS,
**pymongo_kwargs,
)
return await self.find_one({"_id": self.id}).delete(
session=session, bulk_writer=bulk_writer, **pymongo_kwargs
)
@classmethod
async def delete_all(
cls,
session: Optional[ClientSession] = None,
bulk_writer: Optional[BulkWriter] = None,
**pymongo_kwargs,
) -> Optional[DeleteResult]:
"""
Delete all the documents
:param session: Optional[ClientSession] - pymongo session.
:param bulk_writer: "BulkWriter" - Beanie bulk writer
:param **pymongo_kwargs: pymongo native parameters for delete operation
:return: Optional[DeleteResult] - pymongo DeleteResult instance.
"""
return await cls.find_all().delete(
session=session, bulk_writer=bulk_writer, **pymongo_kwargs
)
# State management
@classmethod
def use_state_management(cls) -> bool:
"""
Is state management turned on
:return: bool
"""
return cls.get_settings().use_state_management
@classmethod
def state_management_save_previous(cls) -> bool:
"""
Should we save the previous state after a commit to database
:return: bool
"""
return cls.get_settings().state_management_save_previous
@classmethod
def state_management_replace_objects(cls) -> bool:
"""
Should objects be replaced when using state management
:return: bool
"""
return cls.get_settings().state_management_replace_objects
def _save_state(self) -> None:
"""
Save current document state. Internal method
:return: None
"""
if self.use_state_management() and self.id is not None:
if self.state_management_save_previous():
self._previous_saved_state = self._saved_state
self._saved_state = get_dict(
self, to_db=True, keep_nulls=self.get_settings().keep_nulls
)
def get_saved_state(self) -> Optional[Dict[str, Any]]:
"""
Saved state getter. It is protected property.
:return: Optional[Dict[str, Any]] - saved state
"""
return self._saved_state
def get_previous_saved_state(self) -> Optional[Dict[str, Any]]:
"""
Previous state getter. It is a protected property.
:return: Optional[Dict[str, Any]] - previous state
"""
return self._previous_saved_state
@property # type: ignore
@saved_state_needed
def is_changed(self) -> bool:
if self._saved_state == get_dict(
self, to_db=True, keep_nulls=self.get_settings().keep_nulls
):
return False
return True
@property # type: ignore
@saved_state_needed
@previous_saved_state_needed
def has_changed(self) -> bool:
if (
self._previous_saved_state is None
or self._previous_saved_state == self._saved_state
):
return False
return True
def _collect_updates(
self, old_dict: Dict[str, Any], new_dict: Dict[str, Any]
) -> Dict[str, Any]:
"""
Compares old_dict with new_dict and returns field paths that have been updated
Args:
old_dict: dict1
new_dict: dict2
Returns: dictionary with updates
"""
updates = {}
if old_dict.keys() - new_dict.keys():
updates = new_dict
else:
for field_name, field_value in new_dict.items():
if field_value != old_dict.get(field_name):
if not self.state_management_replace_objects() and (
isinstance(field_value, dict)
and isinstance(old_dict.get(field_name), dict)
):
if old_dict.get(field_name) is None:
updates[field_name] = field_value
elif isinstance(field_value, dict) and isinstance(
old_dict.get(field_name), dict
):
field_data = self._collect_updates(
old_dict.get(field_name), # type: ignore
field_value,
)
for k, v in field_data.items():
updates[f"{field_name}.{k}"] = v
else:
updates[field_name] = field_value
return updates
@saved_state_needed
def get_changes(self) -> Dict[str, Any]:
return self._collect_updates(
self._saved_state, get_dict(self, to_db=True, keep_nulls=self.get_settings().keep_nulls) # type: ignore
)
@saved_state_needed
@previous_saved_state_needed
def get_previous_changes(self) -> Dict[str, Any]:
if self._previous_saved_state is None:
return {}
return self._collect_updates(
self._previous_saved_state, self._saved_state # type: ignore
)
@saved_state_needed
def rollback(self) -> None: