| 1 |
import asyncio |
| 2 |
from typing import Any, ClassVar |
| 3 |
|
| 4 |
from pydantic import BaseModel |
| 5 |
|
| 6 |
from beanie.exceptions import ViewWasNotInitialized |
| 7 |
from beanie.odm.fields import Link, LinkInfo |
| 8 |
from beanie.odm.interfaces.aggregate import AggregateInterface |
| 9 |
from beanie.odm.interfaces.detector import DetectionInterface, ModelType |
| 10 |
from beanie.odm.interfaces.find import FindInterface |
| 11 |
from beanie.odm.interfaces.getters import OtherGettersInterface |
| 12 |
from beanie.odm.settings.view import ViewSettings |
| 13 |
|
| 14 |
|
| 15 |
class View( |
| 16 |
BaseModel, |
| 17 |
FindInterface, |
| 18 |
AggregateInterface, |
| 19 |
OtherGettersInterface, |
| 20 |
DetectionInterface, |
| 21 |
): |
| 22 |
""" |
| 23 |
What is needed: |
| 24 |
|
| 25 |
Source collection or view |
| 26 |
pipeline |
| 27 |
|
| 28 |
""" |
| 29 |
|
| 30 |
# Database |
| 31 |
_database_major_version: ClassVar[int] = 4 |
| 32 |
|
| 33 |
# Relations |
| 34 |
_link_fields: ClassVar[dict[str, LinkInfo] | None] = None |
| 35 |
|
| 36 |
# Settings |
| 37 |
_settings: ClassVar[ViewSettings] |
| 38 |
|
| 39 |
@classmethod |
| 40 |
def get_settings(cls) -> ViewSettings: |
| 41 |
""" |
| 42 |
Get view settings, which was created on |
| 43 |
the initialization step |
| 44 |
|
| 45 |
:return: ViewSettings class |
| 46 |
""" |
| 47 |
if cls._settings is None: |
| 48 |
raise ViewWasNotInitialized |
| 49 |
return cls._settings |
| 50 |
|
| 51 |
async def fetch_link(self, field: str | Any): |
| 52 |
ref_obj = getattr(self, field, None) |
| 53 |
if isinstance(ref_obj, Link): |
| 54 |
value = await ref_obj.fetch(fetch_links=True) |
| 55 |
setattr(self, field, value) |
| 56 |
if isinstance(ref_obj, list) and ref_obj: |
| 57 |
values = await Link.fetch_list(ref_obj, fetch_links=True) |
| 58 |
setattr(self, field, values) |
| 59 |
|
| 60 |
async def fetch_all_links(self): |
| 61 |
coros = [] |
| 62 |
link_fields = self.get_link_fields() |
| 63 |
if link_fields is not None: |
| 64 |
for ref in link_fields.values(): |
| 65 |
coros.append(self.fetch_link(ref.field_name)) # TODO lists |
| 66 |
await asyncio.gather(*coros) |
| 67 |
|
| 68 |
@classmethod |
| 69 |
def get_link_fields(cls) -> dict[str, LinkInfo] | None: |
| 70 |
return cls._link_fields |
| 71 |
|
| 72 |
@classmethod |
| 73 |
def get_model_type(cls) -> ModelType: |
| 74 |
return ModelType.View |