Debian Codegraph @

beanie/odm/interfaces/find.py

raw
1 from abc import abstractmethod
2 from collections.abc import Iterable, Mapping
3 from typing import (
4 TYPE_CHECKING,
5 Any,
6 ClassVar,
7 TypeVar,
8 overload,
9 )
10
11 from pydantic import (
12 BaseModel,
13 )
14 from pymongo.asynchronous.client_session import AsyncClientSession
15
16 from beanie.odm.enums import SortDirection
17 from beanie.odm.interfaces.detector import ModelType
18 from beanie.odm.queries.find import FindMany, FindOne
19 from beanie.odm.settings.base import ItemSettings
20
21 if TYPE_CHECKING:
22 from beanie.odm.documents import Document
23 from beanie.odm.union_doc import UnionDoc
24 from beanie.odm.views import View
25
26 DocumentProjectionType = TypeVar("DocumentProjectionType", bound=BaseModel)
27 FindType = TypeVar("FindType", bound="Document | UnionDoc | View")
28
29
30 class FindInterface:
31 # Customization
32 # Query builders could be replaced in the inherited classes
33 _find_one_query_class: ClassVar[type] = FindOne
34 _find_many_query_class: ClassVar[type] = FindMany
35
36 _inheritance_inited: bool = False
37 _class_id: ClassVar[str | None]
38 _children: ClassVar[dict[str, type["Document"]]]
39
40 @classmethod
41 @abstractmethod
42 def get_model_type(cls) -> ModelType:
43 pass
44
45 @classmethod
46 @abstractmethod
47 def get_settings(cls) -> ItemSettings:
48 pass
49
50 @overload
51 @classmethod
52 def find_one( # type: ignore
53 cls: type[FindType],
54 *args: Mapping[Any, Any] | bool,
55 projection_model: None = None,
56 session: AsyncClientSession | None = None,
57 ignore_cache: bool = False,
58 fetch_links: bool = False,
59 with_children: bool = False,
60 nesting_depth: int | None = None,
61 nesting_depths_per_field: dict[str, int] | None = None,
62 **pymongo_kwargs: Any,
63 ) -> FindOne[FindType]: ...
64
65 @overload
66 @classmethod
67 def find_one( # type: ignore
68 cls: type[FindType],
69 *args: Mapping[Any, Any] | bool,
70 projection_model: type["DocumentProjectionType"],
71 session: AsyncClientSession | None = None,
72 ignore_cache: bool = False,
73 fetch_links: bool = False,
74 with_children: bool = False,
75 nesting_depth: int | None = None,
76 nesting_depths_per_field: dict[str, int] | None = None,
77 **pymongo_kwargs: Any,
78 ) -> FindOne["DocumentProjectionType"]: ...
79
80 @classmethod
81 def find_one( # type: ignore
82 cls: type[FindType],
83 *args: Mapping[Any, Any] | bool,
84 projection_model: type["DocumentProjectionType"] | None = None,
85 session: AsyncClientSession | None = None,
86 ignore_cache: bool = False,
87 fetch_links: bool = False,
88 with_children: bool = False,
89 nesting_depth: int | None = None,
90 nesting_depths_per_field: dict[str, int] | None = None,
91 **pymongo_kwargs: Any,
92 ) -> FindOne[FindType] | FindOne["DocumentProjectionType"]:
93 """
94 Find one document by criteria.
95 Returns [FindOne](query.md#findone) query object.
96 When awaited this will either return a document or None if no document exists for the search criteria.
97
98 :param args: *Mapping[Any, Any] - search criteria
99 :param projection_model: Optional[type[BaseModel]] - projection model
100 :param session: Optional[AsyncClientSession] - pymongo session.
101 :param ignore_cache: bool
102 :param **pymongo_kwargs: pymongo native parameters for find operation (if Document class contains links, this parameter must fit the respective parameter of the aggregate MongoDB function)
103 :return: [FindOne](query.md#findone) - find query instance
104 """
105 args = cls._add_class_id_filter(args, with_children)
106 return cls._find_one_query_class(document_model=cls).find_one(
107 *args,
108 projection_model=projection_model,
109 session=session,
110 ignore_cache=ignore_cache,
111 fetch_links=fetch_links,
112 nesting_depth=nesting_depth,
113 nesting_depths_per_field=nesting_depths_per_field,
114 **pymongo_kwargs,
115 )
116
117 @overload
118 @classmethod
119 def find_many( # type: ignore
120 cls: type[FindType],
121 *args: Mapping[Any, Any] | bool,
122 projection_model: None = None,
123 skip: int | None = None,
124 limit: int | None = None,
125 sort: str | list[tuple[str, SortDirection]] | None = None,
126 session: AsyncClientSession | None = None,
127 ignore_cache: bool = False,
128 fetch_links: bool = False,
129 with_children: bool = False,
130 lazy_parse: bool = False,
131 nesting_depth: int | None = None,
132 nesting_depths_per_field: dict[str, int] | None = None,
133 **pymongo_kwargs: Any,
134 ) -> FindMany[FindType]: ...
135
136 @overload
137 @classmethod
138 def find_many( # type: ignore
139 cls: type[FindType],
140 *args: Mapping[Any, Any] | bool,
141 projection_model: type["DocumentProjectionType"] | None = None,
142 skip: int | None = None,
143 limit: int | None = None,
144 sort: str | list[tuple[str, SortDirection]] | None = None,
145 session: AsyncClientSession | None = None,
146 ignore_cache: bool = False,
147 fetch_links: bool = False,
148 with_children: bool = False,
149 lazy_parse: bool = False,
150 nesting_depth: int | None = None,
151 nesting_depths_per_field: dict[str, int] | None = None,
152 **pymongo_kwargs: Any,
153 ) -> FindMany["DocumentProjectionType"]: ...
154
155 @classmethod
156 def find_many( # type: ignore
157 cls: type[FindType],
158 *args: Mapping[Any, Any] | bool,
159 projection_model: type["DocumentProjectionType"] | None = None,
160 skip: int | None = None,
161 limit: int | None = None,
162 sort: str | list[tuple[str, SortDirection]] | None = None,
163 session: AsyncClientSession | None = None,
164 ignore_cache: bool = False,
165 fetch_links: bool = False,
166 with_children: bool = False,
167 lazy_parse: bool = False,
168 nesting_depth: int | None = None,
169 nesting_depths_per_field: dict[str, int] | None = None,
170 **pymongo_kwargs: Any,
171 ) -> FindMany[FindType] | FindMany["DocumentProjectionType"]:
172 """
173 Find many documents by criteria.
174 Returns [FindMany](query.md#findmany) query object
175
176 :param args: *Mapping[Any, Any] - search criteria
177 :param skip: Optional[int] - The number of documents to omit.
178 :param limit: Optional[int] - The maximum number of results to return.
179 :param sort: Union[None, str, list[tuple[str, SortDirection]]] - A key or a list of (key, direction) pairs specifying the sort order for this query.
180 :param projection_model: Optional[type[BaseModel]] - projection model
181 :param session: Optional[AsyncClientSession] - pymongo session.
182 :param ignore_cache: bool
183 :param lazy_parse: bool
184 :param **pymongo_kwargs: pymongo native parameters for find operation (if Document class contains links, this parameter must fit the respective parameter of the aggregate MongoDB function)
185 :return: [FindMany](query.md#findmany) - query instance
186 """
187 args = cls._add_class_id_filter(args, with_children)
188 return cls._find_many_query_class(document_model=cls).find_many(
189 *args,
190 sort=sort,
191 skip=skip,
192 limit=limit,
193 projection_model=projection_model,
194 session=session,
195 ignore_cache=ignore_cache,
196 fetch_links=fetch_links,
197 lazy_parse=lazy_parse,
198 nesting_depth=nesting_depth,
199 nesting_depths_per_field=nesting_depths_per_field,
200 **pymongo_kwargs,
201 )
202
203 @overload
204 @classmethod
205 def find( # type: ignore
206 cls: type[FindType],
207 *args: Mapping[Any, Any] | bool,
208 projection_model: None = None,
209 skip: int | None = None,
210 limit: int | None = None,
211 sort: str | list[tuple[str, SortDirection]] | None = None,
212 session: AsyncClientSession | None = None,
213 ignore_cache: bool = False,
214 fetch_links: bool = False,
215 with_children: bool = False,
216 lazy_parse: bool = False,
217 nesting_depth: int | None = None,
218 nesting_depths_per_field: dict[str, int] | None = None,
219 **pymongo_kwargs: Any,
220 ) -> FindMany[FindType]: ...
221
222 @overload
223 @classmethod
224 def find( # type: ignore
225 cls: type[FindType],
226 *args: Mapping[Any, Any] | bool,
227 projection_model: type["DocumentProjectionType"],
228 skip: int | None = None,
229 limit: int | None = None,
230 sort: str | list[tuple[str, SortDirection]] | None = None,
231 session: AsyncClientSession | None = None,
232 ignore_cache: bool = False,
233 fetch_links: bool = False,
234 with_children: bool = False,
235 lazy_parse: bool = False,
236 nesting_depth: int | None = None,
237 nesting_depths_per_field: dict[str, int] | None = None,
238 **pymongo_kwargs: Any,
239 ) -> FindMany["DocumentProjectionType"]: ...
240
241 @classmethod
242 def find( # type: ignore
243 cls: type[FindType],
244 *args: Mapping[Any, Any] | bool,
245 projection_model: type["DocumentProjectionType"] | None = None,
246 skip: int | None = None,
247 limit: int | None = None,
248 sort: str | list[tuple[str, SortDirection]] | None = None,
249 session: AsyncClientSession | None = None,
250 ignore_cache: bool = False,
251 fetch_links: bool = False,
252 with_children: bool = False,
253 lazy_parse: bool = False,
254 nesting_depth: int | None = None,
255 nesting_depths_per_field: dict[str, int] | None = None,
256 **pymongo_kwargs: Any,
257 ) -> FindMany[FindType] | FindMany["DocumentProjectionType"]:
258 """
259 The same as find_many
260 """
261 return cls.find_many(
262 *args,
263 skip=skip,
264 limit=limit,
265 sort=sort,
266 projection_model=projection_model,
267 session=session,
268 ignore_cache=ignore_cache,
269 fetch_links=fetch_links,
270 with_children=with_children,
271 lazy_parse=lazy_parse,
272 nesting_depth=nesting_depth,
273 nesting_depths_per_field=nesting_depths_per_field,
274 **pymongo_kwargs,
275 )
276
277 @overload
278 @classmethod
279 def find_all( # type: ignore
280 cls: type[FindType],
281 skip: int | None = None,
282 limit: int | None = None,
283 sort: str | list[tuple[str, SortDirection]] | None = None,
284 projection_model: None = None,
285 session: AsyncClientSession | None = None,
286 ignore_cache: bool = False,
287 with_children: bool = False,
288 lazy_parse: bool = False,
289 nesting_depth: int | None = None,
290 nesting_depths_per_field: dict[str, int] | None = None,
291 **pymongo_kwargs: Any,
292 ) -> FindMany[FindType]: ...
293
294 @overload
295 @classmethod
296 def find_all( # type: ignore
297 cls: type[FindType],
298 skip: int | None = None,
299 limit: int | None = None,
300 sort: str | list[tuple[str, SortDirection]] | None = None,
301 projection_model: type["DocumentProjectionType"] | None = None,
302 session: AsyncClientSession | None = None,
303 ignore_cache: bool = False,
304 with_children: bool = False,
305 lazy_parse: bool = False,
306 nesting_depth: int | None = None,
307 nesting_depths_per_field: dict[str, int] | None = None,
308 **pymongo_kwargs: Any,
309 ) -> FindMany["DocumentProjectionType"]: ...
310
311 @classmethod
312 def find_all( # type: ignore
313 cls: type[FindType],
314 skip: int | None = None,
315 limit: int | None = None,
316 sort: str | list[tuple[str, SortDirection]] | None = None,
317 projection_model: type["DocumentProjectionType"] | None = None,
318 session: AsyncClientSession | None = None,
319 ignore_cache: bool = False,
320 with_children: bool = False,
321 lazy_parse: bool = False,
322 nesting_depth: int | None = None,
323 nesting_depths_per_field: dict[str, int] | None = None,
324 **pymongo_kwargs: Any,
325 ) -> FindMany[FindType] | FindMany["DocumentProjectionType"]:
326 """
327 Get all the documents
328
329 :param skip: Optional[int] - The number of documents to omit.
330 :param limit: Optional[int] - The maximum number of results to return.
331 :param sort: Union[None, str, list[tuple[str, SortDirection]]] - A key or a list of (key, direction) pairs specifying the sort order for this query.
332 :param projection_model: Optional[type[BaseModel]] - projection model
333 :param session: Optional[AsyncClientSession] - pymongo session.
334 :param **pymongo_kwargs: pymongo native parameters for find operation (if Document class contains links, this parameter must fit the respective parameter of the aggregate MongoDB function)
335 :return: [FindMany](query.md#findmany) - query instance
336 """
337 return cls.find_many(
338 {},
339 skip=skip,
340 limit=limit,
341 sort=sort,
342 projection_model=projection_model,
343 session=session,
344 ignore_cache=ignore_cache,
345 with_children=with_children,
346 lazy_parse=lazy_parse,
347 nesting_depth=nesting_depth,
348 nesting_depths_per_field=nesting_depths_per_field,
349 **pymongo_kwargs,
350 )
351
352 @overload
353 @classmethod
354 def all( # type: ignore
355 cls: type[FindType],
356 projection_model: None = None,
357 skip: int | None = None,
358 limit: int | None = None,
359 sort: str | list[tuple[str, SortDirection]] | None = None,
360 session: AsyncClientSession | None = None,
361 ignore_cache: bool = False,
362 with_children: bool = False,
363 lazy_parse: bool = False,
364 nesting_depth: int | None = None,
365 nesting_depths_per_field: dict[str, int] | None = None,
366 **pymongo_kwargs: Any,
367 ) -> FindMany[FindType]: ...
368
369 @overload
370 @classmethod
371 def all( # type: ignore
372 cls: type[FindType],
373 projection_model: type["DocumentProjectionType"],
374 skip: int | None = None,
375 limit: int | None = None,
376 sort: str | list[tuple[str, SortDirection]] | None = None,
377 session: AsyncClientSession | None = None,
378 ignore_cache: bool = False,
379 with_children: bool = False,
380 lazy_parse: bool = False,
381 nesting_depth: int | None = None,
382 nesting_depths_per_field: dict[str, int] | None = None,
383 **pymongo_kwargs: Any,
384 ) -> FindMany["DocumentProjectionType"]: ...
385
386 @classmethod
387 def all( # type: ignore
388 cls: type[FindType],
389 projection_model: type["DocumentProjectionType"] | None = None,
390 skip: int | None = None,
391 limit: int | None = None,
392 sort: str | list[tuple[str, SortDirection]] | None = None,
393 session: AsyncClientSession | None = None,
394 ignore_cache: bool = False,
395 with_children: bool = False,
396 lazy_parse: bool = False,
397 nesting_depth: int | None = None,
398 nesting_depths_per_field: dict[str, int] | None = None,
399 **pymongo_kwargs: Any,
400 ) -> FindMany[FindType] | FindMany["DocumentProjectionType"]:
401 """
402 the same as find_all
403 """
404 return cls.find_all(
405 skip=skip,
406 limit=limit,
407 sort=sort,
408 projection_model=projection_model,
409 session=session,
410 ignore_cache=ignore_cache,
411 with_children=with_children,
412 lazy_parse=lazy_parse,
413 nesting_depth=nesting_depth,
414 nesting_depths_per_field=nesting_depths_per_field,
415 **pymongo_kwargs,
416 )
417
418 @classmethod
419 async def count(cls) -> int:
420 """
421 Number of documents in the collections
422 The same as find_all().count()
423
424 :return: int
425 """
426 return await cls.find_all().count() # type: ignore
427
428 @classmethod
429 def _add_class_id_filter(cls, args: tuple, with_children: bool = False):
430 settings = cls.get_settings()
431 class_id = settings.class_id
432
433 # skip if _class_id is already added
434 if any(isinstance(a, Iterable) and class_id in a for a in args):
435 return args
436
437 if (
438 cls.get_model_type() is ModelType.Document
439 and cls._inheritance_inited
440 ):
441 if not with_children:
442 args += ({class_id: cls._class_id},)
443 else:
444 args += (
445 {
446 class_id: {
447 "$in": [cls._class_id]
448 + [cname for cname in cls._children]
449 }
450 },
451 )
452
453 if settings.union_doc:
454 args += ({class_id: settings.union_doc_alias},)
455 return args