| 1 |
from abc import abstractmethod |
| 2 |
from typing import ( |
| 3 |
TYPE_CHECKING, |
| 4 |
Any, |
| 5 |
Generic, |
| 6 |
TypeVar, |
| 7 |
cast, |
| 8 |
) |
| 9 |
|
| 10 |
if TYPE_CHECKING: |
| 11 |
from pymongo.asynchronous.command_cursor import AsyncCommandCursor |
| 12 |
from pymongo.asynchronous.cursor import AsyncCursor |
| 13 |
|
| 14 |
from pydantic.main import BaseModel |
| 15 |
|
| 16 |
from beanie.odm.utils.parsing import parse_obj |
| 17 |
|
| 18 |
CursorResultType = TypeVar("CursorResultType") |
| 19 |
|
| 20 |
|
| 21 |
class BaseCursorQuery(Generic[CursorResultType]): |
| 22 |
""" |
| 23 |
BaseCursorQuery class. Wrapper over AsyncCursor, |
| 24 |
which parse result with model |
| 25 |
""" |
| 26 |
|
| 27 |
cursor = None |
| 28 |
lazy_parse = False |
| 29 |
|
| 30 |
@abstractmethod |
| 31 |
def get_projection_model(self) -> type[BaseModel] | None: ... |
| 32 |
|
| 33 |
@abstractmethod |
| 34 |
async def get_cursor( |
| 35 |
self, |
| 36 |
) -> "AsyncCommandCursor[dict[str, Any]] | AsyncCursor[dict[str, Any]] | None": ... |
| 37 |
|
| 38 |
def __aiter__(self): |
| 39 |
return self |
| 40 |
|
| 41 |
async def __anext__(self) -> CursorResultType: |
| 42 |
if self.cursor is None: |
| 43 |
self.cursor = await self.get_cursor() |
| 44 |
|
| 45 |
assert self.cursor is not None |
| 46 |
next_item = await self.cursor.__anext__() |
| 47 |
projection = self.get_projection_model() |
| 48 |
if projection is None: |
| 49 |
return next_item |
| 50 |
return parse_obj(projection, next_item, lazy_parse=self.lazy_parse) # type: ignore |
| 51 |
|
| 52 |
@abstractmethod |
| 53 |
def _get_cache(self) -> list[dict[str, Any]]: ... |
| 54 |
|
| 55 |
@abstractmethod |
| 56 |
def _set_cache(self, data): ... |
| 57 |
|
| 58 |
async def to_list( |
| 59 |
self, length: int | None = None |
| 60 |
) -> list[CursorResultType]: |
| 61 |
""" |
| 62 |
Get list of documents |
| 63 |
|
| 64 |
:param length: Optional[int] - length of the list |
| 65 |
:return: Union[List[BaseModel], List[Dict[str, Any]]] |
| 66 |
""" |
| 67 |
cursor = await self.get_cursor() |
| 68 |
pymongo_list: list[dict[str, Any]] = self._get_cache() |
| 69 |
|
| 70 |
if pymongo_list is None: |
| 71 |
pymongo_list = await cursor.to_list(length) |
| 72 |
self._set_cache(pymongo_list) |
| 73 |
projection = self.get_projection_model() |
| 74 |
if projection is not None: |
| 75 |
return cast( |
| 76 |
list[CursorResultType], |
| 77 |
[ |
| 78 |
parse_obj(projection, i, lazy_parse=self.lazy_parse) |
| 79 |
for i in pymongo_list |
| 80 |
], |
| 81 |
) |
| 82 |
return cast(list[CursorResultType], pymongo_list) |