| 1 |
from collections.abc import Mapping |
| 2 |
from types import TracebackType |
| 3 |
from typing import TYPE_CHECKING, Any, TypeAlias |
| 4 |
|
| 5 |
from pymongo import ( |
| 6 |
DeleteMany, |
| 7 |
DeleteOne, |
| 8 |
InsertOne, |
| 9 |
ReplaceOne, |
| 10 |
UpdateMany, |
| 11 |
UpdateOne, |
| 12 |
) |
| 13 |
from pymongo.asynchronous.client_session import AsyncClientSession |
| 14 |
from pymongo.results import BulkWriteResult |
| 15 |
from typing_extensions import Self |
| 16 |
|
| 17 |
if TYPE_CHECKING: |
| 18 |
from beanie import Document |
| 19 |
from beanie.odm.union_doc import UnionDoc |
| 20 |
|
| 21 |
_WriteOp: TypeAlias = ( |
| 22 |
InsertOne[Mapping[Any, Any]] |
| 23 |
| DeleteOne |
| 24 |
| DeleteMany |
| 25 |
| ReplaceOne[Mapping[Any, Any]] |
| 26 |
| UpdateOne |
| 27 |
| UpdateMany |
| 28 |
) |
| 29 |
|
| 30 |
|
| 31 |
class BulkWriter: |
| 32 |
""" |
| 33 |
A utility class for managing and executing bulk operations. |
| 34 |
|
| 35 |
This class facilitates the efficient execution of multiple database operations |
| 36 |
(e.g., inserts, updates, deletes, replacements) in a single batch. It supports asynchronous |
| 37 |
context management and ensures that all queued operations are committed upon exiting the context. |
| 38 |
|
| 39 |
Attributes: |
| 40 |
session Optional[AsyncClientSession]: |
| 41 |
The pymongo session used for transactional operations. |
| 42 |
Defaults to None, meaning no session is used. |
| 43 |
ordered Optional[bool]: |
| 44 |
Specifies whether operations are executed sequentially (default) or in parallel. |
| 45 |
- If True, operations are performed serially, stopping at the first failure. |
| 46 |
- If False, operations may be executed in arbitrary order, and all operations are attempted |
| 47 |
regardless of individual failures. |
| 48 |
bypass_document_validation Optional[bool]: |
| 49 |
If True, document-level validation is bypassed for all operations |
| 50 |
in the bulk write. This applies to MongoDB's schema validation rules, allowing documents that |
| 51 |
do not meet validation criteria to be inserted or modified. Defaults to False. |
| 52 |
comment Optional[Any]: |
| 53 |
A user-provided comment attached to the bulk operation command, useful for |
| 54 |
auditing and debugging purposes. |
| 55 |
operations List[Union[DeleteMany, DeleteOne, InsertOne, ReplaceOne, UpdateMany, UpdateOne]]: |
| 56 |
A list of MongoDB operations queued for bulk execution. |
| 57 |
object_class Type[Union[Document, UnionDoc]]: |
| 58 |
The document model class associated with the operations. |
| 59 |
|
| 60 |
Parameters: |
| 61 |
session Optional[AsyncClientSession]: The pymongo session for transaction support. |
| 62 |
Defaults to None (no session). |
| 63 |
ordered Optional[bool]: Specifies whether operations are executed in sequence (True) or in parallel (False). |
| 64 |
Defaults to True. |
| 65 |
bypass_document_validation Optional[bool]: Allows the bulk operation to bypass document-level validation. |
| 66 |
This is particularly useful when working with schemas that are being phased in or for bulk imports |
| 67 |
where strict validation may not be necessary. Defaults to False. |
| 68 |
comment Optional[Any]: A custom comment attached to the bulk operation. |
| 69 |
Defaults to None. |
| 70 |
object_class Type[Union[Document, UnionDoc]]: The document model class associated with the operations. |
| 71 |
""" |
| 72 |
|
| 73 |
def __init__( |
| 74 |
self, |
| 75 |
session: AsyncClientSession | None = None, |
| 76 |
ordered: bool = True, |
| 77 |
object_class: type["Document"] | type["UnionDoc"] | None = None, |
| 78 |
bypass_document_validation: bool | None = False, |
| 79 |
comment: Any | None = None, |
| 80 |
) -> None: |
| 81 |
self.operations: list[_WriteOp] = [] |
| 82 |
self.session = session |
| 83 |
self.ordered = ordered |
| 84 |
self.object_class = object_class |
| 85 |
self.bypass_document_validation = bypass_document_validation |
| 86 |
self.comment = comment |
| 87 |
self._collection_name: str | None = ( |
| 88 |
object_class.get_collection_name() if object_class else None |
| 89 |
) |
| 90 |
|
| 91 |
async def __aenter__(self) -> Self: |
| 92 |
return self |
| 93 |
|
| 94 |
async def __aexit__( |
| 95 |
self, |
| 96 |
exc_type: type[BaseException] | None, |
| 97 |
exc: BaseException | None, |
| 98 |
tb: TracebackType | None, |
| 99 |
) -> None: |
| 100 |
if exc_type is None: |
| 101 |
await self.commit() |
| 102 |
|
| 103 |
async def commit(self) -> BulkWriteResult | None: |
| 104 |
""" |
| 105 |
Commit all queued operations to the database. |
| 106 |
|
| 107 |
Executes all queued operations in a single bulk write request. If there |
| 108 |
are no operations to commit, it returns ``None``. |
| 109 |
|
| 110 |
:return: The result of the bulk write operation if operations are committed. |
| 111 |
Returns ``None`` if there are no operations to execute. |
| 112 |
:rtype: Optional[BulkWriteResult] |
| 113 |
|
| 114 |
:raises ValueError: |
| 115 |
If the object_class is not specified before committing. |
| 116 |
""" |
| 117 |
if not self.operations: |
| 118 |
return None |
| 119 |
if not self.object_class: |
| 120 |
raise ValueError( |
| 121 |
"The document model class must be specified before committing operations." |
| 122 |
) |
| 123 |
return await self.object_class.get_pymongo_collection().bulk_write( |
| 124 |
self.operations, |
| 125 |
ordered=self.ordered, |
| 126 |
bypass_document_validation=self.bypass_document_validation, |
| 127 |
session=self.session, |
| 128 |
comment=self.comment, |
| 129 |
) |
| 130 |
|
| 131 |
def add_operation( |
| 132 |
self, |
| 133 |
object_class: type["Document"] | type["UnionDoc"], |
| 134 |
operation: _WriteOp, |
| 135 |
): |
| 136 |
""" |
| 137 |
Add an operation to the queue. |
| 138 |
|
| 139 |
This method adds a MongoDB operation to the BulkWriter's operation queue. |
| 140 |
All operations in the queue must belong to the same collection. |
| 141 |
|
| 142 |
:param object_class: Type[Union[Document, UnionDoc]] |
| 143 |
The document model class associated with the operation. |
| 144 |
:param operation: Union[DeleteMany, DeleteOne, InsertOne, ReplaceOne, UpdateMany, UpdateOne] |
| 145 |
The MongoDB operation to add to the queue. |
| 146 |
:raises ValueError: |
| 147 |
If the collection differs from the one already associated with the BulkWriter. |
| 148 |
""" |
| 149 |
if self.object_class is None: |
| 150 |
self.object_class = object_class |
| 151 |
self._collection_name = object_class.get_collection_name() |
| 152 |
else: |
| 153 |
if object_class.get_collection_name() != self._collection_name: |
| 154 |
raise ValueError( |
| 155 |
"All the operations should be for a same collection name" |
| 156 |
) |
| 157 |
self.operations.append(operation) |