Debian Codegraph @

beanie/odm/queries/aggregation.py

raw
1 from collections.abc import Mapping
2 from typing import (
3 TYPE_CHECKING,
4 Any,
5 Generic,
6 TypeVar,
7 )
8
9 from pydantic import BaseModel
10
11 from beanie.odm.cache import LRUCache
12 from beanie.odm.interfaces.clone import CloneInterface
13 from beanie.odm.interfaces.session import SessionMethods
14 from beanie.odm.queries.cursor import BaseCursorQuery
15 from beanie.odm.utils.projection import get_projection
16
17 if TYPE_CHECKING:
18 from pymongo.asynchronous.command_cursor import AsyncCommandCursor
19
20 from beanie.odm.documents import DocType
21
22 AggregationProjectionType = TypeVar("AggregationProjectionType")
23
24
25 class AggregationQuery(
26 Generic[AggregationProjectionType],
27 BaseCursorQuery[AggregationProjectionType],
28 SessionMethods,
29 CloneInterface,
30 ):
31 """
32 Aggregation Query
33 """
34
35 def __init__(
36 self,
37 document_model: type["DocType"],
38 aggregation_pipeline: list[dict[str, Any]],
39 find_query: Mapping[str, Any],
40 projection_model: type[BaseModel] | None = None,
41 ignore_cache: bool = False,
42 **pymongo_kwargs: Any,
43 ):
44 self.aggregation_pipeline = aggregation_pipeline
45 self.document_model = document_model
46 self.projection_model = projection_model
47 self.find_query = find_query
48 self.session = None
49 self.ignore_cache = ignore_cache
50 self.pymongo_kwargs = pymongo_kwargs
51
52 @property
53 def _cache_key(self) -> str:
54 return LRUCache.create_key(
55 {
56 "type": "Aggregation",
57 "filter": self.find_query,
58 "pipeline": self.aggregation_pipeline,
59 "projection": get_projection(self.projection_model)
60 if self.projection_model
61 else None,
62 }
63 )
64
65 def _get_cache(self):
66 if (
67 self.document_model.get_settings().use_cache
68 and self.ignore_cache is False
69 ):
70 return self.document_model._cache.get(self._cache_key) # type: ignore
71 else:
72 return None
73
74 def _set_cache(self, data):
75 if (
76 self.document_model.get_settings().use_cache
77 and self.ignore_cache is False
78 ):
79 return self.document_model._cache.set(self._cache_key, data) # type: ignore
80
81 def get_aggregation_pipeline(
82 self,
83 ) -> list[dict[str, Any]]:
84 match_pipeline: list[dict[str, Any]] = (
85 [{"$match": self.find_query}] if self.find_query else []
86 )
87 projection_pipeline: list[dict[str, Any]] = []
88 if self.projection_model:
89 projection = get_projection(self.projection_model)
90 if projection is not None:
91 projection_pipeline = [{"$project": projection}]
92 return match_pipeline + self.aggregation_pipeline + projection_pipeline
93
94 async def get_cursor(self) -> "AsyncCommandCursor":
95 aggregation_pipeline = self.get_aggregation_pipeline()
96 return await self.document_model.get_pymongo_collection().aggregate(
97 aggregation_pipeline, session=self.session, **self.pymongo_kwargs
98 )
99
100 def get_projection_model(self) -> type[BaseModel] | None:
101 return self.projection_model