/
models.py
1032 lines (741 loc) · 21.3 KB
/
models.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 datetime
from enum import Enum
from ipaddress import (
IPv4Address,
IPv4Interface,
IPv4Network,
IPv6Address,
IPv6Interface,
IPv6Network,
)
from pathlib import Path
from typing import (
Any,
Callable,
ClassVar,
Dict,
List,
Optional,
Set,
Tuple,
Union,
)
from uuid import UUID, uuid4
import pymongo
from pydantic import (
BaseModel,
ConfigDict,
Field,
PrivateAttr,
SecretBytes,
SecretStr,
)
from pydantic.fields import FieldInfo
from pydantic_core import core_schema
from pymongo import IndexModel
from beanie import (
DecimalAnnotation,
Document,
Indexed,
Insert,
Replace,
Save,
Update,
ValidateOnSave,
)
from beanie.odm.actions import Delete, after_event, before_event
from beanie.odm.custom_types.bson.binary import BsonBinary
from beanie.odm.fields import BackLink, Link, PydanticObjectId
from beanie.odm.settings.timeseries import TimeSeriesConfig
from beanie.odm.union_doc import UnionDoc
from beanie.odm.utils.pydantic import IS_PYDANTIC_V2
if IS_PYDANTIC_V2:
from pydantic import RootModel, validate_call
class Color:
def __init__(self, value):
self.value = value
def as_rgb(self):
return self.value
def as_hex(self):
return self.value
@classmethod
def __get_validators__(cls):
yield cls.validate
@classmethod
def validate(cls, value):
if isinstance(value, Color):
return value
if isinstance(value, dict):
return Color(value["value"])
return Color(value)
@classmethod
def __get_pydantic_core_schema__(
cls,
_source_type: Any,
_handler: Callable[[Any], core_schema.CoreSchema], # type: ignore
) -> core_schema.CoreSchema: # type: ignore
def validate(value, _: FieldInfo) -> Color:
if isinstance(value, Color):
return value
if isinstance(value, dict):
return Color(value["value"])
return Color(value)
python_schema = core_schema.general_plain_validator_function(validate)
return core_schema.json_or_python_schema(
json_schema=core_schema.str_schema(),
python_schema=python_schema,
)
class Extra(str, Enum):
allow = "allow"
class Option2(BaseModel):
f: float
class Option1(BaseModel):
s: str
class Nested(BaseModel):
integer: int
option_1: Option1
union: Union[Option1, Option2]
optional: Optional[Option2] = None
class GeoObject(BaseModel):
type: str = "Point"
coordinates: Tuple[float, float]
class Sample(Document):
timestamp: datetime.datetime
increment: Indexed(int)
integer: Indexed(int)
float_num: float
string: str
nested: Nested
optional: Optional[Option2] = None
union: Union[Option1, Option2]
geo: GeoObject
const: str = "TEST"
class SubDocument(BaseModel):
test_str: str
test_int: int = 42
class DocumentTestModel(Document):
test_int: int
test_doc: SubDocument
test_str: str
test_list: List[SubDocument] = Field(exclude=True)
class Settings:
use_cache = True
cache_expiration_time = datetime.timedelta(seconds=10)
cache_capacity = 5
use_state_management = True
class DocumentTestModelWithLink(Document):
test_link: Link[DocumentTestModel]
class Settings:
use_cache = True
cache_expiration_time = datetime.timedelta(seconds=10)
cache_capacity = 5
use_state_management = True
class DocumentTestModelWithCustomCollectionName(Document):
test_int: int
test_list: List[SubDocument]
test_str: str
class Settings:
name = "custom"
class_id = "different_class_id"
class DocumentTestModelWithSimpleIndex(Document):
test_int: Indexed(int)
test_list: List[SubDocument]
test_str: Indexed(str, index_type=pymongo.TEXT)
class DocumentTestModelWithIndexFlags(Document):
test_int: Indexed(int, sparse=True)
test_str: Indexed(str, index_type=pymongo.DESCENDING, unique=True)
class DocumentTestModelWithIndexFlagsAliases(Document):
test_int: Indexed(int, sparse=True) = Field(alias="testInt")
test_str: Indexed(str, index_type=pymongo.DESCENDING, unique=True) = Field(
alias="testStr"
)
class DocumentTestModelWithComplexIndex(Document):
test_int: int
test_list: List[SubDocument]
test_str: str
class Settings:
name = "docs_with_index"
indexes = [
"test_int",
[
("test_int", pymongo.ASCENDING),
("test_str", pymongo.DESCENDING),
],
IndexModel(
[("test_str", pymongo.DESCENDING)],
name="test_string_index_DESCENDING",
),
]
class DocumentTestModelWithDroppedIndex(Document):
test_int: int
test_list: List[SubDocument]
test_str: str
class Settings:
name = "docs_with_index"
indexes = [
"test_int",
]
class DocumentTestModelStringImport(Document):
test_int: int
class DocumentTestModelFailInspection(Document):
test_int_2: int
class Settings:
name = "DocumentTestModel"
class DocumentWithDeprecatedHiddenField(Document):
if IS_PYDANTIC_V2:
test_hidden: List[str] = Field(json_schema_extra={"hidden": True})
else:
test_hidden: List[str] = Field(hidden=True)
class DocumentWithCustomIdUUID(Document):
id: UUID = Field(default_factory=uuid4)
name: str
class DocumentWithCustomIdInt(Document):
id: int
name: str
class DocumentWithCustomFiledsTypes(Document):
color: Color
decimal: DecimalAnnotation
secret_bytes: SecretBytes
secret_string: SecretStr
ipv4address: IPv4Address
ipv4interface: IPv4Interface
ipv4network: IPv4Network
ipv6address: IPv6Address
ipv6interface: IPv6Interface
ipv6network: IPv6Network
timedelta: datetime.timedelta
set_type: Set[str]
tuple_type: Tuple[int, str]
path: Path
if IS_PYDANTIC_V2:
model_config = ConfigDict(
arbitrary_types_allowed=True,
)
else:
class Config:
arbitrary_types_allowed = True
class DocumentWithBsonEncodersFiledsTypes(Document):
color: Color
timestamp: datetime.datetime
class Settings:
bson_encoders = {
Color: lambda c: c.as_rgb(),
datetime.datetime: lambda o: o.isoformat(timespec="microseconds"),
}
if IS_PYDANTIC_V2:
model_config = ConfigDict(
arbitrary_types_allowed=True,
)
else:
class Config:
arbitrary_types_allowed = True
class DocumentWithActions(Document):
name: str
num_1: int = 0
num_2: int = 10
num_3: int = 100
_private_num: int = PrivateAttr(default=100)
class Inner:
inner_num_1 = 0
inner_num_2 = 0
@before_event(Insert)
def capitalize_name(self):
self.name = self.name.capitalize()
@before_event([Insert, Replace, Save])
async def add_one(self):
self.num_1 += 1
@after_event(Insert)
def num_2_change(self):
self.num_2 -= 1
@after_event(Replace)
def num_3_change(self):
self.num_3 -= 1
@before_event(Delete)
def inner_num_to_one(self):
self.Inner.inner_num_1 = 1
@after_event(Delete)
def inner_num_to_two(self):
self.Inner.inner_num_2 = 2
@before_event(Update)
def inner_num_to_one_2(self):
self._private_num += 1
@after_event(Update)
def inner_num_to_two_2(self):
self.num_2 -= 1
class DocumentWithActions2(Document):
name: str
num_1: int = 0
num_2: int = 10
num_3: int = 100
_private_num: int = PrivateAttr(default=100)
class Inner:
inner_num_1 = 0
inner_num_2 = 0
@before_event(Insert)
def capitalize_name(self):
self.name = self.name.capitalize()
@before_event(Insert, Replace, Save)
async def add_one(self):
self.num_1 += 1
@after_event(Insert)
def num_2_change(self):
self.num_2 -= 1
@after_event(Replace)
def num_3_change(self):
self.num_3 -= 1
@before_event(Delete)
def inner_num_to_one(self):
self.Inner.inner_num_1 = 1
@after_event(Delete)
def inner_num_to_two(self):
self.Inner.inner_num_2 = 2
@before_event(Update)
def inner_num_to_one_2(self):
self._private_num += 1
@after_event(Update)
def inner_num_to_two_2(self):
self.num_2 -= 1
class InheritedDocumentWithActions(DocumentWithActions):
...
class InternalDoc(BaseModel):
_private_field: str = PrivateAttr(default="TEST_PRIVATE")
num: int = 100
string: str = "test"
lst: List[int] = [1, 2, 3, 4, 5]
def change_private(self):
self._private_field = "PRIVATE_CHANGED"
def get_private(self):
return self._private_field
class DocumentWithTurnedOnStateManagement(Document):
num_1: int
num_2: int
internal: InternalDoc
class Settings:
use_state_management = True
class DocumentWithTurnedOnStateManagementWithCustomId(Document):
id: int
num_1: int
num_2: int
class Settings:
use_state_management = True
class DocumentWithTurnedOnReplaceObjects(Document):
num_1: int
num_2: int
internal: InternalDoc
class Settings:
use_state_management = True
state_management_replace_objects = True
class DocumentWithTurnedOnSavePrevious(Document):
num_1: int
num_2: int
internal: InternalDoc
class Settings:
use_state_management = True
state_management_save_previous = True
class DocumentWithTurnedOffStateManagement(Document):
num_1: int
num_2: int
class DocumentWithValidationOnSave(Document):
num_1: int
num_2: int
@after_event(ValidateOnSave)
def num_2_plus_1(self):
self.num_2 += 1
class Settings:
validate_on_save = True
use_state_management = True
class DocumentWithRevisionTurnedOn(Document):
num_1: int
num_2: int
class Settings:
use_revision = True
use_state_management = True
class DocumentWithPydanticConfig(Document):
if IS_PYDANTIC_V2:
model_config = ConfigDict(validate_assignment=True)
else:
class Config:
validate_assignment = True
num_1: int
class DocumentWithExtras(Document):
if IS_PYDANTIC_V2:
model_config = ConfigDict(extra="allow")
else:
class Config:
extra = "allow"
num_1: int
class DocumentWithExtrasKw(Document, extra="allow"):
num_1: int
class Yard(Document):
v: int
w: int
class Lock(Document):
k: int
class Window(Document):
x: int
y: int
lock: Optional[Link[Lock]] = None
class WindowWithValidationOnSave(Document):
x: int
y: int
lock: Optional[Link[Lock]] = None
class Settings:
validate_on_save = True
class Door(Document):
t: int = 10
window: Optional[Link[Window]] = None
locks: Optional[List[Link[Lock]]] = None
class Roof(Document):
r: int = 100
class House(Document):
windows: List[Link[Window]]
door: Link[Door]
roof: Optional[Link[Roof]] = None
yards: Optional[List[Link[Yard]]] = None
height: Indexed(int) = 2
name: Indexed(str) = Field(exclude=True)
if IS_PYDANTIC_V2:
model_config = ConfigDict(
extra="allow",
)
else:
class Config:
extra = Extra.allow
class DocumentForEncodingTest(Document):
bytes_field: Optional[bytes] = None
datetime_field: Optional[datetime.datetime] = None
class DocumentWithTimeseries(Document):
ts: datetime.datetime = Field(default_factory=datetime.datetime.now)
class Settings:
timeseries = TimeSeriesConfig(time_field="ts", expire_after_seconds=2)
class DocumentWithStringField(Document):
string_field: str
class DocumentForEncodingTestDate(Document):
date_field: datetime.date = Field(default_factory=datetime.date.today)
class Settings:
name = "test_date"
bson_encoders = {
datetime.date: lambda dt: datetime.datetime(
year=dt.year,
month=dt.month,
day=dt.day,
hour=0,
minute=0,
second=0,
)
}
class DocumentUnion(UnionDoc):
class Settings:
name = "multi_model"
class_id = "123"
class DocumentMultiModelOne(Document):
int_filed: int = 0
shared: int = 0
class Settings:
union_doc = DocumentUnion
name = "multi_one"
class_id = "123"
class DocumentMultiModelTwo(Document):
str_filed: str = "test"
shared: int = 0
linked_doc: Optional[Link[DocumentMultiModelOne]] = None
class Settings:
union_doc = DocumentUnion
name = "multi_two"
class_id = "123"
class YardWithRevision(Document):
v: int
w: int
class Settings:
use_revision = True
use_state_management = True
class LockWithRevision(Document):
k: int
class Settings:
use_revision = True
use_state_management = True
class WindowWithRevision(Document):
x: int
y: int
lock: Link[LockWithRevision]
class Settings:
use_revision = True
use_state_management = True
class HouseWithRevision(Document):
windows: List[Link[WindowWithRevision]]
class Settings:
use_revision = True
use_state_management = True
# classes for inheritance test
class Vehicle(Document):
"""Root parent for testing flat inheritance"""
# Vehicle
# / | \
# / | \
# Bicycle Bike Car
# \
# \
# Bus
color: str
@after_event(Insert)
def on_object_create(self):
# this event will be triggered for all children too (self will have corresponding type)
...
class Settings:
is_root = True
class Bicycle(Vehicle):
frame: int
wheels: int
class Fuelled(BaseModel):
"""Just a mixin"""
fuel: Optional[str] = None
class Car(Vehicle, Fuelled):
body: str
class Bike(Vehicle, Fuelled):
...
class Bus(Car, Fuelled):
seats: int
class Owner(Document):
name: str
vehicles: List[Link[Vehicle]] = []
class MixinNonRoot(BaseModel):
id: int = Field(..., ge=1, le=254)
class MyDocNonRoot(Document):
class Settings:
use_state_management = True
class DocNonRoot(MixinNonRoot, MyDocNonRoot):
name: str
class Doc2NonRoot(MyDocNonRoot):
name: str
class Child(BaseModel):
child_field: str
class SampleWithMutableObjects(Document):
d: Dict[str, Child]
lst: List[Child]
class SampleLazyParsing(Document):
i: int
s: str
lst: List[int] = Field(
[],
)
if IS_PYDANTIC_V2:
model_config = ConfigDict(
validate_assignment=True,
)
else:
class Config:
validate_assignment = True
class Settings:
lazy_parsing = True
use_state_management = True
class RootDocument(Document):
name: str
link_root: Link[Document]
class ADocument(RootDocument):
surname: str
link_a: Link[Document]
class Settings:
name = "B"
class BDocument(RootDocument):
email: str
link_b: Link[Document]
class Settings:
name = "B"
class StateAndDecimalFieldModel(Document):
amt: DecimalAnnotation
other_amt: DecimalAnnotation = Field(
decimal_places=1, multiple_of=0.5, default=0
)
class Settings:
name = "amounts"
use_revision = True
use_state_management = True
class Region(Document):
state: Optional[str] = "TEST"
city: Optional[str] = "TEST"
district: Optional[str] = "TEST"
class UsersAddresses(Document):
region_id: Optional[Link[Region]] = None
phone_number: Optional[str] = None
street: Optional[str] = None
class AddressView(BaseModel):
id: Optional[PydanticObjectId] = Field(alias="_id", default=None)
phone_number: Optional[str] = None
street: Optional[str] = None
state: Optional[str] = None
city: Optional[str] = None
district: Optional[str] = None
class Settings:
projection = {
"id": "$_id",
"phone_number": 1,
"street": 1,
"sub_district": "$region_id.sub_district",
"city": "$region_id.city",
"state": "$region_id.state",
}
class SelfLinked(Document):
item: Optional[Link["SelfLinked"]] = None
s: str
class LoopedLinksA(Document):
b: "LoopedLinksB"
class LoopedLinksB(Document):
a: Optional[LoopedLinksA] = None
class DocWithCollectionInnerClass(Document):
s: str
class Collection:
name = "test"
class DocumentWithDecimalField(Document):
amt: DecimalAnnotation
other_amt: DecimalAnnotation = Field(
decimal_places=1, multiple_of=0.5, default=0
)
if IS_PYDANTIC_V2:
model_config = ConfigDict(
validate_assignment=True,
)
else:
class Config:
validate_assignment = True
class Settings:
name = "amounts"
use_revision = True
use_state_management = True
indexes = [
pymongo.IndexModel(
keys=[("amt", pymongo.ASCENDING)], name="amt_ascending"
),
pymongo.IndexModel(
keys=[("other_amt", pymongo.DESCENDING)],
name="other_amt_descending",
),
]
class ModelWithOptionalField(BaseModel):
s: Optional[str] = None
i: int
class DocumentWithKeepNullsFalse(Document):
o: Optional[str] = None
m: ModelWithOptionalField
class Settings:
keep_nulls = False
use_state_management = True
class ReleaseElemMatch(BaseModel):
major_ver: int
minor_ver: int
build_ver: int
class PackageElemMatch(Document):
releases: List[ReleaseElemMatch] = []
class DocumentWithLink(Document):
link: Link["DocumentWithBackLink"]
s: str = "TEST"
class DocumentWithBackLink(Document):
if IS_PYDANTIC_V2:
back_link: BackLink[DocumentWithLink] = Field(
json_schema_extra={"original_field": "link"},
)
else:
back_link: BackLink[DocumentWithLink] = Field(original_field="link")
i: int = 1
class DocumentWithOptionalBackLink(Document):
if IS_PYDANTIC_V2:
back_link: Optional[BackLink[DocumentWithLink]] = Field(
json_schema_extra={"original_field": "link"},
)
else:
back_link: Optional[BackLink[DocumentWithLink]] = Field(
original_field="link"
)
i: int = 1
class DocumentWithListLink(Document):
link: List[Link["DocumentWithListBackLink"]]
s: str = "TEST"
class DocumentWithListBackLink(Document):
if IS_PYDANTIC_V2:
back_link: List[BackLink[DocumentWithListLink]] = Field(
json_schema_extra={"original_field": "link"},
)
else:
back_link: List[BackLink[DocumentWithListLink]] = Field(
original_field="link"
)
i: int = 1
class DocumentWithOptionalListBackLink(Document):
if IS_PYDANTIC_V2:
back_link: Optional[List[BackLink[DocumentWithListLink]]] = Field(
json_schema_extra={"original_field": "link"},
)
else:
back_link: Optional[List[BackLink[DocumentWithListLink]]] = Field(
original_field="link"
)
i: int = 1
class DocumentToBeLinked(Document):
s: str = "TEST"
class DocumentWithListOfLinks(Document):
links: List[Link[DocumentToBeLinked]]
s: str = "TEST"
class DocumentWithTimeStampToTestConsistency(Document):
ts: datetime.datetime = Field(default_factory=datetime.datetime.utcnow)
class DocumentWithIndexMerging1(Document):
class Settings:
indexes = [
"s1",
[
("s2", pymongo.ASCENDING),
],
IndexModel(
[("s3", pymongo.ASCENDING)],
name="s3_index",
),
IndexModel(
[("s4", pymongo.ASCENDING)],
name="s4_index",
),
]
class DocumentWithIndexMerging2(DocumentWithIndexMerging1):
class Settings:
merge_indexes = True
indexes = [
"s0",
"s1",
[
("s2", pymongo.DESCENDING),
],
IndexModel(
[("s3", pymongo.DESCENDING)],
name="s3_index",
),
]
class DocumentWithCustomInit(Document):
s: ClassVar[str] = "TEST"
@classmethod
async def custom_init(cls):
cls.s = "TEST2"
class LinkDocumentForTextSeacrh(Document):
i: int
class DocumentWithTextIndexAndLink(Document):
s: str
link: Link[LinkDocumentForTextSeacrh]
class Settings:
indexes = [
pymongo.IndexModel(