Debian Codegraph @

beanie/odm/union_doc.py

raw
1 from typing import Any, ClassVar, TypeVar
2
3 from pymongo.asynchronous.client_session import AsyncClientSession
4
5 from beanie.exceptions import UnionDocNotInited
6 from beanie.odm.bulk import BulkWriter
7 from beanie.odm.interfaces.aggregate import AggregateInterface
8 from beanie.odm.interfaces.detector import DetectionInterface, ModelType
9 from beanie.odm.interfaces.find import FindInterface
10 from beanie.odm.interfaces.getters import OtherGettersInterface
11 from beanie.odm.settings.union_doc import UnionDocSettings
12
13 UnionDocType = TypeVar("UnionDocType", bound="UnionDoc")
14
15
16 class UnionDoc(
17 FindInterface,
18 AggregateInterface,
19 OtherGettersInterface,
20 DetectionInterface,
21 ):
22 _document_models: ClassVar[dict[str, type] | None] = None
23 _is_inited: ClassVar[bool] = False
24 _settings: ClassVar[UnionDocSettings]
25
26 @classmethod
27 def get_settings(cls) -> UnionDocSettings:
28 return cls._settings
29
30 @classmethod
31 def register_doc(cls, name: str, doc_model: type):
32 if cls._document_models is None:
33 cls._document_models = {}
34
35 if cls._is_inited is False:
36 raise UnionDocNotInited
37
38 cls._document_models[name] = doc_model
39 return cls.get_settings().name
40
41 @classmethod
42 def get_model_type(cls) -> ModelType:
43 return ModelType.UnionDoc
44
45 @classmethod
46 def bulk_writer(
47 cls,
48 session: AsyncClientSession | None = None,
49 ordered: bool = True,
50 bypass_document_validation: bool = False,
51 comment: Any | None = None,
52 ) -> BulkWriter:
53 """
54 Returns a BulkWriter instance for handling bulk write operations.
55
56 :param session: Optional[AsyncClientSession] - pymongo session.
57 The session instance used for transactional operations.
58 :param ordered: bool
59 If ``True`` (the default), requests will be performed on the server serially, in the order provided. If an error
60 occurs, all remaining operations are aborted. If ``False``, requests will be performed on the server in
61 arbitrary order, possibly in parallel, and all operations will be attempted.
62 :param bypass_document_validation: bool, optional
63 If ``True``, allows the write to opt-out of document-level validation. Default is ``False``.
64 :param comment: str, optional
65 A user-provided comment to attach to the BulkWriter.
66
67 :returns: BulkWriter
68 An instance of BulkWriter configured with the provided settings.
69
70 Example Usage:
71 --------------
72 This method is typically used within an asynchronous context manager.
73
74 .. code-block:: python
75
76 async with Document.bulk_writer(ordered=True) as bulk:
77 await Document.insert_one(Document(field="value"), bulk_writer=bulk)
78 """
79 return BulkWriter(
80 session, ordered, cls, bypass_document_validation, comment
81 )