| 1 |
from abc import abstractmethod |
| 2 |
from collections.abc import Callable, Generator, Mapping |
| 3 |
from enum import Enum |
| 4 |
from typing import TYPE_CHECKING, Any |
| 5 |
|
| 6 |
from pymongo import ReturnDocument |
| 7 |
from pymongo import UpdateMany as UpdateManyPyMongo |
| 8 |
from pymongo import UpdateOne as UpdateOnePyMongo |
| 9 |
from pymongo.asynchronous.client_session import AsyncClientSession |
| 10 |
from pymongo.results import InsertOneResult, UpdateResult |
| 11 |
|
| 12 |
from beanie.odm.bulk import BulkWriter |
| 13 |
from beanie.odm.interfaces.clone import CloneInterface |
| 14 |
from beanie.odm.interfaces.session import SessionMethods |
| 15 |
from beanie.odm.interfaces.update import ( |
| 16 |
UpdateMethods, |
| 17 |
) |
| 18 |
from beanie.odm.operators.update import BaseUpdateOperator |
| 19 |
from beanie.odm.operators.update.general import SetRevisionId |
| 20 |
from beanie.odm.utils.encoder import Encoder |
| 21 |
from beanie.odm.utils.parsing import parse_obj |
| 22 |
|
| 23 |
if TYPE_CHECKING: |
| 24 |
from beanie.odm.documents import DocType |
| 25 |
|
| 26 |
|
| 27 |
class UpdateResponse(str, Enum): |
| 28 |
UPDATE_RESULT = "UPDATE_RESULT" # PyMongo update result |
| 29 |
OLD_DOCUMENT = "OLD_DOCUMENT" # Original document |
| 30 |
NEW_DOCUMENT = "NEW_DOCUMENT" # Updated document |
| 31 |
|
| 32 |
|
| 33 |
class UpdateQuery(UpdateMethods, SessionMethods, CloneInterface): |
| 34 |
""" |
| 35 |
Update Query base class |
| 36 |
""" |
| 37 |
|
| 38 |
def __init__( |
| 39 |
self, |
| 40 |
document_model: type["DocType"], |
| 41 |
find_query: Mapping[str, Any], |
| 42 |
): |
| 43 |
self.document_model = document_model |
| 44 |
self.find_query = find_query |
| 45 |
self.update_expressions: list[Mapping[str, Any]] = [] |
| 46 |
self.session = None |
| 47 |
self.is_upsert = False |
| 48 |
self.upsert_insert_doc: "DocType | None" = None # noqa: UP037 |
| 49 |
self.encoders: dict[Any, Callable[[Any], Any]] = {} |
| 50 |
self.bulk_writer: BulkWriter | None = None |
| 51 |
self.encoders = self.document_model.get_settings().bson_encoders |
| 52 |
self.pymongo_kwargs: dict[str, Any] = {} |
| 53 |
|
| 54 |
@property |
| 55 |
def update_query(self) -> dict[str, Any]: |
| 56 |
query: dict[str, Any] | list[dict[str, Any]] | None = None |
| 57 |
for expression in self.update_expressions: |
| 58 |
if isinstance(expression, BaseUpdateOperator): |
| 59 |
if query is None: |
| 60 |
query = {} |
| 61 |
if isinstance(query, list): |
| 62 |
raise TypeError("Wrong expression type") |
| 63 |
query.update(expression.query) |
| 64 |
elif isinstance(expression, dict): |
| 65 |
if query is None: |
| 66 |
query = {} |
| 67 |
if isinstance(query, list): |
| 68 |
raise TypeError("Wrong expression type") |
| 69 |
query.update(expression) |
| 70 |
elif isinstance(expression, SetRevisionId): |
| 71 |
if query is None: |
| 72 |
query = {} |
| 73 |
if isinstance(query, list): |
| 74 |
raise TypeError("Wrong expression type") |
| 75 |
set_query = query.get("$set", {}) |
| 76 |
set_query.update(expression.query.get("$set", {})) |
| 77 |
query["$set"] = set_query |
| 78 |
elif isinstance(expression, list): |
| 79 |
if query is None: |
| 80 |
query = [] |
| 81 |
if isinstance(query, dict): |
| 82 |
raise TypeError("Wrong expression type") |
| 83 |
query.extend(expression) |
| 84 |
else: |
| 85 |
raise TypeError("Wrong expression type") |
| 86 |
return Encoder(custom_encoders=self.encoders).encode(query) |
| 87 |
|
| 88 |
@abstractmethod |
| 89 |
async def _update(self) -> UpdateResult: ... |
| 90 |
|
| 91 |
|
| 92 |
class UpdateMany(UpdateQuery): |
| 93 |
""" |
| 94 |
Update Many query class |
| 95 |
""" |
| 96 |
|
| 97 |
def update( |
| 98 |
self, |
| 99 |
*args: Mapping[str, Any], |
| 100 |
session: AsyncClientSession | None = None, |
| 101 |
bulk_writer: BulkWriter | None = None, |
| 102 |
**pymongo_kwargs: Any, |
| 103 |
) -> "UpdateQuery": |
| 104 |
""" |
| 105 |
Provide modifications to the update query. |
| 106 |
|
| 107 |
:param args: *Union[dict, Mapping] - the modifications to apply. |
| 108 |
:param session: Optional[AsyncClientSession] - pymongo session |
| 109 |
:param bulk_writer: Optional[BulkWriter] |
| 110 |
:param pymongo_kwargs: pymongo native parameters for update operation |
| 111 |
:return: UpdateMany query |
| 112 |
""" |
| 113 |
self.set_session(session=session) |
| 114 |
self.update_expressions += args |
| 115 |
if bulk_writer: |
| 116 |
self.bulk_writer = bulk_writer |
| 117 |
self.pymongo_kwargs.update(pymongo_kwargs) |
| 118 |
return self |
| 119 |
|
| 120 |
def upsert( |
| 121 |
self, |
| 122 |
*args: Mapping[str, Any], |
| 123 |
on_insert: "DocType", |
| 124 |
session: AsyncClientSession | None = None, |
| 125 |
**pymongo_kwargs: Any, |
| 126 |
) -> "UpdateQuery": |
| 127 |
""" |
| 128 |
Provide modifications to the upsert query. |
| 129 |
|
| 130 |
:param args: *Union[dict, Mapping] - the modifications to apply. |
| 131 |
:param on_insert: DocType - document to insert if there is no matched |
| 132 |
document in the collection |
| 133 |
:param session: Optional[AsyncClientSession] - pymongo session |
| 134 |
:param **pymongo_kwargs: pymongo native parameters for update operation |
| 135 |
:return: UpdateMany query |
| 136 |
""" |
| 137 |
self.upsert_insert_doc = on_insert # type: ignore |
| 138 |
self.update(*args, session=session, **pymongo_kwargs) |
| 139 |
return self |
| 140 |
|
| 141 |
def update_many( |
| 142 |
self, |
| 143 |
*args: Mapping[str, Any], |
| 144 |
session: AsyncClientSession | None = None, |
| 145 |
bulk_writer: BulkWriter | None = None, |
| 146 |
**pymongo_kwargs: Any, |
| 147 |
): |
| 148 |
""" |
| 149 |
Provide modifications to the update query |
| 150 |
|
| 151 |
:param args: *Union[dict, Mapping] - the modifications to apply. |
| 152 |
:param session: Optional[AsyncClientSession] - pymongo session |
| 153 |
:param bulk_writer: "BulkWriter" - Beanie bulk writer |
| 154 |
:param pymongo_kwargs: pymongo native parameters for update operation |
| 155 |
:return: UpdateMany query |
| 156 |
""" |
| 157 |
return self.update( |
| 158 |
*args, session=session, bulk_writer=bulk_writer, **pymongo_kwargs |
| 159 |
) |
| 160 |
|
| 161 |
async def _update(self): |
| 162 |
if self.bulk_writer is None: |
| 163 |
return ( |
| 164 |
await self.document_model.get_pymongo_collection().update_many( |
| 165 |
self.find_query, |
| 166 |
self.update_query, |
| 167 |
session=self.session, |
| 168 |
**self.pymongo_kwargs, |
| 169 |
) |
| 170 |
) |
| 171 |
else: |
| 172 |
self.bulk_writer.add_operation( |
| 173 |
self.document_model, |
| 174 |
UpdateManyPyMongo( |
| 175 |
self.find_query, self.update_query, **self.pymongo_kwargs |
| 176 |
), |
| 177 |
) |
| 178 |
|
| 179 |
def __await__( |
| 180 |
self, |
| 181 |
) -> Generator[ |
| 182 |
Any, None, "UpdateResult | InsertOneResult | DocType | None" |
| 183 |
]: |
| 184 |
""" |
| 185 |
Run the query |
| 186 |
:return: |
| 187 |
""" |
| 188 |
|
| 189 |
update_result = yield from self._update().__await__() |
| 190 |
if self.upsert_insert_doc is None: |
| 191 |
return update_result |
| 192 |
|
| 193 |
if update_result is not None and update_result.matched_count == 0: |
| 194 |
return ( |
| 195 |
yield from self.document_model.insert_one( |
| 196 |
document=self.upsert_insert_doc, |
| 197 |
session=self.session, |
| 198 |
bulk_writer=self.bulk_writer, |
| 199 |
).__await__() |
| 200 |
) |
| 201 |
|
| 202 |
return update_result |
| 203 |
|
| 204 |
|
| 205 |
class UpdateOne(UpdateQuery): |
| 206 |
""" |
| 207 |
Update One query class |
| 208 |
""" |
| 209 |
|
| 210 |
def __init__(self, *args: Any, **kwargs: Any): |
| 211 |
super().__init__(*args, **kwargs) |
| 212 |
self.response_type = UpdateResponse.UPDATE_RESULT |
| 213 |
|
| 214 |
def update( |
| 215 |
self, |
| 216 |
*args: Mapping[str, Any], |
| 217 |
session: AsyncClientSession | None = None, |
| 218 |
bulk_writer: BulkWriter | None = None, |
| 219 |
response_type: UpdateResponse | None = None, |
| 220 |
**pymongo_kwargs: Any, |
| 221 |
) -> "UpdateQuery": |
| 222 |
""" |
| 223 |
Provide modifications to the update query. |
| 224 |
|
| 225 |
:param args: *Union[dict, Mapping] - the modifications to apply. |
| 226 |
:param session: Optional[AsyncClientSession] - pymongo session |
| 227 |
:param bulk_writer: Optional[BulkWriter] |
| 228 |
:param response_type: UpdateResponse |
| 229 |
:param pymongo_kwargs: pymongo native parameters for update operation |
| 230 |
:return: UpdateMany query |
| 231 |
""" |
| 232 |
self.set_session(session=session) |
| 233 |
self.update_expressions += args |
| 234 |
if response_type is not None: |
| 235 |
self.response_type = response_type |
| 236 |
if bulk_writer: |
| 237 |
self.bulk_writer = bulk_writer |
| 238 |
self.pymongo_kwargs.update(pymongo_kwargs) |
| 239 |
return self |
| 240 |
|
| 241 |
def upsert( |
| 242 |
self, |
| 243 |
*args: Mapping[str, Any], |
| 244 |
on_insert: "DocType", |
| 245 |
session: AsyncClientSession | None = None, |
| 246 |
response_type: UpdateResponse | None = None, |
| 247 |
**pymongo_kwargs: Any, |
| 248 |
) -> "UpdateQuery": |
| 249 |
""" |
| 250 |
Provide modifications to the upsert query. |
| 251 |
|
| 252 |
:param args: *Union[dict, Mapping] - the modifications to apply. |
| 253 |
:param on_insert: DocType - document to insert if there is no matched |
| 254 |
document in the collection |
| 255 |
:param session: Optional[AsyncClientSession] - pymongo session |
| 256 |
:param response_type: Optional[UpdateResponse] |
| 257 |
:param pymongo_kwargs: pymongo native parameters for update operation |
| 258 |
:return: UpdateMany query |
| 259 |
""" |
| 260 |
self.upsert_insert_doc = on_insert # type: ignore |
| 261 |
self.update( |
| 262 |
*args, |
| 263 |
response_type=response_type, |
| 264 |
session=session, |
| 265 |
**pymongo_kwargs, |
| 266 |
) |
| 267 |
return self |
| 268 |
|
| 269 |
def update_one( |
| 270 |
self, |
| 271 |
*args: Mapping[str, Any], |
| 272 |
session: AsyncClientSession | None = None, |
| 273 |
bulk_writer: BulkWriter | None = None, |
| 274 |
response_type: UpdateResponse | None = None, |
| 275 |
**pymongo_kwargs: Any, |
| 276 |
): |
| 277 |
""" |
| 278 |
Provide modifications to the update query. The same as `update()` |
| 279 |
|
| 280 |
:param args: *Union[dict, Mapping] - the modifications to apply. |
| 281 |
:param session: Optional[AsyncClientSession] - pymongo session |
| 282 |
:param bulk_writer: "BulkWriter" - Beanie bulk writer |
| 283 |
:param response_type: Optional[UpdateResponse] |
| 284 |
:param pymongo_kwargs: pymongo native parameters for update operation |
| 285 |
:return: UpdateMany query |
| 286 |
""" |
| 287 |
return self.update( |
| 288 |
*args, |
| 289 |
session=session, |
| 290 |
bulk_writer=bulk_writer, |
| 291 |
response_type=response_type, |
| 292 |
**pymongo_kwargs, |
| 293 |
) |
| 294 |
|
| 295 |
async def _update(self): |
| 296 |
if not self.bulk_writer: |
| 297 |
if self.response_type is UpdateResponse.UPDATE_RESULT: |
| 298 |
return await self.document_model.get_pymongo_collection().update_one( |
| 299 |
self.find_query, |
| 300 |
self.update_query, |
| 301 |
session=self.session, |
| 302 |
**self.pymongo_kwargs, |
| 303 |
) |
| 304 |
else: |
| 305 |
result = await self.document_model.get_pymongo_collection().find_one_and_update( |
| 306 |
self.find_query, |
| 307 |
self.update_query, |
| 308 |
session=self.session, |
| 309 |
return_document=( |
| 310 |
ReturnDocument.BEFORE |
| 311 |
if self.response_type is UpdateResponse.OLD_DOCUMENT |
| 312 |
else ReturnDocument.AFTER |
| 313 |
), |
| 314 |
**self.pymongo_kwargs, |
| 315 |
) |
| 316 |
if result is not None: |
| 317 |
result = parse_obj(self.document_model, result) |
| 318 |
return result |
| 319 |
else: |
| 320 |
self.bulk_writer.add_operation( |
| 321 |
self.document_model, |
| 322 |
UpdateOnePyMongo( |
| 323 |
self.find_query, self.update_query, **self.pymongo_kwargs |
| 324 |
), |
| 325 |
) |
| 326 |
|
| 327 |
def __await__( |
| 328 |
self, |
| 329 |
) -> Generator[ |
| 330 |
Any, None, "UpdateResult | InsertOneResult | DocType | None" |
| 331 |
]: |
| 332 |
""" |
| 333 |
Run the query |
| 334 |
:return: |
| 335 |
""" |
| 336 |
update_result = yield from self._update().__await__() |
| 337 |
if self.upsert_insert_doc is None: |
| 338 |
return update_result |
| 339 |
|
| 340 |
if ( |
| 341 |
self.response_type is UpdateResponse.UPDATE_RESULT |
| 342 |
and update_result is not None |
| 343 |
and update_result.matched_count == 0 |
| 344 |
) or ( |
| 345 |
self.response_type is not UpdateResponse.UPDATE_RESULT |
| 346 |
and update_result is None |
| 347 |
): |
| 348 |
return ( |
| 349 |
yield from self.document_model.insert_one( |
| 350 |
document=self.upsert_insert_doc, |
| 351 |
session=self.session, |
| 352 |
bulk_writer=self.bulk_writer, |
| 353 |
).__await__() |
| 354 |
) |
| 355 |
|
| 356 |
return update_result |