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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385
|
import asyncio
import warnings
from datetime import datetime, timezone
from enum import Enum
from typing import (
TYPE_CHECKING,
Any,
Callable,
ClassVar,
Coroutine,
Dict,
Iterable,
List,
Mapping,
Optional,
Tuple,
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.asynchronous.client_session import AsyncClientSession
from pymongo.errors import DuplicateKeyError
from pymongo.results import (
DeleteResult,
InsertManyResult,
)
from typing_extensions import Concatenate, ParamSpec, Self, TypeAlias
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
from beanie.odm.cache import LRUCache
from beanie.odm.enums import SortDirection
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.find import FindMany, FindOne
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 apply_changes, 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,
)
from beanie.odm.utils.typing import extract_id_class
if IS_PYDANTIC_V2:
from pydantic import model_validator
if TYPE_CHECKING:
from beanie.odm.views import View
FindType = TypeVar("FindType", bound=Union["Document", "View"])
DocType = TypeVar("DocType", bound="Document")
P = ParamSpec("P")
R = TypeVar("R")
# can describe both sync and async, where R itself is a coroutine
AnyDocMethod: TypeAlias = Callable[Concatenate[DocType, P], R]
# describes only async
AsyncDocMethod: TypeAlias = Callable[
Concatenate[DocType, P], Coroutine[Any, Any, R]
]
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 MergeStrategy(str, Enum):
local = "local"
remote = "remote"
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)
_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 __init__(self, *args: Any, **kwargs: Any) -> None:
super(Document, self).__init__(*args, **kwargs)
self.get_pymongo_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[AsyncClientSession] = None,
ignore_cache: bool = False,
fetch_links: bool = False,
with_children: bool = False,
nesting_depth: Optional[int] = None,
nesting_depths_per_field: Optional[Dict[str, int]] = None,
**pymongo_kwargs: Any,
) -> Optional["DocType"]:
"""
Get document by id, returns None if document does not exist
:param document_id: PydanticObjectId - document id
:param session: Optional[AsyncClientSession] - 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,
nesting_depth=nesting_depth,
nesting_depths_per_field=nesting_depths_per_field,
**pymongo_kwargs,
)
async def sync(self, merge_strategy: MergeStrategy = MergeStrategy.remote):
"""
Sync the document with the database
:param merge_strategy: MergeStrategy - how to merge the document
:return: None
"""
if (
merge_strategy == MergeStrategy.local
and self.get_settings().use_state_management is False
):
raise ValueError(
"State management must be turned on to use local merge strategy"
)
if self.id is None:
raise DocumentWasNotSaved
document = await self.find_one({"_id": self.id})
if document is None:
raise DocumentNotFound
if merge_strategy == MergeStrategy.local:
original_changes = self.get_changes()
new_state = document.get_saved_state()
if new_state is None:
raise DocumentWasNotSaved
changes_to_apply = self._collect_updates(
new_state, original_changes
)
merge_models(self, document)
apply_changes(changes_to_apply, self)
elif merge_strategy == MergeStrategy.remote:
merge_models(self, document)
else:
raise ValueError("Invalid merge strategy")
@wrap_with_actions(EventTypes.INSERT)
@save_state_after
@validate_self_before
async def insert(
self: Self,
*,
link_rule: WriteRules = WriteRules.DO_NOTHING,
session: Optional[AsyncClientSession] = None,
skip_actions: Optional[List[Union[ActionDirections, str]]] = None,
) -> Self:
"""
Insert the document (self) to the collection
:param link_rule: WriteRules - if "WriteRules.WRITE", it will insert Link Documents to db.
:param session: AsyncClientSession - pymongo session
:return: self
"""
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, session=session
)
if field_info.link_type in [
LinkTypes.LIST,
LinkTypes.OPTIONAL_LIST,
]:
if isinstance(value, List):
await asyncio.gather(
*[
obj.save(
link_rule=WriteRules.WRITE,
session=session,
)
for obj in value
if isinstance(obj, Document)
]
)
result = await self.get_pymongo_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: Self,
session: Optional[AsyncClientSession] = None,
) -> Self:
"""
The same as self.insert()
:return: self
"""
return await self.insert(session=session)
@classmethod
async def insert_one(
cls: Type[DocType],
document: DocType,
session: Optional[AsyncClientSession] = 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: AsyncClientSession - 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(
type(document),
InsertOne(
get_dict(
document,
to_db=True,
keep_nulls=document.get_settings().keep_nulls,
)
),
)
return None
@classmethod
async def insert_many(
cls: Type[DocType],
documents: Iterable[DocType],
session: Optional[AsyncClientSession] = None,
link_rule: WriteRules = WriteRules.DO_NOTHING,
**pymongo_kwargs: Any,
) -> InsertManyResult:
"""
Insert many documents to the collection
:param documents: List["Document"] - documents to insert
:param session: AsyncClientSession - 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_pymongo_collection().insert_many(
documents_list, session=session, **pymongo_kwargs
)
@wrap_with_actions(EventTypes.REPLACE)
@save_state_after
@validate_self_before
async def replace(
self: Self,
ignore_revision: bool = False,
session: Optional[AsyncClientSession] = None,
bulk_writer: Optional[BulkWriter] = None,
link_rule: WriteRules = WriteRules.DO_NOTHING,
skip_actions: Optional[List[Union[ActionDirections, str]]] = None,
) -> Self:
"""
Fully update the document in the database
:param session: Optional[AsyncClientSession] - 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):
await asyncio.gather(
*[
obj.replace(
link_rule=link_rule,
bulk_writer=bulk_writer,
ignore_revision=ignore_revision,
session=session,
)
for obj in value
if isinstance(obj, Document)
]
)
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.revision_id
self.revision_id = uuid4()
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: Self,
session: Optional[AsyncClientSession] = None,
link_rule: WriteRules = WriteRules.DO_NOTHING,
ignore_revision: bool = False,
**kwargs: Any,
) -> Self:
"""
Update an existing model in the database or
insert it if it does not yet exist.
:param session: Optional[AsyncClientSession] - pymongo session.
:param link_rule: WriteRules - rules how to deal with links on writing
:param ignore_revision: bool - do force save.
:return: self
"""
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):
await asyncio.gather(
*[
obj.save(
link_rule=link_rule, session=session
)
for obj in value
if isinstance(obj, Document)
]
)
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: Self,
ignore_revision: bool = False,
session: Optional[AsyncClientSession] = None,
bulk_writer: Optional[BulkWriter] = None,
skip_actions: Optional[List[Union[ActionDirections, str]]] = None,
) -> Optional[Self]:
"""
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: Optional[self]
"""
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,
ignore_revision=ignore_revision,
session=session,
bulk_writer=bulk_writer,
)
@classmethod
async def replace_many(
cls: Type[DocType],
documents: List[DocType],
session: Optional[AsyncClientSession] = None,
) -> None:
"""
Replace list of documents
:param documents: List["Document"]
:param session: Optional[AsyncClientSession] - 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: Self,
*args: Union[Dict[Any, Any], Mapping[Any, Any]],
ignore_revision: bool = False,
session: Optional[AsyncClientSession] = None,
bulk_writer: Optional[BulkWriter] = None,
skip_actions: Optional[List[Union[ActionDirections, str]]] = None,
skip_sync: Optional[bool] = None,
**pymongo_kwargs: Any,
) -> Self:
"""
Partially update the document in the database
:param args: *Union[dict, Mapping] - the modifications to apply.
:param session: AsyncClientSession - 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: self
"""
arguments: list[Any] = 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.revision_id
if use_revision_id:
new_revision_id = uuid4()
arguments.append(SetRevisionId(new_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[AsyncClientSession] = None,
bulk_writer: Optional[BulkWriter] = None,
**pymongo_kwargs: Any,
) -> UpdateMany:
"""
Partially update all the documents
:param args: *Union[dict, Mapping] - the modifications to apply.
:param session: AsyncClientSession - 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: Self,
expression: Dict[Union[ExpressionField, str, Any], Any],
session: Optional[AsyncClientSession] = None,
bulk_writer: Optional[BulkWriter] = None,
skip_sync: Optional[bool] = None,
**kwargs: Any,
) -> Coroutine[None, None, Self]:
"""
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], Any] - keys and
values to set
:param session: Optional[AsyncClientSession] - 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: Self,
expression: Dict[Union[datetime, ExpressionField, str], Any],
session: Optional[AsyncClientSession] = None,
bulk_writer: Optional[BulkWriter] = None,
skip_sync: Optional[bool] = None,
**kwargs: Any,
) -> Coroutine[None, None, Self]:
"""
Set current date
Uses [CurrentDate operator](operators/update.md#currentdate)
:param expression: Dict[Union[datetime, ExpressionField, str], Any]
:param session: Optional[AsyncClientSession] - 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: Self,
expression: Dict[Union[ExpressionField, float, int, str], Any],
session: Optional[AsyncClientSession] = None,
bulk_writer: Optional[BulkWriter] = None,
skip_sync: Optional[bool] = None,
**kwargs: Any,
) -> Coroutine[None, None, Self]:
"""
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, float, int, str], Any]
:param session: Optional[AsyncClientSession] - 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[AsyncClientSession] = None,
bulk_writer: Optional[BulkWriter] = None,
link_rule: DeleteRules = DeleteRules.DO_NOTHING,
skip_actions: Optional[List[Union[ActionDirections, str]]] = None,
**pymongo_kwargs: Any,
) -> Optional[DeleteResult]:
"""
Delete the document
:param session: Optional[AsyncClientSession] - 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):
await asyncio.gather(
*[
obj.delete(
link_rule=DeleteRules.DELETE_LINKS,
**pymongo_kwargs,
)
for obj in value
if isinstance(obj, Document)
]
)
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[AsyncClientSession] = None,
bulk_writer: Optional[BulkWriter] = None,
**pymongo_kwargs: Any,
) -> Optional[DeleteResult]:
"""
Delete all the documents
:param session: Optional[AsyncClientSession] - 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,
exclude={"revision_id"},
)
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
@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,
exclude={"revision_id"},
):
return False
return True
@property
@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, # type: ignore
get_dict(
self,
to_db=True,
keep_nulls=self.get_settings().keep_nulls,
exclude={"revision_id"},
),
)
@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:
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)
# 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
async def inspect_collection(
cls, session: Optional[AsyncClientSession] = None
) -> InspectionResult:
"""
Check, if documents, stored in the MongoDB collection
are compatible with the Document schema
:param session: Optional[AsyncClientSession] - pymongo session
The session instance used for transactional operations. Defaults to None.
:return: InspectionResult
"""
inspection_result = InspectionResult()
async for json_document in cls.get_pymongo_collection().find(
{}, session=session
):
try:
parse_model(cls, 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
@classmethod
def _check_hidden_fields(cls):
hidden_fields = [
(name, field)
for name, field in get_model_fields(cls).items()
if get_extra_field_info(field, "hidden") is True
]
if not hidden_fields:
return
warnings.warn(
f"{cls.__name__}: 'hidden=True' is deprecated, please use 'exclude=True'",
DeprecationWarning,
stacklevel=2,
)
if IS_PYDANTIC_V2:
for name, field in hidden_fields:
field.exclude = True
del field.json_schema_extra["hidden"]
cls.model_rebuild(force=True)
else:
for name, field in hidden_fields:
field.field_info.exclude = True
del field.field_info.extra["hidden"]
cls.__exclude_fields__[name] = True
@wrap_with_actions(event_type=EventTypes.VALIDATE_ON_SAVE)
async def validate_self(self, *args: Any, **kwargs: Any):
# TODO: it can be sync, but needs some actions controller improvements
if self.get_settings().validate_on_save:
new_model = parse_model(self.__class__, get_model_dump(self))
merge_models(self, new_model)
def to_ref(self):
if self.id is None:
raise DocumentWasNotSaved("Can not create dbref without id")
return DBRef(self.get_pymongo_collection().name, self.id)
async def fetch_link(self, field: Union[str, Any]):
ref_obj = getattr(self, field, None)
if isinstance(ref_obj, Link):
value = await ref_obj.fetch(fetch_links=True)
setattr(self, field, value)
if isinstance(ref_obj, list) and ref_obj:
values = await Link.fetch_list(ref_obj, fetch_links=True)
setattr(self, field, values)
async def fetch_all_links(self):
coros = []
link_fields = self.get_link_fields()
if link_fields is not None:
for ref in link_fields.values():
coros.append(self.fetch_link(ref.field_name)) # TODO lists
await asyncio.gather(*coros)
@classmethod
def get_link_fields(cls) -> Optional[Dict[str, LinkInfo]]:
return cls._link_fields
@classmethod
def get_model_type(cls) -> ModelType:
return ModelType.Document
@classmethod
async def distinct(
cls,
key: str,
filter: Optional[Mapping[str, Any]] = None,
session: Optional[AsyncClientSession] = None,
**kwargs: Any,
) -> list:
return await cls.get_pymongo_collection().distinct(
key=key, filter=filter, session=session, **kwargs
)
@classmethod
def link_from_id(cls, id: Any):
ref = DBRef(id=id, collection=cls.get_collection_name())
return Link(ref, document_class=cls)
@classmethod
def bulk_writer(
cls,
session: Optional[AsyncClientSession] = None,
ordered: bool = True,
bypass_document_validation: Optional[bool] = False,
comment: Optional[Any] = None,
) -> BulkWriter:
"""
Returns a BulkWriter instance for handling bulk write operations.
:param session: Optional[AsyncClientSession] - pymongo session.
The session instance used for transactional operations.
:param ordered: bool
If ``True`` (the default), requests will be performed on the server serially, in the order provided. If an error
occurs, all remaining operations are aborted. If ``False``, requests will be performed on the server in
arbitrary order, possibly in parallel, and all operations will be attempted.
:param bypass_document_validation: bool, optional
If ``True``, allows the write to opt-out of document-level validation. Default is ``False``.
:param comment: str, optional
A user-provided comment to attach to the BulkWriter.
:returns: BulkWriter
An instance of BulkWriter configured with the provided settings.
Example Usage:
--------------
This method is typically used within an asynchronous context manager.
.. code-block:: python
async with Document.bulk_writer(ordered=True) as bulk:
await Document.insert_one(Document(field="value"), bulk_writer=bulk)
"""
return BulkWriter(
session, ordered, cls, bypass_document_validation, comment
)
class DocumentWithSoftDelete(Document):
deleted_at: Optional[datetime] = None
def is_deleted(self) -> bool:
return self.deleted_at is not None
async def hard_delete(
self,
session: Optional[AsyncClientSession] = None,
bulk_writer: Optional[BulkWriter] = None,
link_rule: DeleteRules = DeleteRules.DO_NOTHING,
skip_actions: Optional[List[Union[ActionDirections, str]]] = None,
**pymongo_kwargs: Any,
) -> Optional[DeleteResult]:
return await super().delete(
session=session,
bulk_writer=bulk_writer,
link_rule=link_rule,
skip_actions=skip_actions,
**pymongo_kwargs,
)
async def delete(
self,
session: Optional[AsyncClientSession] = None,
bulk_writer: Optional[BulkWriter] = None,
link_rule: DeleteRules = DeleteRules.DO_NOTHING,
skip_actions: Optional[List[Union[ActionDirections, str]]] = None,
**pymongo_kwargs,
) -> Optional[DeleteResult]:
self.deleted_at = datetime.now(tz=timezone.utc)
await self.save()
return None
@classmethod
def find_many_in_all( # type: ignore
cls: Type[FindType],
*args: Union[Mapping[Any, 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[AsyncClientSession] = None,
ignore_cache: bool = False,
fetch_links: bool = False,
with_children: bool = False,
lazy_parse: bool = False,
nesting_depth: Optional[int] = None,
nesting_depths_per_field: Optional[Dict[str, int]] = None,
**pymongo_kwargs: Any,
) -> Union[FindMany[FindType], FindMany["DocumentProjectionType"]]:
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,
fetch_links=fetch_links,
lazy_parse=lazy_parse,
nesting_depth=nesting_depth,
nesting_depths_per_field=nesting_depths_per_field,
**pymongo_kwargs,
)
@classmethod
def find_many( # type: ignore
cls: Type[FindType],
*args: Union[Mapping[Any, 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[AsyncClientSession] = None,
ignore_cache: bool = False,
fetch_links: bool = False,
with_children: bool = False,
lazy_parse: bool = False,
nesting_depth: Optional[int] = None,
nesting_depths_per_field: Optional[Dict[str, int]] = None,
**pymongo_kwargs: Any,
) -> Union[FindMany[FindType], FindMany["DocumentProjectionType"]]:
args = cls._add_class_id_filter(args, with_children) + (
{"deleted_at": None},
)
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,
fetch_links=fetch_links,
lazy_parse=lazy_parse,
nesting_depth=nesting_depth,
nesting_depths_per_field=nesting_depths_per_field,
**pymongo_kwargs,
)
@classmethod
def find_one( # type: ignore
cls: Type[FindType],
*args: Union[Mapping[Any, Any], bool],
projection_model: Optional[Type["DocumentProjectionType"]] = None,
session: Optional[AsyncClientSession] = None,
ignore_cache: bool = False,
fetch_links: bool = False,
with_children: bool = False,
nesting_depth: Optional[int] = None,
nesting_depths_per_field: Optional[Dict[str, int]] = None,
**pymongo_kwargs: Any,
) -> Union[FindOne[FindType], FindOne["DocumentProjectionType"]]:
args = cls._add_class_id_filter(args, with_children) + (
{"deleted_at": None},
)
return cls._find_one_query_class(document_model=cls).find_one(
*args,
projection_model=projection_model,
session=session,
ignore_cache=ignore_cache,
fetch_links=fetch_links,
nesting_depth=nesting_depth,
nesting_depths_per_field=nesting_depths_per_field,
**pymongo_kwargs,
)
|