/
documents.py
927 lines (832 loc) · 29.6 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
from typing import (
Dict,
Optional,
List,
Type,
Union,
Tuple,
Mapping,
TypeVar,
Any,
overload,
)
from uuid import UUID, uuid4
from bson import ObjectId
from motor.motor_asyncio import AsyncIOMotorDatabase, AsyncIOMotorCollection
from pydantic import (
ValidationError,
parse_obj_as,
PrivateAttr,
validator,
)
from pydantic.main import BaseModel
from pymongo import InsertOne
from pymongo.client_session import ClientSession
from pymongo.results import (
DeleteResult,
InsertOneResult,
InsertManyResult,
)
from beanie.exceptions import (
CollectionWasNotInitialized,
ReplaceError,
DocumentNotFound,
RevisionIdWasChanged,
)
from beanie.odm.actions import EventTypes, wrap_with_actions
from beanie.odm.cache import LRUCache
from beanie.odm.bulk import BulkWriter, Operation
from beanie.odm.enums import SortDirection
from beanie.odm.fields import PydanticObjectId, ExpressionField
from beanie.odm.interfaces.update import (
UpdateMethods,
)
from beanie.odm.models import (
InspectionResult,
InspectionStatuses,
InspectionError,
)
from beanie.odm.operators.find.comparison import In
from beanie.odm.queries.aggregation import AggregationQuery
from beanie.odm.queries.find import FindOne, FindMany
from beanie.odm.queries.update import UpdateMany
from beanie.odm.settings.general import DocumentSettings
from beanie.odm.utils.dump import get_dict
from beanie.odm.utils.self_validation import validate_self_before
from beanie.odm.utils.state import saved_state_needed, save_state_after
DocType = TypeVar("DocType", bound="Document")
DocumentProjectionType = TypeVar("DocumentProjectionType", bound=BaseModel)
class Document(BaseModel, UpdateMethods):
"""
Document Mapping class.
Fields:
- `id` - MongoDB document ObjectID "_id" field.
Mapped to the PydanticObjectId class
Inherited from:
- Pydantic BaseModel
- [UpdateMethods](https://roman-right.github.io/beanie/api/interfaces/#aggregatemethods)
"""
id: Optional[PydanticObjectId] = None
# State
revision_id: Optional[UUID] = None
_previous_revision_id: Optional[UUID] = PrivateAttr(default=None)
_saved_state: Optional[Dict[str, Any]] = PrivateAttr(default=None)
# Cache
_cache: Optional[LRUCache] = None
# Settings
_document_settings: Optional[DocumentSettings] = None
# Customization
# Query builders could be replaced in the inherited classes
_find_one_query_class = FindOne
_find_many_query_class = FindMany
@validator("revision_id")
def set_revision_id(cls, revision_id):
if not cls.get_settings().model_settings.use_revision:
return None
return revision_id or uuid4()
def __init__(self, *args, **kwargs):
super(Document, self).__init__(*args, **kwargs)
self.get_motor_collection()
async def _sync(self) -> None:
"""
Update local document from the database
:return: None
"""
if self.id is None:
raise ValueError("Document has no id")
new_instance: Optional[Document] = await self.get(self.id)
if new_instance is None:
raise DocumentNotFound(
"Can not sync, document not in database anymore."
)
for key, value in dict(new_instance).items():
setattr(self, key, value)
if self.use_state_management():
self._save_state()
@wrap_with_actions(EventTypes.INSERT)
@save_state_after
@validate_self_before
async def insert(
self: DocType,
session: Optional[ClientSession] = None,
) -> DocType:
"""
Insert the document (self) to the collection
:return: Document
"""
result = await self.get_motor_collection().insert_one(
get_dict(self), session=session
)
new_id = result.inserted_id
if not isinstance(new_id, self.__fields__["id"].type_):
new_id = self.__fields__["id"].type_(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: "BulkWriter" = None,
) -> InsertOneResult:
"""
Insert one document to the collection
:param document: Document - document to insert
:param session: ClientSession - pymongo session
:param bulk_writer: "BulkWriter" - Beanie bulk writer
:return: InsertOneResult
"""
if not isinstance(document, cls):
raise TypeError(
"Inserting document must be of the original document class"
)
if bulk_writer is None:
return await cls.get_motor_collection().insert_one(
get_dict(document), session=session
)
else:
bulk_writer.add_operation(
Operation(
operation=InsertOne,
first_query=get_dict(document),
object_class=type(document),
)
)
@classmethod
async def insert_many(
cls: Type[DocType],
documents: List[DocType],
session: Optional[ClientSession] = None,
) -> InsertManyResult:
"""
Insert many documents to the collection
:param documents: List["Document"] - documents to insert
:param session: ClientSession - pymongo session
:return: InsertManyResult
"""
documents_list = [get_dict(document) for document in documents]
return await cls.get_motor_collection().insert_many(
documents_list,
session=session,
)
@classmethod
async def get(
cls: Type[DocType],
document_id: PydanticObjectId,
session: Optional[ClientSession] = None,
ignore_cache: bool = False,
) -> 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)
:return: Union["Document", None]
"""
if not isinstance(document_id, cls.__fields__["id"].type_):
document_id = parse_obj_as(cls.__fields__["id"].type_, document_id)
return await cls.find_one(
{"_id": document_id}, session=session, ignore_cache=ignore_cache
)
@overload
@classmethod
def find_one(
cls: Type[DocType],
*args: Union[Mapping[str, Any], bool],
projection_model: None = None,
session: Optional[ClientSession] = None,
ignore_cache: bool = False,
) -> FindOne[DocType]:
...
@overload
@classmethod
def find_one(
cls: Type[DocType],
*args: Union[Mapping[str, Any], bool],
projection_model: Type[DocumentProjectionType],
session: Optional[ClientSession] = None,
ignore_cache: bool = False,
) -> FindOne[DocumentProjectionType]:
...
@classmethod
def find_one(
cls: Type[DocType],
*args: Union[Mapping[str, Any], bool],
projection_model: Optional[Type[DocumentProjectionType]] = None,
session: Optional[ClientSession] = None,
ignore_cache: bool = False,
) -> Union[FindOne[DocType], FindOne[DocumentProjectionType]]:
"""
Find one document by criteria.
Returns [FindOne](https://roman-right.github.io/beanie/api/queries/#findone) query object.
When awaited this will either return a document or None if no document exists for the search criteria.
:param args: *Mapping[str, Any] - search criteria
:param projection_model: Optional[Type[BaseModel]] - projection model
:param session: Optional[ClientSession] - pymongo session instance
:param ignore_cache: bool
:return: [FindOne](https://roman-right.github.io/beanie/api/queries/#findone) - find query instance
"""
return cls._find_one_query_class(document_model=cls).find_one(
*args,
projection_model=projection_model,
session=session,
ignore_cache=ignore_cache,
)
@overload
@classmethod
def find_many(
cls: Type[DocType],
*args: Union[Mapping[str, Any], bool],
projection_model: None = None,
skip: Optional[int] = None,
limit: Optional[int] = None,
sort: Union[None, str, List[Tuple[str, SortDirection]]] = None,
session: Optional[ClientSession] = None,
ignore_cache: bool = False,
) -> FindMany[DocType]:
...
@overload
@classmethod
def find_many(
cls: Type[DocType],
*args: Union[Mapping[str, Any], bool],
projection_model: Type[DocumentProjectionType] = None,
skip: Optional[int] = None,
limit: Optional[int] = None,
sort: Union[None, str, List[Tuple[str, SortDirection]]] = None,
session: Optional[ClientSession] = None,
ignore_cache: bool = False,
) -> FindMany[DocumentProjectionType]:
...
@classmethod
def find_many(
cls: Type[DocType],
*args: Union[Mapping[str, Any], bool],
projection_model: Optional[Type[DocumentProjectionType]] = None,
skip: Optional[int] = None,
limit: Optional[int] = None,
sort: Union[None, str, List[Tuple[str, SortDirection]]] = None,
session: Optional[ClientSession] = None,
ignore_cache: bool = False,
) -> Union[FindMany[DocType], FindMany[DocumentProjectionType]]:
"""
Find many documents by criteria.
Returns [FindMany](https://roman-right.github.io/beanie/api/queries/#findmany) query object
:param args: *Mapping[str, Any] - search criteria
:param skip: Optional[int] - The number of documents to omit.
:param limit: Optional[int] - The maximum number of results to return.
:param sort: Union[None, str, List[Tuple[str, SortDirection]]] - A key
or a list of (key, direction) pairs specifying the sort order
for this query.
:param projection_model: Optional[Type[BaseModel]] - projection model
:param session: Optional[ClientSession] - pymongo session
:param ignore_cache: bool
:return: [FindMany](https://roman-right.github.io/beanie/api/queries/#findmany) - query instance
"""
return cls._find_many_query_class(document_model=cls).find_many(
*args,
sort=sort,
skip=skip,
limit=limit,
projection_model=projection_model,
session=session,
ignore_cache=ignore_cache,
)
@overload
@classmethod
def find(
cls: Type[DocType],
*args: Union[Mapping[str, Any], bool],
projection_model: None = None,
skip: Optional[int] = None,
limit: Optional[int] = None,
sort: Union[None, str, List[Tuple[str, SortDirection]]] = None,
session: Optional[ClientSession] = None,
ignore_cache: bool = False,
) -> FindMany[DocType]:
...
@overload
@classmethod
def find(
cls: Type[DocType],
*args: Union[Mapping[str, Any], bool],
projection_model: Type[DocumentProjectionType],
skip: Optional[int] = None,
limit: Optional[int] = None,
sort: Union[None, str, List[Tuple[str, SortDirection]]] = None,
session: Optional[ClientSession] = None,
ignore_cache: bool = False,
) -> FindMany[DocumentProjectionType]:
...
@classmethod
def find(
cls: Type[DocType],
*args: Union[Mapping[str, Any], bool],
projection_model: Optional[Type[DocumentProjectionType]] = None,
skip: Optional[int] = None,
limit: Optional[int] = None,
sort: Union[None, str, List[Tuple[str, SortDirection]]] = None,
session: Optional[ClientSession] = None,
ignore_cache: bool = False,
) -> Union[FindMany[DocType], FindMany[DocumentProjectionType]]:
"""
The same as find_many
"""
return cls.find_many(
*args,
skip=skip,
limit=limit,
sort=sort,
projection_model=projection_model,
session=session,
ignore_cache=ignore_cache,
)
@overload
@classmethod
def find_all(
cls: Type[DocType],
skip: Optional[int] = None,
limit: Optional[int] = None,
sort: Union[None, str, List[Tuple[str, SortDirection]]] = None,
projection_model: None = None,
session: Optional[ClientSession] = None,
ignore_cache: bool = False,
) -> FindMany[DocType]:
...
@overload
@classmethod
def find_all(
cls: Type[DocType],
skip: Optional[int] = None,
limit: Optional[int] = None,
sort: Union[None, str, List[Tuple[str, SortDirection]]] = None,
projection_model: Optional[Type[DocumentProjectionType]] = None,
session: Optional[ClientSession] = None,
ignore_cache: bool = False,
) -> FindMany[DocumentProjectionType]:
...
@classmethod
def find_all(
cls: Type[DocType],
skip: Optional[int] = None,
limit: Optional[int] = None,
sort: Union[None, str, List[Tuple[str, SortDirection]]] = None,
projection_model: Optional[Type[DocumentProjectionType]] = None,
session: Optional[ClientSession] = None,
ignore_cache: bool = False,
) -> Union[FindMany[DocType], FindMany[DocumentProjectionType]]:
"""
Get all the documents
:param skip: Optional[int] - The number of documents to omit.
:param limit: Optional[int] - The maximum number of results to return.
:param sort: Union[None, str, List[Tuple[str, SortDirection]]] - A key
or a list of (key, direction) pairs specifying the sort order
for this query.
:param projection_model: Optional[Type[BaseModel]] - projection model
:param session: Optional[ClientSession] - pymongo session
:return: [FindMany](https://roman-right.github.io/beanie/api/queries/#findmany) - query instance
"""
return cls.find_many(
{},
skip=skip,
limit=limit,
sort=sort,
projection_model=projection_model,
session=session,
ignore_cache=ignore_cache,
)
@overload
@classmethod
def all(
cls: Type[DocType],
projection_model: None = None,
skip: Optional[int] = None,
limit: Optional[int] = None,
sort: Union[None, str, List[Tuple[str, SortDirection]]] = None,
session: Optional[ClientSession] = None,
ignore_cache: bool = False,
) -> FindMany[DocType]:
...
@overload
@classmethod
def all(
cls: Type[DocType],
projection_model: Type[DocumentProjectionType],
skip: Optional[int] = None,
limit: Optional[int] = None,
sort: Union[None, str, List[Tuple[str, SortDirection]]] = None,
session: Optional[ClientSession] = None,
ignore_cache: bool = False,
) -> FindMany[DocumentProjectionType]:
...
@classmethod
def all(
cls: Type[DocType],
projection_model: Optional[Type[DocumentProjectionType]] = None,
skip: Optional[int] = None,
limit: Optional[int] = None,
sort: Union[None, str, List[Tuple[str, SortDirection]]] = None,
session: Optional[ClientSession] = None,
ignore_cache: bool = False,
) -> Union[FindMany[DocType], FindMany[DocumentProjectionType]]:
"""
the same as find_all
"""
return cls.find_all(
skip=skip,
limit=limit,
sort=sort,
projection_model=projection_model,
session=session,
ignore_cache=ignore_cache,
)
@wrap_with_actions(EventTypes.REPLACE)
@save_state_after
@validate_self_before
async def replace(
self: DocType,
ignore_revision: bool = False,
session: Optional[ClientSession] = None,
bulk_writer: Optional[BulkWriter] = 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")
use_revision_id = self.get_settings().model_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
async def save(
self: DocType, session: Optional[ClientSession] = None
) -> DocType:
"""
Update an existing model in the database or insert it if it does not yet exist.
:param session: Optional[ClientSession] - pymongo session.
:return: None
"""
try:
return await self.replace(session=session)
except (ValueError, DocumentNotFound):
return await self.insert(session=session)
@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,
) -> 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()
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"
)
await cls.find(In(cls.id, ids_list), session=session).delete()
await cls.insert_many(documents, session=session)
@save_state_after
async def update(
self,
*args,
ignore_revision: bool = False,
session: Optional[ClientSession] = None,
bulk_writer: Optional[BulkWriter] = None,
) -> None:
"""
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
:return: None
"""
use_revision_id = self.get_settings().model_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
result = await self.find_one(find_query).update(
*args, session=session, bulk_writer=bulk_writer
)
if (
use_revision_id
and not ignore_revision
and result.modified_count == 0
):
raise RevisionIdWasChanged
await self._sync()
@classmethod
def update_all(
cls,
*args: Union[dict, Mapping],
session: Optional[ClientSession] = None,
bulk_writer: Optional[BulkWriter] = None,
) -> 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
:return: UpdateMany query
"""
return cls.find_all().update_many(
*args, session=session, bulk_writer=bulk_writer
)
async def delete(
self,
session: Optional[ClientSession] = None,
bulk_writer: Optional[BulkWriter] = None,
) -> Optional[DeleteResult]:
"""
Delete the document
:param session: Optional[ClientSession] - pymongo session.
:param bulk_writer: "BulkWriter" - Beanie bulk writer
:return: Optional[DeleteResult] - pymongo DeleteResult instance.
"""
return await self.find_one({"_id": self.id}).delete(
session=session, bulk_writer=bulk_writer
)
@classmethod
async def delete_all(
cls,
session: Optional[ClientSession] = None,
bulk_writer: Optional[BulkWriter] = None,
) -> Optional[DeleteResult]:
"""
Delete all the documents
:param session: Optional[ClientSession] - pymongo session.
:param bulk_writer: "BulkWriter" - Beanie bulk writer
:return: Optional[DeleteResult] - pymongo DeleteResult instance.
"""
return await cls.find_all().delete(
session=session, bulk_writer=bulk_writer
)
@overload
@classmethod
def aggregate(
cls: Type[DocType],
aggregation_pipeline: list,
projection_model: None = None,
session: Optional[ClientSession] = None,
ignore_cache: bool = False,
) -> AggregationQuery[Dict[str, Any]]:
...
@overload
@classmethod
def aggregate(
cls: Type[DocType],
aggregation_pipeline: list,
projection_model: Type[DocumentProjectionType],
session: Optional[ClientSession] = None,
ignore_cache: bool = False,
) -> AggregationQuery[DocumentProjectionType]:
...
@classmethod
def aggregate(
cls: Type[DocType],
aggregation_pipeline: list,
projection_model: Optional[Type[DocumentProjectionType]] = None,
session: Optional[ClientSession] = None,
ignore_cache: bool = False,
) -> Union[
AggregationQuery[Dict[str, Any]],
AggregationQuery[DocumentProjectionType],
]:
"""
Aggregate over collection.
Returns [AggregationQuery](https://roman-right.github.io/beanie/api/queries/#aggregationquery) query object
:param aggregation_pipeline: list - aggregation pipeline
:param projection_model: Type[BaseModel]
:param session: Optional[ClientSession]
:param ignore_cache: bool
:return: [AggregationQuery](https://roman-right.github.io/beanie/api/queries/#aggregationquery)
"""
return cls.find_all().aggregate(
aggregation_pipeline=aggregation_pipeline,
projection_model=projection_model,
session=session,
ignore_cache=ignore_cache,
)
@classmethod
async def count(cls) -> int:
"""
Number of documents in the collections
The same as find_all().count()
:return: int
"""
return await cls.find_all().count()
# State management
@classmethod
def use_state_management(cls) -> bool:
"""
Is state management turned on
:return: bool
"""
return cls.get_settings().model_settings.use_state_management
def _save_state(self) -> None:
"""
Save current document state. Internal method
:return: None
"""
if self.use_state_management():
self._saved_state = get_dict(self)
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
@classmethod
def _parse_obj_saving_state(cls: Type[DocType], obj: Any) -> DocType:
"""
Parse object and save state then. Internal method.
:param obj: Any
:return: DocType
"""
result: DocType = cls.parse_obj(obj)
result._save_state()
return result
@property # type: ignore
@saved_state_needed
def is_changed(self) -> bool:
if self._saved_state == get_dict(self):
return False
return True
@saved_state_needed
def get_changes(self) -> Dict[str, Any]:
# TODO search deeply
changes = {}
if self.is_changed:
current_state = get_dict(self)
for k, v in self._saved_state.items(): # type: ignore
if v != current_state[k]:
changes[k] = current_state[k]
return changes
@saved_state_needed
def rollback(self) -> None:
if self.is_changed:
for key, value in self._saved_state.items(): # type: ignore
if key == "_id":
setattr(self, "id", value)
else:
setattr(self, key, value)
# Initialization
@classmethod
def init_cache(cls) -> None:
"""
Init model's cache
:return: None
"""
if cls.get_settings().model_settings.use_cache:
cls._cache = LRUCache(
capacity=cls.get_settings().model_settings.cache_capacity,
expiration_time=cls.get_settings().model_settings.cache_expiration_time,
)
@classmethod
def init_fields(cls) -> None:
"""
Init class fields
:return: None
"""
for k, v in cls.__fields__.items():
path = v.alias or v.name
setattr(cls, k, ExpressionField(path))
@classmethod
async def init_settings(
cls, database: AsyncIOMotorDatabase, allow_index_dropping: bool
) -> None:
"""
Init document settings (collection and models)
:param database: AsyncIOMotorDatabase - motor database
:param allow_index_dropping: bool
:return: None
"""
# TODO looks ugly a little. Too many parameters transfers.
cls._document_settings = await DocumentSettings.init(
database=database,
document_model=cls,
allow_index_dropping=allow_index_dropping,
)
@classmethod
async def init_model(
cls, database: AsyncIOMotorDatabase, allow_index_dropping: bool
) -> None:
"""
Init wrapper
:param database: AsyncIOMotorDatabase
:param allow_index_dropping: bool
:return: None
"""
await cls.init_settings(
database=database, allow_index_dropping=allow_index_dropping
)
cls.init_fields()
cls.init_cache()
# Other
@classmethod
def get_settings(cls) -> DocumentSettings:
"""
Get document settings, which was created on
the initialization step
:return: DocumentSettings class
"""
if cls._document_settings is None:
raise CollectionWasNotInitialized
return cls._document_settings
@classmethod
def get_motor_collection(cls) -> AsyncIOMotorCollection:
"""
Get Motor Collection to access low level control
:return: AsyncIOMotorCollection
"""
collection_meta = cls.get_settings().collection_settings
return collection_meta.motor_collection
@classmethod
async def inspect_collection(
cls, session: Optional[ClientSession] = None
) -> InspectionResult:
"""
Check, if documents, stored in the MongoDB collection
are compatible with the Document schema
:return: InspectionResult
"""
inspection_result = InspectionResult()
async for json_document in cls.get_motor_collection().find(
{}, session=session
):
try:
cls.parse_obj(json_document)
except ValidationError as e:
if inspection_result.status == InspectionStatuses.OK:
inspection_result.status = InspectionStatuses.FAIL
inspection_result.errors.append(
InspectionError(
document_id=json_document["_id"], error=str(e)
)
)
return inspection_result
@wrap_with_actions(event_type=EventTypes.VALIDATE_ON_SAVE)
async def validate_self(self):
# TODO it can be sync, but needs some actions controller improvements
if self.get_settings().model_settings.validate_on_save:
self.parse_obj(self)
class Config:
json_encoders = {
ObjectId: lambda v: str(v),
}
allow_population_by_field_name = True
fields = {"id": "_id"}