| 1 |
import asyncio |
| 2 |
import warnings |
| 3 |
from collections.abc import Callable, Coroutine, Iterable, Mapping |
| 4 |
from datetime import datetime, timezone |
| 5 |
from enum import Enum |
| 6 |
from typing import ( |
| 7 |
TYPE_CHECKING, |
| 8 |
Any, |
| 9 |
ClassVar, |
| 10 |
TypeAlias, |
| 11 |
TypeVar, |
| 12 |
) |
| 13 |
from uuid import UUID, uuid4 |
| 14 |
|
| 15 |
from bson import DBRef |
| 16 |
from lazy_model import LazyModel |
| 17 |
from pydantic import ( |
| 18 |
ConfigDict, |
| 19 |
Field, |
| 20 |
PrivateAttr, |
| 21 |
ValidationError, |
| 22 |
model_validator, |
| 23 |
) |
| 24 |
from pydantic.main import BaseModel |
| 25 |
from pymongo import InsertOne |
| 26 |
from pymongo.asynchronous.client_session import AsyncClientSession |
| 27 |
from pymongo.errors import DuplicateKeyError |
| 28 |
from pymongo.results import ( |
| 29 |
DeleteResult, |
| 30 |
InsertManyResult, |
| 31 |
) |
| 32 |
from typing_extensions import ParamSpec, Self |
| 33 |
|
| 34 |
from beanie.exceptions import ( |
| 35 |
CollectionWasNotInitialized, |
| 36 |
DocumentNotFound, |
| 37 |
DocumentWasNotSaved, |
| 38 |
NotSupported, |
| 39 |
ReplaceError, |
| 40 |
RevisionIdWasChanged, |
| 41 |
) |
| 42 |
from beanie.odm.actions import ( |
| 43 |
ActionDirections, |
| 44 |
ActionRegistry, |
| 45 |
EventTypes, |
| 46 |
wrap_with_actions, |
| 47 |
) |
| 48 |
from beanie.odm.bulk import BulkWriter |
| 49 |
from beanie.odm.cache import LRUCache |
| 50 |
from beanie.odm.enums import SortDirection |
| 51 |
from beanie.odm.fields import ( |
| 52 |
BackLink, |
| 53 |
DeleteRules, |
| 54 |
ExpressionField, |
| 55 |
Link, |
| 56 |
LinkInfo, |
| 57 |
LinkTypes, |
| 58 |
PydanticObjectId, |
| 59 |
WriteRules, |
| 60 |
) |
| 61 |
from beanie.odm.interfaces.aggregate import AggregateInterface |
| 62 |
from beanie.odm.interfaces.detector import ModelType |
| 63 |
from beanie.odm.interfaces.find import FindInterface |
| 64 |
from beanie.odm.interfaces.getters import OtherGettersInterface |
| 65 |
from beanie.odm.interfaces.inheritance import InheritanceInterface |
| 66 |
from beanie.odm.interfaces.setters import SettersInterface |
| 67 |
from beanie.odm.models import ( |
| 68 |
InspectionError, |
| 69 |
InspectionResult, |
| 70 |
InspectionStatuses, |
| 71 |
) |
| 72 |
from beanie.odm.operators.find.comparison import In |
| 73 |
from beanie.odm.operators.update.general import ( |
| 74 |
CurrentDate, |
| 75 |
Inc, |
| 76 |
SetRevisionId, |
| 77 |
Unset, |
| 78 |
) |
| 79 |
from beanie.odm.operators.update.general import ( |
| 80 |
Set as SetOperator, |
| 81 |
) |
| 82 |
from beanie.odm.queries.find import FindMany, FindOne |
| 83 |
from beanie.odm.queries.update import UpdateMany, UpdateResponse |
| 84 |
from beanie.odm.settings.document import DocumentSettings |
| 85 |
from beanie.odm.utils.dump import get_dict, get_top_level_nones |
| 86 |
from beanie.odm.utils.parsing import apply_changes, merge_models |
| 87 |
from beanie.odm.utils.pydantic import ( |
| 88 |
get_extra_field_info, |
| 89 |
get_field_type, |
| 90 |
get_model_dump, |
| 91 |
get_model_fields, |
| 92 |
parse_model, |
| 93 |
parse_object_as, |
| 94 |
) |
| 95 |
from beanie.odm.utils.self_validation import validate_self_before |
| 96 |
from beanie.odm.utils.state import ( |
| 97 |
previous_saved_state_needed, |
| 98 |
save_state_after, |
| 99 |
saved_state_needed, |
| 100 |
) |
| 101 |
from beanie.odm.utils.typing import extract_id_class |
| 102 |
from beanie.odm.utils.update_merge import merge_update_expressions |
| 103 |
|
| 104 |
if TYPE_CHECKING: |
| 105 |
from beanie.odm.views import View |
| 106 |
|
| 107 |
FindType = TypeVar("FindType", bound="Document | View") |
| 108 |
DocType = TypeVar("DocType", bound="Document") |
| 109 |
P = ParamSpec("P") |
| 110 |
R = TypeVar("R") |
| 111 |
# can describe both sync and async, where R itself is a coroutine |
| 112 |
AnyDocMethod: TypeAlias = Callable[P, R] |
| 113 |
# describes only async |
| 114 |
AsyncDocMethod: TypeAlias = Callable[P, Coroutine[Any, Any, R]] |
| 115 |
DocumentProjectionType = TypeVar("DocumentProjectionType", bound=BaseModel) |
| 116 |
|
| 117 |
|
| 118 |
def json_schema_extra(schema: dict[str, Any], model: type["Document"]) -> None: |
| 119 |
# remove excluded fields from the json schema |
| 120 |
properties = schema.get("properties") |
| 121 |
if not properties: |
| 122 |
return |
| 123 |
for k, field in get_model_fields(model).items(): |
| 124 |
k = field.alias or k |
| 125 |
if k not in properties: |
| 126 |
continue |
| 127 |
if field.exclude: |
| 128 |
del properties[k] |
| 129 |
|
| 130 |
|
| 131 |
def document_alias_generator(s: str) -> str: |
| 132 |
if s == "id": |
| 133 |
return "_id" |
| 134 |
return s |
| 135 |
|
| 136 |
|
| 137 |
class MergeStrategy(str, Enum): |
| 138 |
local = "local" |
| 139 |
remote = "remote" |
| 140 |
|
| 141 |
|
| 142 |
class Document( |
| 143 |
LazyModel, |
| 144 |
SettersInterface, |
| 145 |
InheritanceInterface, |
| 146 |
FindInterface, |
| 147 |
AggregateInterface, |
| 148 |
OtherGettersInterface, |
| 149 |
): |
| 150 |
""" |
| 151 |
Document Mapping class. |
| 152 |
|
| 153 |
Fields: |
| 154 |
|
| 155 |
- `id` - MongoDB document ObjectID "_id" field. |
| 156 |
Mapped to the PydanticObjectId class |
| 157 |
""" |
| 158 |
|
| 159 |
model_config = ConfigDict( |
| 160 |
json_schema_extra=json_schema_extra, |
| 161 |
populate_by_name=True, |
| 162 |
alias_generator=document_alias_generator, |
| 163 |
) |
| 164 |
|
| 165 |
id: PydanticObjectId | None = Field( |
| 166 |
default=None, description="MongoDB document ObjectID" |
| 167 |
) |
| 168 |
|
| 169 |
# State |
| 170 |
revision_id: UUID | None = Field(default=None, exclude=True) |
| 171 |
_saved_state: dict[str, Any] | None = PrivateAttr(default=None) |
| 172 |
_previous_saved_state: dict[str, Any] | None = PrivateAttr(default=None) |
| 173 |
|
| 174 |
# Relations |
| 175 |
_link_fields: ClassVar[dict[str, LinkInfo] | None] = None |
| 176 |
|
| 177 |
# Cache |
| 178 |
_cache: ClassVar[LRUCache | None] = None |
| 179 |
|
| 180 |
# Settings |
| 181 |
_document_settings: ClassVar[DocumentSettings | None] = None |
| 182 |
|
| 183 |
# Database |
| 184 |
_database_major_version: ClassVar[int] = 4 |
| 185 |
|
| 186 |
def __init__(self, *args: Any, **kwargs: Any) -> None: |
| 187 |
super().__init__(*args, **kwargs) |
| 188 |
self.get_pymongo_collection() |
| 189 |
|
| 190 |
@classmethod |
| 191 |
def _fill_back_refs(cls, values): |
| 192 |
if cls._link_fields: |
| 193 |
for field_name, link_info in cls._link_fields.items(): |
| 194 |
if ( |
| 195 |
link_info.link_type |
| 196 |
in [LinkTypes.BACK_DIRECT, LinkTypes.OPTIONAL_BACK_DIRECT] |
| 197 |
and field_name not in values |
| 198 |
): |
| 199 |
values[field_name] = BackLink[link_info.document_class]( |
| 200 |
link_info.document_class |
| 201 |
) |
| 202 |
if ( |
| 203 |
link_info.link_type |
| 204 |
in [LinkTypes.BACK_LIST, LinkTypes.OPTIONAL_BACK_LIST] |
| 205 |
and field_name not in values |
| 206 |
): |
| 207 |
values[field_name] = [ |
| 208 |
BackLink[link_info.document_class]( |
| 209 |
link_info.document_class |
| 210 |
) |
| 211 |
] |
| 212 |
return values |
| 213 |
|
| 214 |
@model_validator(mode="before") |
| 215 |
def fill_back_refs(cls, values): |
| 216 |
return cls._fill_back_refs(values) |
| 217 |
|
| 218 |
@classmethod |
| 219 |
async def get( |
| 220 |
cls: type["DocType"], |
| 221 |
document_id: Any, |
| 222 |
session: AsyncClientSession | None = None, |
| 223 |
ignore_cache: bool = False, |
| 224 |
fetch_links: bool = False, |
| 225 |
with_children: bool = False, |
| 226 |
nesting_depth: int | None = None, |
| 227 |
nesting_depths_per_field: dict[str, int] | None = None, |
| 228 |
**pymongo_kwargs: Any, |
| 229 |
) -> "DocType | None": |
| 230 |
""" |
| 231 |
Get document by id, returns None if document does not exist |
| 232 |
|
| 233 |
:param document_id: PydanticObjectId - document id |
| 234 |
:param session: Optional[AsyncClientSession] - pymongo session |
| 235 |
:param ignore_cache: bool - ignore cache (if it is turned on) |
| 236 |
:param **pymongo_kwargs: pymongo native parameters for find operation |
| 237 |
:return: Union["Document", None] |
| 238 |
""" |
| 239 |
if not isinstance( |
| 240 |
document_id, |
| 241 |
extract_id_class(get_field_type(get_model_fields(cls)["id"])), |
| 242 |
): |
| 243 |
document_id = parse_object_as( |
| 244 |
get_field_type(get_model_fields(cls)["id"]), document_id |
| 245 |
) |
| 246 |
|
| 247 |
return await cls.find_one( |
| 248 |
{"_id": document_id}, |
| 249 |
session=session, |
| 250 |
ignore_cache=ignore_cache, |
| 251 |
fetch_links=fetch_links, |
| 252 |
with_children=with_children, |
| 253 |
nesting_depth=nesting_depth, |
| 254 |
nesting_depths_per_field=nesting_depths_per_field, |
| 255 |
**pymongo_kwargs, |
| 256 |
) |
| 257 |
|
| 258 |
async def sync(self, merge_strategy: MergeStrategy = MergeStrategy.remote): |
| 259 |
""" |
| 260 |
Sync the document with the database |
| 261 |
|
| 262 |
:param merge_strategy: MergeStrategy - how to merge the document |
| 263 |
:return: None |
| 264 |
""" |
| 265 |
if ( |
| 266 |
merge_strategy is MergeStrategy.local |
| 267 |
and self.get_settings().use_state_management is False |
| 268 |
): |
| 269 |
raise ValueError( |
| 270 |
"State management must be turned on to use local merge strategy" |
| 271 |
) |
| 272 |
if self.id is None: |
| 273 |
raise DocumentWasNotSaved |
| 274 |
document = await self.find_one({"_id": self.id}) |
| 275 |
if document is None: |
| 276 |
raise DocumentNotFound |
| 277 |
|
| 278 |
if merge_strategy is MergeStrategy.local: |
| 279 |
original_changes = self.get_changes() |
| 280 |
new_state = document.get_saved_state() |
| 281 |
if new_state is None: |
| 282 |
raise DocumentWasNotSaved |
| 283 |
changes_to_apply = self._collect_updates( |
| 284 |
new_state, original_changes |
| 285 |
) |
| 286 |
merge_models(self, document) |
| 287 |
apply_changes(changes_to_apply, self) |
| 288 |
elif merge_strategy is MergeStrategy.remote: |
| 289 |
merge_models(self, document) |
| 290 |
else: |
| 291 |
raise ValueError("Invalid merge strategy") |
| 292 |
|
| 293 |
@validate_self_before |
| 294 |
@wrap_with_actions(EventTypes.INSERT) |
| 295 |
@save_state_after |
| 296 |
async def insert( |
| 297 |
self: Self, |
| 298 |
*, |
| 299 |
link_rule: WriteRules = WriteRules.DO_NOTHING, |
| 300 |
session: AsyncClientSession | None = None, |
| 301 |
skip_actions: list[ActionDirections | str] | None = None, |
| 302 |
) -> Self: |
| 303 |
""" |
| 304 |
Insert the document (self) to the collection |
| 305 |
:param link_rule: WriteRules - if "WriteRules.WRITE", it will insert Link Documents to db. |
| 306 |
:param session: AsyncClientSession - pymongo session |
| 307 |
:return: self |
| 308 |
""" |
| 309 |
if self.get_settings().use_revision: |
| 310 |
self.revision_id = uuid4() |
| 311 |
if link_rule is WriteRules.WRITE: |
| 312 |
link_fields = self.get_link_fields() |
| 313 |
if link_fields is not None: |
| 314 |
for field_info in link_fields.values(): |
| 315 |
value = getattr(self, field_info.field_name) |
| 316 |
if field_info.link_type in ( |
| 317 |
LinkTypes.DIRECT, |
| 318 |
LinkTypes.OPTIONAL_DIRECT, |
| 319 |
): |
| 320 |
if isinstance(value, Document): |
| 321 |
await value.save( |
| 322 |
link_rule=WriteRules.WRITE, session=session |
| 323 |
) |
| 324 |
if field_info.link_type in ( |
| 325 |
LinkTypes.LIST, |
| 326 |
LinkTypes.OPTIONAL_LIST, |
| 327 |
): |
| 328 |
if isinstance(value, list): |
| 329 |
await asyncio.gather( |
| 330 |
*[ |
| 331 |
obj.save( |
| 332 |
link_rule=WriteRules.WRITE, |
| 333 |
session=session, |
| 334 |
) |
| 335 |
for obj in value |
| 336 |
if isinstance(obj, Document) |
| 337 |
] |
| 338 |
) |
| 339 |
result = await self.get_pymongo_collection().insert_one( |
| 340 |
get_dict( |
| 341 |
self, to_db=True, keep_nulls=self.get_settings().keep_nulls |
| 342 |
), |
| 343 |
session=session, |
| 344 |
) |
| 345 |
new_id = result.inserted_id |
| 346 |
if not isinstance( |
| 347 |
new_id, |
| 348 |
extract_id_class(get_field_type(get_model_fields(self)["id"])), |
| 349 |
): |
| 350 |
new_id = parse_object_as( |
| 351 |
get_field_type(get_model_fields(self)["id"]), new_id |
| 352 |
) |
| 353 |
self.id = new_id |
| 354 |
return self |
| 355 |
|
| 356 |
async def create( |
| 357 |
self: Self, |
| 358 |
session: AsyncClientSession | None = None, |
| 359 |
) -> Self: |
| 360 |
""" |
| 361 |
The same as self.insert() |
| 362 |
:return: self |
| 363 |
""" |
| 364 |
return await self.insert(session=session) |
| 365 |
|
| 366 |
@classmethod |
| 367 |
async def insert_one( |
| 368 |
cls: type[DocType], |
| 369 |
document: DocType, |
| 370 |
session: AsyncClientSession | None = None, |
| 371 |
bulk_writer: "BulkWriter | None" = None, |
| 372 |
link_rule: WriteRules = WriteRules.DO_NOTHING, |
| 373 |
) -> DocType | None: |
| 374 |
""" |
| 375 |
Insert one document to the collection |
| 376 |
:param document: Document - document to insert |
| 377 |
:param session: AsyncClientSession - pymongo session |
| 378 |
:param bulk_writer: "BulkWriter" - Beanie bulk writer |
| 379 |
:param link_rule: InsertRules - hot to manage link fields |
| 380 |
:return: DocType |
| 381 |
""" |
| 382 |
if not isinstance(document, cls): |
| 383 |
raise TypeError( |
| 384 |
"Inserting document must be of the original document class" |
| 385 |
) |
| 386 |
if bulk_writer is None: |
| 387 |
return await document.insert(link_rule=link_rule, session=session) |
| 388 |
else: |
| 389 |
if link_rule == WriteRules.WRITE: |
| 390 |
raise NotSupported( |
| 391 |
"Cascade insert with bulk writing not supported" |
| 392 |
) |
| 393 |
bulk_writer.add_operation( |
| 394 |
type(document), |
| 395 |
InsertOne( |
| 396 |
get_dict( |
| 397 |
document, |
| 398 |
to_db=True, |
| 399 |
keep_nulls=document.get_settings().keep_nulls, |
| 400 |
) |
| 401 |
), |
| 402 |
) |
| 403 |
return None |
| 404 |
|
| 405 |
@classmethod |
| 406 |
async def insert_many( |
| 407 |
cls: type[DocType], |
| 408 |
documents: Iterable[DocType], |
| 409 |
session: AsyncClientSession | None = None, |
| 410 |
link_rule: WriteRules = WriteRules.DO_NOTHING, |
| 411 |
**pymongo_kwargs: Any, |
| 412 |
) -> InsertManyResult: |
| 413 |
""" |
| 414 |
Insert many documents to the collection |
| 415 |
|
| 416 |
:param documents: List["Document"] - documents to insert |
| 417 |
:param session: AsyncClientSession - pymongo session |
| 418 |
:param link_rule: InsertRules - how to manage link fields |
| 419 |
:return: InsertManyResult |
| 420 |
""" |
| 421 |
if link_rule == WriteRules.WRITE: |
| 422 |
raise NotSupported( |
| 423 |
"Cascade insert not supported for insert many method" |
| 424 |
) |
| 425 |
documents_list = [ |
| 426 |
get_dict( |
| 427 |
document, |
| 428 |
to_db=True, |
| 429 |
keep_nulls=document.get_settings().keep_nulls, |
| 430 |
) |
| 431 |
for document in documents |
| 432 |
] |
| 433 |
return await cls.get_pymongo_collection().insert_many( |
| 434 |
documents_list, session=session, **pymongo_kwargs |
| 435 |
) |
| 436 |
|
| 437 |
@validate_self_before |
| 438 |
@wrap_with_actions(EventTypes.REPLACE) |
| 439 |
@save_state_after |
| 440 |
async def replace( |
| 441 |
self: Self, |
| 442 |
ignore_revision: bool = False, |
| 443 |
session: AsyncClientSession | None = None, |
| 444 |
bulk_writer: BulkWriter | None = None, |
| 445 |
link_rule: WriteRules = WriteRules.DO_NOTHING, |
| 446 |
skip_actions: list[ActionDirections | str] | None = None, |
| 447 |
) -> Self: |
| 448 |
""" |
| 449 |
Fully update the document in the database |
| 450 |
|
| 451 |
:param session: Optional[AsyncClientSession] - pymongo session. |
| 452 |
:param ignore_revision: bool - do force replace. |
| 453 |
Used when revision based protection is turned on. |
| 454 |
:param bulk_writer: "BulkWriter" - Beanie bulk writer |
| 455 |
:return: self |
| 456 |
""" |
| 457 |
if self.id is None: |
| 458 |
raise ValueError("Document must have an id") |
| 459 |
|
| 460 |
if bulk_writer is not None and link_rule is not WriteRules.DO_NOTHING: |
| 461 |
raise NotSupported |
| 462 |
|
| 463 |
if link_rule is WriteRules.WRITE: |
| 464 |
link_fields = self.get_link_fields() |
| 465 |
if link_fields is not None: |
| 466 |
for field_info in link_fields.values(): |
| 467 |
value = getattr(self, field_info.field_name) |
| 468 |
if field_info.link_type in ( |
| 469 |
LinkTypes.DIRECT, |
| 470 |
LinkTypes.OPTIONAL_DIRECT, |
| 471 |
LinkTypes.BACK_DIRECT, |
| 472 |
LinkTypes.OPTIONAL_BACK_DIRECT, |
| 473 |
): |
| 474 |
if isinstance(value, Document): |
| 475 |
await value.replace( |
| 476 |
link_rule=link_rule, |
| 477 |
bulk_writer=bulk_writer, |
| 478 |
ignore_revision=ignore_revision, |
| 479 |
session=session, |
| 480 |
) |
| 481 |
if field_info.link_type in ( |
| 482 |
LinkTypes.LIST, |
| 483 |
LinkTypes.OPTIONAL_LIST, |
| 484 |
LinkTypes.BACK_LIST, |
| 485 |
LinkTypes.OPTIONAL_BACK_LIST, |
| 486 |
): |
| 487 |
if isinstance(value, list): |
| 488 |
await asyncio.gather( |
| 489 |
*[ |
| 490 |
obj.replace( |
| 491 |
link_rule=link_rule, |
| 492 |
bulk_writer=bulk_writer, |
| 493 |
ignore_revision=ignore_revision, |
| 494 |
session=session, |
| 495 |
) |
| 496 |
for obj in value |
| 497 |
if isinstance(obj, Document) |
| 498 |
] |
| 499 |
) |
| 500 |
|
| 501 |
use_revision_id = self.get_settings().use_revision |
| 502 |
find_query: dict[str, Any] = {"_id": self.id} |
| 503 |
|
| 504 |
if use_revision_id and not ignore_revision: |
| 505 |
find_query["revision_id"] = self.revision_id |
| 506 |
self.revision_id = uuid4() |
| 507 |
try: |
| 508 |
await self.find_one(find_query).replace_one( |
| 509 |
self, |
| 510 |
session=session, |
| 511 |
bulk_writer=bulk_writer, |
| 512 |
) |
| 513 |
except DocumentNotFound: |
| 514 |
if use_revision_id and not ignore_revision: |
| 515 |
raise RevisionIdWasChanged |
| 516 |
else: |
| 517 |
raise DocumentNotFound |
| 518 |
return self |
| 519 |
|
| 520 |
@validate_self_before |
| 521 |
@wrap_with_actions(EventTypes.SAVE) |
| 522 |
@save_state_after |
| 523 |
async def save( |
| 524 |
self: Self, |
| 525 |
session: AsyncClientSession | None = None, |
| 526 |
link_rule: WriteRules = WriteRules.DO_NOTHING, |
| 527 |
ignore_revision: bool = False, |
| 528 |
**kwargs: Any, |
| 529 |
) -> Self: |
| 530 |
""" |
| 531 |
Update an existing model in the database or |
| 532 |
insert it if it does not yet exist. |
| 533 |
|
| 534 |
:param session: Optional[AsyncClientSession] - pymongo session. |
| 535 |
:param link_rule: WriteRules - rules how to deal with links on writing |
| 536 |
:param ignore_revision: bool - do force save. |
| 537 |
:return: self |
| 538 |
""" |
| 539 |
if link_rule is WriteRules.WRITE: |
| 540 |
link_fields = self.get_link_fields() |
| 541 |
if link_fields is not None: |
| 542 |
for field_info in link_fields.values(): |
| 543 |
value = getattr(self, field_info.field_name) |
| 544 |
if field_info.link_type in ( |
| 545 |
LinkTypes.DIRECT, |
| 546 |
LinkTypes.OPTIONAL_DIRECT, |
| 547 |
LinkTypes.BACK_DIRECT, |
| 548 |
LinkTypes.OPTIONAL_BACK_DIRECT, |
| 549 |
): |
| 550 |
if isinstance(value, Document): |
| 551 |
await value.save( |
| 552 |
link_rule=link_rule, session=session |
| 553 |
) |
| 554 |
if field_info.link_type in ( |
| 555 |
LinkTypes.LIST, |
| 556 |
LinkTypes.OPTIONAL_LIST, |
| 557 |
LinkTypes.BACK_LIST, |
| 558 |
LinkTypes.OPTIONAL_BACK_LIST, |
| 559 |
): |
| 560 |
if isinstance(value, list): |
| 561 |
await asyncio.gather( |
| 562 |
*[ |
| 563 |
obj.save( |
| 564 |
link_rule=link_rule, session=session |
| 565 |
) |
| 566 |
for obj in value |
| 567 |
if isinstance(obj, Document) |
| 568 |
] |
| 569 |
) |
| 570 |
|
| 571 |
if self.get_settings().keep_nulls is False: |
| 572 |
arguments: list[SetOperator | Unset] = [ |
| 573 |
SetOperator( |
| 574 |
get_dict( |
| 575 |
self, |
| 576 |
to_db=True, |
| 577 |
keep_nulls=self.get_settings().keep_nulls, |
| 578 |
) |
| 579 |
) |
| 580 |
] |
| 581 |
nones = get_top_level_nones(self) |
| 582 |
if nones: |
| 583 |
arguments.append(Unset(nones)) |
| 584 |
return await self.update( |
| 585 |
*arguments, |
| 586 |
session=session, |
| 587 |
ignore_revision=ignore_revision, |
| 588 |
upsert=True, |
| 589 |
**kwargs, |
| 590 |
) |
| 591 |
else: |
| 592 |
return await self.update( |
| 593 |
SetOperator( |
| 594 |
get_dict( |
| 595 |
self, |
| 596 |
to_db=True, |
| 597 |
keep_nulls=self.get_settings().keep_nulls, |
| 598 |
) |
| 599 |
), |
| 600 |
session=session, |
| 601 |
ignore_revision=ignore_revision, |
| 602 |
upsert=True, |
| 603 |
**kwargs, |
| 604 |
) |
| 605 |
|
| 606 |
@saved_state_needed |
| 607 |
@validate_self_before |
| 608 |
@wrap_with_actions(EventTypes.SAVE_CHANGES) |
| 609 |
async def save_changes( |
| 610 |
self: Self, |
| 611 |
ignore_revision: bool = False, |
| 612 |
session: AsyncClientSession | None = None, |
| 613 |
bulk_writer: BulkWriter | None = None, |
| 614 |
skip_actions: list[ActionDirections | str] | None = None, |
| 615 |
) -> Self | None: |
| 616 |
""" |
| 617 |
Save changes. |
| 618 |
State management usage must be turned on |
| 619 |
|
| 620 |
:param ignore_revision: bool - ignore revision id, if revision is turned on |
| 621 |
:param bulk_writer: "BulkWriter" - Beanie bulk writer |
| 622 |
:return: Optional[self] |
| 623 |
""" |
| 624 |
if not self.is_changed: |
| 625 |
return None |
| 626 |
changes = self.get_changes() |
| 627 |
if self.get_settings().keep_nulls is False: |
| 628 |
arguments: list[SetOperator | Unset] = [SetOperator(changes)] |
| 629 |
nones = get_top_level_nones(self) |
| 630 |
if nones: |
| 631 |
arguments.append(Unset(nones)) |
| 632 |
return await self.update( |
| 633 |
*arguments, |
| 634 |
ignore_revision=ignore_revision, |
| 635 |
session=session, |
| 636 |
bulk_writer=bulk_writer, |
| 637 |
) |
| 638 |
else: |
| 639 |
return await self.set( |
| 640 |
changes, |
| 641 |
ignore_revision=ignore_revision, |
| 642 |
session=session, |
| 643 |
bulk_writer=bulk_writer, |
| 644 |
) |
| 645 |
|
| 646 |
@classmethod |
| 647 |
async def replace_many( |
| 648 |
cls: type[DocType], |
| 649 |
documents: list[DocType], |
| 650 |
session: AsyncClientSession | None = None, |
| 651 |
) -> None: |
| 652 |
""" |
| 653 |
Replace list of documents |
| 654 |
|
| 655 |
:param documents: List["Document"] |
| 656 |
:param session: Optional[AsyncClientSession] - pymongo session. |
| 657 |
:return: None |
| 658 |
""" |
| 659 |
ids_list = [document.id for document in documents] |
| 660 |
if await cls.find(In(cls.id, ids_list)).count() != len(ids_list): |
| 661 |
raise ReplaceError( |
| 662 |
"Some of the documents are not exist in the collection" |
| 663 |
) |
| 664 |
async with BulkWriter(session=session) as bulk_writer: |
| 665 |
for document in documents: |
| 666 |
await document.replace( |
| 667 |
bulk_writer=bulk_writer, session=session |
| 668 |
) |
| 669 |
|
| 670 |
@save_state_after |
| 671 |
async def update( |
| 672 |
self: Self, |
| 673 |
*args: dict[Any, Any] | Mapping[Any, Any], |
| 674 |
ignore_revision: bool = False, |
| 675 |
session: AsyncClientSession | None = None, |
| 676 |
bulk_writer: BulkWriter | None = None, |
| 677 |
skip_actions: list[ActionDirections | str] | None = None, |
| 678 |
skip_sync: bool | None = None, |
| 679 |
**pymongo_kwargs: Any, |
| 680 |
) -> Self: |
| 681 |
""" |
| 682 |
Partially update the document in the database |
| 683 |
|
| 684 |
:param args: *Union[dict, Mapping] - the modifications to apply. |
| 685 |
:param session: AsyncClientSession - pymongo session. |
| 686 |
:param ignore_revision: bool - force update. Will update even if revision id is not the same, as stored |
| 687 |
:param bulk_writer: "BulkWriter" - Beanie bulk writer |
| 688 |
:param pymongo_kwargs: pymongo native parameters for update operation |
| 689 |
:return: self |
| 690 |
""" |
| 691 |
if skip_actions is None: |
| 692 |
skip_actions = [] |
| 693 |
|
| 694 |
if skip_sync is not None: |
| 695 |
raise DeprecationWarning( |
| 696 |
"skip_sync parameter is not supported. The document get synced always using atomic operation." |
| 697 |
) |
| 698 |
|
| 699 |
has_before_actions = ( |
| 700 |
ActionDirections.BEFORE not in skip_actions |
| 701 |
and bool( |
| 702 |
ActionRegistry.get_action_list( |
| 703 |
self.__class__, |
| 704 |
EventTypes.UPDATE, |
| 705 |
ActionDirections.BEFORE, |
| 706 |
) |
| 707 |
) |
| 708 |
) |
| 709 |
|
| 710 |
if has_before_actions: |
| 711 |
# Always diff with keep_nulls=True so that fields set to |
| 712 |
# None by a before_event handler are detected as changes |
| 713 |
# (they would be silently dropped with keep_nulls=False). |
| 714 |
pre_action_state = get_dict(self, to_db=True, keep_nulls=True) |
| 715 |
|
| 716 |
await ActionRegistry.run_actions( |
| 717 |
self, |
| 718 |
event_type=EventTypes.UPDATE, |
| 719 |
action_direction=ActionDirections.BEFORE, |
| 720 |
exclude=skip_actions, |
| 721 |
) |
| 722 |
|
| 723 |
post_action_state = get_dict(self, to_db=True, keep_nulls=True) |
| 724 |
action_changes = { |
| 725 |
key: value |
| 726 |
for key, value in post_action_state.items() |
| 727 |
if key not in ("_id", "revision_id") |
| 728 |
and pre_action_state.get(key) != value |
| 729 |
} |
| 730 |
else: |
| 731 |
await ActionRegistry.run_actions( |
| 732 |
self, |
| 733 |
event_type=EventTypes.UPDATE, |
| 734 |
action_direction=ActionDirections.BEFORE, |
| 735 |
exclude=skip_actions, |
| 736 |
) |
| 737 |
action_changes = {} |
| 738 |
|
| 739 |
arguments: list[Any] = list(args) |
| 740 |
if action_changes: |
| 741 |
arguments = merge_update_expressions( |
| 742 |
arguments, |
| 743 |
action_changes, |
| 744 |
strategy=self.get_settings().action_conflict_resolution, |
| 745 |
) |
| 746 |
|
| 747 |
use_revision_id = self.get_settings().use_revision |
| 748 |
|
| 749 |
if self.id is not None: |
| 750 |
find_query: dict[str, Any] = {"_id": self.id} |
| 751 |
else: |
| 752 |
find_query = {"_id": PydanticObjectId()} |
| 753 |
|
| 754 |
if use_revision_id and not ignore_revision: |
| 755 |
find_query["revision_id"] = self.revision_id |
| 756 |
|
| 757 |
if use_revision_id: |
| 758 |
new_revision_id = uuid4() |
| 759 |
arguments.append(SetRevisionId(new_revision_id)) |
| 760 |
try: |
| 761 |
result = await self.find_one(find_query).update( |
| 762 |
*arguments, |
| 763 |
session=session, |
| 764 |
response_type=UpdateResponse.NEW_DOCUMENT, |
| 765 |
bulk_writer=bulk_writer, |
| 766 |
**pymongo_kwargs, |
| 767 |
) |
| 768 |
except DuplicateKeyError as e: |
| 769 |
# A DuplicateKeyError on _id during an upsert with revision |
| 770 |
# filtering means the revision didn't match (the filter missed |
| 771 |
# the existing doc, so mongo tried to insert a duplicate _id). |
| 772 |
# A DuplicateKeyError on the revision_id key is also a |
| 773 |
# revision conflict. Any other DuplicateKeyError (e.g. on a |
| 774 |
# user-defined unique index) should propagate as-is. |
| 775 |
# |
| 776 |
# Use the structured `details` dict from PyMongo's WriteError |
| 777 |
# (keyPattern) instead of matching on the error message string, |
| 778 |
# which can vary across MongoDB versions. |
| 779 |
if use_revision_id and not ignore_revision: |
| 780 |
key_pattern = getattr(e, "details", {}).get("keyPattern", {}) |
| 781 |
if "_id" in key_pattern or "revision_id" in key_pattern: |
| 782 |
raise RevisionIdWasChanged |
| 783 |
raise |
| 784 |
if bulk_writer is None: |
| 785 |
if use_revision_id and not ignore_revision and result is None: |
| 786 |
raise RevisionIdWasChanged |
| 787 |
merge_models(self, result) |
| 788 |
|
| 789 |
await ActionRegistry.run_actions( |
| 790 |
self, |
| 791 |
event_type=EventTypes.UPDATE, |
| 792 |
action_direction=ActionDirections.AFTER, |
| 793 |
exclude=skip_actions, |
| 794 |
) |
| 795 |
|
| 796 |
return self |
| 797 |
|
| 798 |
@classmethod |
| 799 |
def update_all( |
| 800 |
cls, |
| 801 |
*args: dict | Mapping, |
| 802 |
session: AsyncClientSession | None = None, |
| 803 |
bulk_writer: BulkWriter | None = None, |
| 804 |
**pymongo_kwargs: Any, |
| 805 |
) -> UpdateMany: |
| 806 |
""" |
| 807 |
Partially update all the documents |
| 808 |
|
| 809 |
:param args: *Union[dict, Mapping] - the modifications to apply. |
| 810 |
:param session: AsyncClientSession - pymongo session. |
| 811 |
:param bulk_writer: "BulkWriter" - Beanie bulk writer |
| 812 |
:param **pymongo_kwargs: pymongo native parameters for find operation |
| 813 |
:return: UpdateMany query |
| 814 |
""" |
| 815 |
return cls.find_all().update_many( |
| 816 |
*args, session=session, bulk_writer=bulk_writer, **pymongo_kwargs |
| 817 |
) |
| 818 |
|
| 819 |
def set( |
| 820 |
self: Self, |
| 821 |
expression: dict[ExpressionField | str | Any, Any], |
| 822 |
session: AsyncClientSession | None = None, |
| 823 |
bulk_writer: BulkWriter | None = None, |
| 824 |
skip_sync: bool | None = None, |
| 825 |
**kwargs: Any, |
| 826 |
) -> Coroutine[None, None, Self]: |
| 827 |
""" |
| 828 |
Set values |
| 829 |
|
| 830 |
Example: |
| 831 |
|
| 832 |
```python |
| 833 |
|
| 834 |
class Sample(Document): |
| 835 |
one: int |
| 836 |
|
| 837 |
await Document.find(Sample.one == 1).set({Sample.one: 100}) |
| 838 |
|
| 839 |
``` |
| 840 |
|
| 841 |
Uses [Set operator](operators/update.md#set) |
| 842 |
|
| 843 |
:param expression: Dict[Union[ExpressionField, str, Any], Any] - keys and |
| 844 |
values to set |
| 845 |
:param session: Optional[AsyncClientSession] - pymongo session |
| 846 |
:param bulk_writer: Optional[BulkWriter] - bulk writer |
| 847 |
:param skip_sync: bool - skip doc syncing. Available for the direct instances only |
| 848 |
:return: self |
| 849 |
""" |
| 850 |
return self.update( |
| 851 |
SetOperator(expression), |
| 852 |
session=session, |
| 853 |
bulk_writer=bulk_writer, |
| 854 |
skip_sync=skip_sync, |
| 855 |
**kwargs, |
| 856 |
) |
| 857 |
|
| 858 |
def current_date( |
| 859 |
self: Self, |
| 860 |
expression: dict[datetime | ExpressionField | str, Any], |
| 861 |
session: AsyncClientSession | None = None, |
| 862 |
bulk_writer: BulkWriter | None = None, |
| 863 |
skip_sync: bool | None = None, |
| 864 |
**kwargs: Any, |
| 865 |
) -> Coroutine[None, None, Self]: |
| 866 |
""" |
| 867 |
Set current date |
| 868 |
|
| 869 |
Uses [CurrentDate operator](operators/update.md#currentdate) |
| 870 |
|
| 871 |
:param expression: Dict[Union[datetime, ExpressionField, str], Any] |
| 872 |
:param session: Optional[AsyncClientSession] - pymongo session |
| 873 |
:param bulk_writer: Optional[BulkWriter] - bulk writer |
| 874 |
:param skip_sync: bool - skip doc syncing. Available for the direct instances only |
| 875 |
:return: self |
| 876 |
""" |
| 877 |
return self.update( |
| 878 |
CurrentDate(expression), |
| 879 |
session=session, |
| 880 |
bulk_writer=bulk_writer, |
| 881 |
skip_sync=skip_sync, |
| 882 |
**kwargs, |
| 883 |
) |
| 884 |
|
| 885 |
def inc( |
| 886 |
self: Self, |
| 887 |
expression: dict[ExpressionField | float | int | str, Any], |
| 888 |
session: AsyncClientSession | None = None, |
| 889 |
bulk_writer: BulkWriter | None = None, |
| 890 |
skip_sync: bool | None = None, |
| 891 |
**kwargs: Any, |
| 892 |
) -> Coroutine[None, None, Self]: |
| 893 |
""" |
| 894 |
Increment |
| 895 |
|
| 896 |
Example: |
| 897 |
|
| 898 |
```python |
| 899 |
|
| 900 |
class Sample(Document): |
| 901 |
one: int |
| 902 |
|
| 903 |
await Document.find(Sample.one == 1).inc({Sample.one: 100}) |
| 904 |
|
| 905 |
``` |
| 906 |
|
| 907 |
Uses [Inc operator](operators/update.md#inc) |
| 908 |
|
| 909 |
:param expression: Dict[Union[ExpressionField, float, int, str], Any] |
| 910 |
:param session: Optional[AsyncClientSession] - pymongo session |
| 911 |
:param bulk_writer: Optional[BulkWriter] - bulk writer |
| 912 |
:param skip_sync: bool - skip doc syncing. Available for the direct instances only |
| 913 |
:return: self |
| 914 |
""" |
| 915 |
return self.update( |
| 916 |
Inc(expression), |
| 917 |
session=session, |
| 918 |
bulk_writer=bulk_writer, |
| 919 |
skip_sync=skip_sync, |
| 920 |
**kwargs, |
| 921 |
) |
| 922 |
|
| 923 |
@wrap_with_actions(EventTypes.DELETE) |
| 924 |
async def delete( |
| 925 |
self, |
| 926 |
session: AsyncClientSession | None = None, |
| 927 |
bulk_writer: BulkWriter | None = None, |
| 928 |
link_rule: DeleteRules = DeleteRules.DO_NOTHING, |
| 929 |
skip_actions: list[ActionDirections | str] | None = None, |
| 930 |
**pymongo_kwargs: Any, |
| 931 |
) -> DeleteResult | None: |
| 932 |
""" |
| 933 |
Delete the document |
| 934 |
|
| 935 |
:param session: Optional[AsyncClientSession] - pymongo session. |
| 936 |
:param bulk_writer: "BulkWriter" - Beanie bulk writer |
| 937 |
:param link_rule: DeleteRules - rules for link fields |
| 938 |
:param **pymongo_kwargs: pymongo native parameters for delete operation |
| 939 |
:return: Optional[DeleteResult] - pymongo DeleteResult instance. |
| 940 |
""" |
| 941 |
|
| 942 |
if link_rule is DeleteRules.DELETE_LINKS: |
| 943 |
link_fields = self.get_link_fields() |
| 944 |
if link_fields is not None: |
| 945 |
for field_info in link_fields.values(): |
| 946 |
value = getattr(self, field_info.field_name) |
| 947 |
if field_info.link_type in ( |
| 948 |
LinkTypes.DIRECT, |
| 949 |
LinkTypes.OPTIONAL_DIRECT, |
| 950 |
LinkTypes.BACK_DIRECT, |
| 951 |
LinkTypes.OPTIONAL_BACK_DIRECT, |
| 952 |
): |
| 953 |
if isinstance(value, Document): |
| 954 |
await value.delete( |
| 955 |
link_rule=DeleteRules.DELETE_LINKS, |
| 956 |
**pymongo_kwargs, |
| 957 |
) |
| 958 |
if field_info.link_type in ( |
| 959 |
LinkTypes.LIST, |
| 960 |
LinkTypes.OPTIONAL_LIST, |
| 961 |
LinkTypes.BACK_LIST, |
| 962 |
LinkTypes.OPTIONAL_BACK_LIST, |
| 963 |
): |
| 964 |
if isinstance(value, list): |
| 965 |
await asyncio.gather( |
| 966 |
*[ |
| 967 |
obj.delete( |
| 968 |
link_rule=DeleteRules.DELETE_LINKS, |
| 969 |
**pymongo_kwargs, |
| 970 |
) |
| 971 |
for obj in value |
| 972 |
if isinstance(obj, Document) |
| 973 |
] |
| 974 |
) |
| 975 |
|
| 976 |
return await self.find_one({"_id": self.id}).delete( |
| 977 |
session=session, bulk_writer=bulk_writer, **pymongo_kwargs |
| 978 |
) |
| 979 |
|
| 980 |
@classmethod |
| 981 |
async def delete_all( |
| 982 |
cls, |
| 983 |
session: AsyncClientSession | None = None, |
| 984 |
bulk_writer: BulkWriter | None = None, |
| 985 |
with_children: bool = False, |
| 986 |
**pymongo_kwargs: Any, |
| 987 |
) -> DeleteResult | None: |
| 988 |
""" |
| 989 |
Delete all the documents |
| 990 |
|
| 991 |
:param session: Optional[AsyncClientSession] - pymongo session. |
| 992 |
:param bulk_writer: "BulkWriter" - Beanie bulk writer |
| 993 |
:param **pymongo_kwargs: pymongo native parameters for delete operation |
| 994 |
:return: Optional[DeleteResult] - pymongo DeleteResult instance. |
| 995 |
""" |
| 996 |
return await cls.find_all(with_children=with_children).delete( |
| 997 |
session=session, bulk_writer=bulk_writer, **pymongo_kwargs |
| 998 |
) |
| 999 |
|
| 1000 |
# State management |
| 1001 |
|
| 1002 |
@classmethod |
| 1003 |
def use_state_management(cls) -> bool: |
| 1004 |
""" |
| 1005 |
Is state management turned on |
| 1006 |
:return: bool |
| 1007 |
""" |
| 1008 |
return cls.get_settings().use_state_management |
| 1009 |
|
| 1010 |
@classmethod |
| 1011 |
def state_management_save_previous(cls) -> bool: |
| 1012 |
""" |
| 1013 |
Should we save the previous state after a commit to database |
| 1014 |
:return: bool |
| 1015 |
""" |
| 1016 |
return cls.get_settings().state_management_save_previous |
| 1017 |
|
| 1018 |
@classmethod |
| 1019 |
def state_management_replace_objects(cls) -> bool: |
| 1020 |
""" |
| 1021 |
Should objects be replaced when using state management |
| 1022 |
:return: bool |
| 1023 |
""" |
| 1024 |
return cls.get_settings().state_management_replace_objects |
| 1025 |
|
| 1026 |
def _save_state(self) -> None: |
| 1027 |
""" |
| 1028 |
Save current document state. Internal method |
| 1029 |
:return: None |
| 1030 |
""" |
| 1031 |
if self.use_state_management() and self.id is not None: |
| 1032 |
if self.state_management_save_previous(): |
| 1033 |
self._previous_saved_state = self._saved_state |
| 1034 |
|
| 1035 |
self._saved_state = get_dict( |
| 1036 |
self, |
| 1037 |
to_db=True, |
| 1038 |
keep_nulls=self.get_settings().keep_nulls, |
| 1039 |
exclude={"revision_id"}, |
| 1040 |
) |
| 1041 |
|
| 1042 |
def get_saved_state(self) -> dict[str, Any] | None: |
| 1043 |
""" |
| 1044 |
Saved state getter. It is protected property. |
| 1045 |
:return: Optional[Dict[str, Any]] - saved state |
| 1046 |
""" |
| 1047 |
return self._saved_state |
| 1048 |
|
| 1049 |
def get_previous_saved_state(self) -> dict[str, Any] | None: |
| 1050 |
""" |
| 1051 |
Previous state getter. It is a protected property. |
| 1052 |
:return: Optional[Dict[str, Any]] - previous state |
| 1053 |
""" |
| 1054 |
return self._previous_saved_state |
| 1055 |
|
| 1056 |
@property |
| 1057 |
@saved_state_needed |
| 1058 |
def is_changed(self) -> bool: |
| 1059 |
return self._saved_state != get_dict( |
| 1060 |
self, |
| 1061 |
to_db=True, |
| 1062 |
keep_nulls=self.get_settings().keep_nulls, |
| 1063 |
exclude={"revision_id"}, |
| 1064 |
) |
| 1065 |
|
| 1066 |
@property |
| 1067 |
@saved_state_needed |
| 1068 |
@previous_saved_state_needed |
| 1069 |
def has_changed(self) -> bool: |
| 1070 |
if self._previous_saved_state is None: |
| 1071 |
return False |
| 1072 |
return self._previous_saved_state != self._saved_state |
| 1073 |
|
| 1074 |
def _collect_updates( |
| 1075 |
self, old_dict: dict[str, Any], new_dict: dict[str, Any] |
| 1076 |
) -> dict[str, Any]: |
| 1077 |
""" |
| 1078 |
Compares old_dict with new_dict and returns field paths that have been updated |
| 1079 |
Args: |
| 1080 |
old_dict: dict1 |
| 1081 |
new_dict: dict2 |
| 1082 |
|
| 1083 |
Returns: dictionary with updates |
| 1084 |
|
| 1085 |
""" |
| 1086 |
updates = {} |
| 1087 |
if old_dict.keys() - new_dict.keys(): |
| 1088 |
updates = new_dict |
| 1089 |
else: |
| 1090 |
for field_name, field_value in new_dict.items(): |
| 1091 |
if field_value != old_dict.get(field_name): |
| 1092 |
if not self.state_management_replace_objects() and ( |
| 1093 |
isinstance(field_value, dict) |
| 1094 |
and isinstance(old_dict.get(field_name), dict) |
| 1095 |
): |
| 1096 |
if old_dict.get(field_name) is None: |
| 1097 |
updates[field_name] = field_value |
| 1098 |
elif isinstance(field_value, dict) and isinstance( |
| 1099 |
old_dict.get(field_name), dict |
| 1100 |
): |
| 1101 |
field_data = self._collect_updates( |
| 1102 |
old_dict.get(field_name), # type: ignore |
| 1103 |
field_value, |
| 1104 |
) |
| 1105 |
|
| 1106 |
for k, v in field_data.items(): |
| 1107 |
updates[f"{field_name}.{k}"] = v |
| 1108 |
else: |
| 1109 |
updates[field_name] = field_value |
| 1110 |
|
| 1111 |
return updates |
| 1112 |
|
| 1113 |
@saved_state_needed |
| 1114 |
def get_changes(self) -> dict[str, Any]: |
| 1115 |
assert self._saved_state is not None |
| 1116 |
|
| 1117 |
return self._collect_updates( |
| 1118 |
self._saved_state, |
| 1119 |
get_dict( |
| 1120 |
self, |
| 1121 |
to_db=True, |
| 1122 |
keep_nulls=self.get_settings().keep_nulls, |
| 1123 |
exclude={"revision_id"}, |
| 1124 |
), |
| 1125 |
) |
| 1126 |
|
| 1127 |
@saved_state_needed |
| 1128 |
@previous_saved_state_needed |
| 1129 |
def get_previous_changes(self) -> dict[str, Any]: |
| 1130 |
assert self._saved_state is not None |
| 1131 |
|
| 1132 |
if self._previous_saved_state is None: |
| 1133 |
return {} |
| 1134 |
|
| 1135 |
return self._collect_updates( |
| 1136 |
self._previous_saved_state, |
| 1137 |
self._saved_state, |
| 1138 |
) |
| 1139 |
|
| 1140 |
@saved_state_needed |
| 1141 |
def rollback(self) -> None: |
| 1142 |
assert self._saved_state is not None |
| 1143 |
|
| 1144 |
if self.is_changed: |
| 1145 |
for key, value in self._saved_state.items(): |
| 1146 |
if key == "_id": |
| 1147 |
self.id = value |
| 1148 |
else: |
| 1149 |
setattr(self, key, value) |
| 1150 |
|
| 1151 |
# Other |
| 1152 |
|
| 1153 |
@classmethod |
| 1154 |
def get_settings(cls) -> DocumentSettings: |
| 1155 |
""" |
| 1156 |
Get document settings, which was created on |
| 1157 |
the initialization step |
| 1158 |
|
| 1159 |
:return: DocumentSettings class |
| 1160 |
""" |
| 1161 |
if cls._document_settings is None: |
| 1162 |
raise CollectionWasNotInitialized |
| 1163 |
return cls._document_settings |
| 1164 |
|
| 1165 |
@classmethod |
| 1166 |
async def inspect_collection( |
| 1167 |
cls, session: AsyncClientSession | None = None |
| 1168 |
) -> InspectionResult: |
| 1169 |
""" |
| 1170 |
Check, if documents, stored in the MongoDB collection |
| 1171 |
are compatible with the Document schema |
| 1172 |
|
| 1173 |
:param session: Optional[AsyncClientSession] - pymongo session |
| 1174 |
The session instance used for transactional operations. Defaults to None. |
| 1175 |
:return: InspectionResult |
| 1176 |
""" |
| 1177 |
inspection_result = InspectionResult() |
| 1178 |
async for json_document in cls.get_pymongo_collection().find( |
| 1179 |
{}, session=session |
| 1180 |
): |
| 1181 |
try: |
| 1182 |
parse_model(cls, json_document) |
| 1183 |
except ValidationError as e: |
| 1184 |
if inspection_result.status is InspectionStatuses.OK: |
| 1185 |
inspection_result.status = InspectionStatuses.FAIL |
| 1186 |
inspection_result.errors.append( |
| 1187 |
InspectionError( |
| 1188 |
document_id=json_document["_id"], error=str(e) |
| 1189 |
) |
| 1190 |
) |
| 1191 |
return inspection_result |
| 1192 |
|
| 1193 |
@classmethod |
| 1194 |
def _check_hidden_fields(cls): |
| 1195 |
hidden_fields = [ |
| 1196 |
(name, field) |
| 1197 |
for name, field in get_model_fields(cls).items() |
| 1198 |
if get_extra_field_info(field, "hidden") is True |
| 1199 |
] |
| 1200 |
if not hidden_fields: |
| 1201 |
return |
| 1202 |
warnings.warn( |
| 1203 |
f"{cls.__name__}: 'hidden=True' is deprecated, please use 'exclude=True'", |
| 1204 |
DeprecationWarning, |
| 1205 |
stacklevel=2, |
| 1206 |
) |
| 1207 |
for _name, field in hidden_fields: |
| 1208 |
field.exclude = True |
| 1209 |
del field.json_schema_extra["hidden"] |
| 1210 |
cls.model_rebuild(force=True) |
| 1211 |
|
| 1212 |
@wrap_with_actions(event_type=EventTypes.VALIDATE_ON_SAVE) |
| 1213 |
async def validate_self(self, *args: Any, **kwargs: Any): |
| 1214 |
# TODO: it can be sync, but needs some actions controller improvements |
| 1215 |
if self.get_settings().validate_on_save: |
| 1216 |
new_model = parse_model(self.__class__, get_model_dump(self)) |
| 1217 |
merge_models(self, new_model) |
| 1218 |
|
| 1219 |
def to_ref(self): |
| 1220 |
if self.id is None: |
| 1221 |
raise DocumentWasNotSaved("Can not create dbref without id") |
| 1222 |
return DBRef(self.get_pymongo_collection().name, self.id) |
| 1223 |
|
| 1224 |
async def fetch_link(self, field: str | Any): |
| 1225 |
"""Fetch a linked document by field name. |
| 1226 |
|
| 1227 |
Handles forward Links, BackLinks, and lists of either. |
| 1228 |
""" |
| 1229 |
ref_obj = getattr(self, field, None) |
| 1230 |
link_fields = self.get_link_fields() |
| 1231 |
link_info = link_fields.get(field) if link_fields else None |
| 1232 |
|
| 1233 |
# BackLink: query the other collection for documents pointing here |
| 1234 |
if link_info is not None and link_info.link_type in ( |
| 1235 |
LinkTypes.BACK_DIRECT, |
| 1236 |
LinkTypes.OPTIONAL_BACK_DIRECT, |
| 1237 |
): |
| 1238 |
if self.id is None: |
| 1239 |
return |
| 1240 |
query = {f"{link_info.lookup_field_name}.$id": self.id} |
| 1241 |
result = await link_info.document_class.find_one(query) |
| 1242 |
if result is not None: |
| 1243 |
setattr(self, field, result) |
| 1244 |
return |
| 1245 |
|
| 1246 |
if link_info is not None and link_info.link_type in ( |
| 1247 |
LinkTypes.BACK_LIST, |
| 1248 |
LinkTypes.OPTIONAL_BACK_LIST, |
| 1249 |
): |
| 1250 |
if self.id is None: |
| 1251 |
return |
| 1252 |
results = await link_info.document_class.find( |
| 1253 |
{f"{link_info.lookup_field_name}.$id": self.id}, |
| 1254 |
).to_list() |
| 1255 |
setattr(self, field, results) |
| 1256 |
return |
| 1257 |
|
| 1258 |
# Forward Link |
| 1259 |
if isinstance(ref_obj, Link): |
| 1260 |
value = await ref_obj.fetch(fetch_links=True) |
| 1261 |
setattr(self, field, value) |
| 1262 |
if isinstance(ref_obj, list) and ref_obj: |
| 1263 |
values = await Link.fetch_list(ref_obj, fetch_links=True) |
| 1264 |
setattr(self, field, values) |
| 1265 |
|
| 1266 |
async def fetch_all_links(self): |
| 1267 |
coros = [] |
| 1268 |
link_fields = self.get_link_fields() |
| 1269 |
if link_fields is not None: |
| 1270 |
for ref in link_fields.values(): |
| 1271 |
coros.append(self.fetch_link(ref.field_name)) # TODO lists |
| 1272 |
await asyncio.gather(*coros) |
| 1273 |
|
| 1274 |
@classmethod |
| 1275 |
def get_link_fields(cls) -> dict[str, LinkInfo] | None: |
| 1276 |
return cls._link_fields |
| 1277 |
|
| 1278 |
@classmethod |
| 1279 |
def get_model_type(cls) -> ModelType: |
| 1280 |
return ModelType.Document |
| 1281 |
|
| 1282 |
@classmethod |
| 1283 |
async def distinct( |
| 1284 |
cls, |
| 1285 |
key: str, |
| 1286 |
filter: Mapping[str, Any] | None = None, |
| 1287 |
session: AsyncClientSession | None = None, |
| 1288 |
**kwargs: Any, |
| 1289 |
) -> list: |
| 1290 |
return await cls.get_pymongo_collection().distinct( |
| 1291 |
key=key, filter=filter, session=session, **kwargs |
| 1292 |
) |
| 1293 |
|
| 1294 |
@classmethod |
| 1295 |
def link_from_id(cls, id: Any): |
| 1296 |
ref = DBRef(id=id, collection=cls.get_collection_name()) |
| 1297 |
return Link(ref, document_class=cls) |
| 1298 |
|
| 1299 |
@classmethod |
| 1300 |
def bulk_writer( |
| 1301 |
cls, |
| 1302 |
session: AsyncClientSession | None = None, |
| 1303 |
ordered: bool = True, |
| 1304 |
bypass_document_validation: bool | None = False, |
| 1305 |
comment: Any | None = None, |
| 1306 |
) -> BulkWriter: |
| 1307 |
""" |
| 1308 |
Returns a BulkWriter instance for handling bulk write operations. |
| 1309 |
|
| 1310 |
:param session: Optional[AsyncClientSession] - pymongo session. |
| 1311 |
The session instance used for transactional operations. |
| 1312 |
:param ordered: bool |
| 1313 |
If ``True`` (the default), requests will be performed on the server serially, in the order provided. If an error |
| 1314 |
occurs, all remaining operations are aborted. If ``False``, requests will be performed on the server in |
| 1315 |
arbitrary order, possibly in parallel, and all operations will be attempted. |
| 1316 |
:param bypass_document_validation: bool, optional |
| 1317 |
If ``True``, allows the write to opt-out of document-level validation. Default is ``False``. |
| 1318 |
:param comment: str, optional |
| 1319 |
A user-provided comment to attach to the BulkWriter. |
| 1320 |
|
| 1321 |
:returns: BulkWriter |
| 1322 |
An instance of BulkWriter configured with the provided settings. |
| 1323 |
|
| 1324 |
Example Usage: |
| 1325 |
This method is typically used within an asynchronous context manager. |
| 1326 |
|
| 1327 |
.. code-block:: python |
| 1328 |
|
| 1329 |
async with Document.bulk_writer(ordered=True) as bulk: |
| 1330 |
await Document.insert_one(Document(field="value"), bulk_writer=bulk) |
| 1331 |
""" |
| 1332 |
return BulkWriter( |
| 1333 |
session, ordered, cls, bypass_document_validation, comment |
| 1334 |
) |
| 1335 |
|
| 1336 |
|
| 1337 |
class DocumentWithSoftDelete(Document): |
| 1338 |
""" |
| 1339 |
Implements **soft deletion** for Beanie documents. |
| 1340 |
|
| 1341 |
Instead of permanently removing a document from the database, |
| 1342 |
this subclass marks the document as deleted by setting the |
| 1343 |
optional ``deleted_at`` field to the current UTC timestamp. Normal query |
| 1344 |
operations automatically exclude such documents, while special |
| 1345 |
query methods can retrieve them when needed. |
| 1346 |
|
| 1347 |
Fields: |
| 1348 |
|
| 1349 |
- `deleted_at` - marks the document as deleted by setting this field |
| 1350 |
to the current UTC timestamp |
| 1351 |
|
| 1352 |
""" |
| 1353 |
|
| 1354 |
deleted_at: datetime | None = None |
| 1355 |
|
| 1356 |
def is_deleted(self) -> bool: |
| 1357 |
""" |
| 1358 |
Returns whether the document has been soft-deleted. |
| 1359 |
|
| 1360 |
:returns: bool |
| 1361 |
``True`` if the document's ``deleted_at`` field is set; |
| 1362 |
otherwise ``False``. |
| 1363 |
""" |
| 1364 |
return self.deleted_at is not None |
| 1365 |
|
| 1366 |
async def hard_delete( |
| 1367 |
self, |
| 1368 |
session: AsyncClientSession | None = None, |
| 1369 |
bulk_writer: BulkWriter | None = None, |
| 1370 |
link_rule: DeleteRules = DeleteRules.DO_NOTHING, |
| 1371 |
skip_actions: list[ActionDirections | str] | None = None, |
| 1372 |
**pymongo_kwargs: Any, |
| 1373 |
) -> DeleteResult | None: |
| 1374 |
""" |
| 1375 |
Permanently deletes the document from the database, unlike :meth:`delete`. |
| 1376 |
|
| 1377 |
:param session: Optional[AsyncClientSession] |
| 1378 |
The MongoDB async session used for the operation. |
| 1379 |
:param bulk_writer: Optional[BulkWriter] |
| 1380 |
A bulk writer used for batching multiple write operations. |
| 1381 |
:param link_rule: DeleteRules |
| 1382 |
Determines how linked documents are handled. Defaults to ``DeleteRules.DO_NOTHING``. |
| 1383 |
:param skip_actions: Optional[List[Union[ActionDirections, str]]] |
| 1384 |
A list of lifecycle actions to skip during deletion. |
| 1385 |
:param **pymongo_kwargs: Any |
| 1386 |
Additional keyword arguments forwarded to PyMongo. |
| 1387 |
:returns: Optional[DeleteResult] |
| 1388 |
The result of the PyMongo delete operation, if available. |
| 1389 |
""" |
| 1390 |
return await super().delete( |
| 1391 |
session=session, |
| 1392 |
bulk_writer=bulk_writer, |
| 1393 |
link_rule=link_rule, |
| 1394 |
skip_actions=skip_actions, |
| 1395 |
**pymongo_kwargs, |
| 1396 |
) |
| 1397 |
|
| 1398 |
async def delete( |
| 1399 |
self, |
| 1400 |
session: AsyncClientSession | None = None, |
| 1401 |
bulk_writer: BulkWriter | None = None, |
| 1402 |
link_rule: DeleteRules = DeleteRules.DO_NOTHING, |
| 1403 |
skip_actions: list[ActionDirections | str] | None = None, |
| 1404 |
**pymongo_kwargs, |
| 1405 |
) -> DeleteResult | None: |
| 1406 |
""" |
| 1407 |
Overrides the base :meth:`delete`. |
| 1408 |
Marks the document as deleted by setting the ``deleted_at`` timestamp. |
| 1409 |
|
| 1410 |
|
| 1411 |
The document remains in the database but is excluded from all |
| 1412 |
standard queries such as :meth:`find`, :meth:`find_one`, and |
| 1413 |
:meth:`find_many`. |
| 1414 |
|
| 1415 |
:param session: Optional[AsyncClientSession] |
| 1416 |
The MongoDB async session used for the operation. |
| 1417 |
:param bulk_writer: Optional[BulkWriter] |
| 1418 |
A bulk writer used for batching multiple write operations. |
| 1419 |
:param link_rule: DeleteRules |
| 1420 |
Determines how linked documents are handled. Defaults to ``DeleteRules.DO_NOTHING``. |
| 1421 |
:param skip_actions: Optional[List[Union[ActionDirections, str]]] |
| 1422 |
A list of lifecycle actions to skip during deletion. |
| 1423 |
:param **pymongo_kwargs: Any |
| 1424 |
Additional keyword arguments forwarded to PyMongo. |
| 1425 |
:returns: None |
| 1426 |
""" |
| 1427 |
self.deleted_at = datetime.now(tz=timezone.utc) |
| 1428 |
await self.save() |
| 1429 |
return None |
| 1430 |
|
| 1431 |
@classmethod |
| 1432 |
def find_many_in_all( # type: ignore |
| 1433 |
cls: type[FindType], |
| 1434 |
*args: Mapping[Any, Any] | bool, |
| 1435 |
projection_model: type["DocumentProjectionType"] | None = None, |
| 1436 |
skip: int | None = None, |
| 1437 |
limit: int | None = None, |
| 1438 |
sort: None | str | list[tuple[str, SortDirection]] = None, |
| 1439 |
session: AsyncClientSession | None = None, |
| 1440 |
ignore_cache: bool = False, |
| 1441 |
fetch_links: bool = False, |
| 1442 |
with_children: bool = False, |
| 1443 |
lazy_parse: bool = False, |
| 1444 |
nesting_depth: int | None = None, |
| 1445 |
nesting_depths_per_field: dict[str, int] | None = None, |
| 1446 |
**pymongo_kwargs: Any, |
| 1447 |
) -> FindMany[FindType] | FindMany["DocumentProjectionType"]: |
| 1448 |
""" |
| 1449 |
Returns a query object including both active and soft-deleted documents. |
| 1450 |
|
| 1451 |
:returns: ``FindMany`` |
| 1452 |
A query object that includes both deleted and non-deleted documents. |
| 1453 |
""" |
| 1454 |
return cls._find_many_query_class(document_model=cls).find_many( |
| 1455 |
*args, |
| 1456 |
sort=sort, |
| 1457 |
skip=skip, |
| 1458 |
limit=limit, |
| 1459 |
projection_model=projection_model, |
| 1460 |
session=session, |
| 1461 |
ignore_cache=ignore_cache, |
| 1462 |
fetch_links=fetch_links, |
| 1463 |
lazy_parse=lazy_parse, |
| 1464 |
nesting_depth=nesting_depth, |
| 1465 |
nesting_depths_per_field=nesting_depths_per_field, |
| 1466 |
**pymongo_kwargs, |
| 1467 |
) |
| 1468 |
|
| 1469 |
@classmethod |
| 1470 |
def find_many( # type: ignore |
| 1471 |
cls: type[FindType], |
| 1472 |
*args: Mapping[Any, Any] | bool, |
| 1473 |
projection_model: type["DocumentProjectionType"] | None = None, |
| 1474 |
skip: int | None = None, |
| 1475 |
limit: int | None = None, |
| 1476 |
sort: None | str | list[tuple[str, SortDirection]] = None, |
| 1477 |
session: AsyncClientSession | None = None, |
| 1478 |
ignore_cache: bool = False, |
| 1479 |
fetch_links: bool = False, |
| 1480 |
with_children: bool = False, |
| 1481 |
lazy_parse: bool = False, |
| 1482 |
nesting_depth: int | None = None, |
| 1483 |
nesting_depths_per_field: dict[str, int] | None = None, |
| 1484 |
**pymongo_kwargs: Any, |
| 1485 |
) -> FindMany[FindType] | FindMany["DocumentProjectionType"]: |
| 1486 |
""" |
| 1487 |
Returns a query object that excludes soft-deleted documents. |
| 1488 |
|
| 1489 |
This overrides the base :meth:`find_many` method by automatically |
| 1490 |
applying a filter ``{"deleted_at": None}``. |
| 1491 |
|
| 1492 |
:returns: ``FindMany`` |
| 1493 |
A query object for fetching only non-deleted documents. |
| 1494 |
|
| 1495 |
""" |
| 1496 |
args = cls._add_class_id_filter(args, with_children) + ( |
| 1497 |
{"deleted_at": None}, |
| 1498 |
) |
| 1499 |
return cls._find_many_query_class(document_model=cls).find_many( |
| 1500 |
*args, |
| 1501 |
sort=sort, |
| 1502 |
skip=skip, |
| 1503 |
limit=limit, |
| 1504 |
projection_model=projection_model, |
| 1505 |
session=session, |
| 1506 |
ignore_cache=ignore_cache, |
| 1507 |
fetch_links=fetch_links, |
| 1508 |
lazy_parse=lazy_parse, |
| 1509 |
nesting_depth=nesting_depth, |
| 1510 |
nesting_depths_per_field=nesting_depths_per_field, |
| 1511 |
**pymongo_kwargs, |
| 1512 |
) |
| 1513 |
|
| 1514 |
@classmethod |
| 1515 |
def find_one( # type: ignore |
| 1516 |
cls: type[FindType], |
| 1517 |
*args: Mapping[Any, Any] | bool, |
| 1518 |
projection_model: type["DocumentProjectionType"] | None = None, |
| 1519 |
session: AsyncClientSession | None = None, |
| 1520 |
ignore_cache: bool = False, |
| 1521 |
fetch_links: bool = False, |
| 1522 |
with_children: bool = False, |
| 1523 |
nesting_depth: int | None = None, |
| 1524 |
nesting_depths_per_field: dict[str, int] | None = None, |
| 1525 |
**pymongo_kwargs: Any, |
| 1526 |
) -> FindOne[FindType] | FindOne["DocumentProjectionType"]: |
| 1527 |
""" |
| 1528 |
Returns a single document that has not been soft-deleted. |
| 1529 |
|
| 1530 |
This overrides the base :meth:`find_one` method by automatically |
| 1531 |
applying a filter ``{"deleted_at": None}``. |
| 1532 |
|
| 1533 |
:returns: ``FindOne`` |
| 1534 |
A query object for a single non-deleted document. |
| 1535 |
|
| 1536 |
""" |
| 1537 |
args = cls._add_class_id_filter(args, with_children) + ( |
| 1538 |
{"deleted_at": None}, |
| 1539 |
) |
| 1540 |
return cls._find_one_query_class(document_model=cls).find_one( |
| 1541 |
*args, |
| 1542 |
projection_model=projection_model, |
| 1543 |
session=session, |
| 1544 |
ignore_cache=ignore_cache, |
| 1545 |
fetch_links=fetch_links, |
| 1546 |
nesting_depth=nesting_depth, |
| 1547 |
nesting_depths_per_field=nesting_depths_per_field, |
| 1548 |
**pymongo_kwargs, |
| 1549 |
) |