Debian Codegraph @

beanie/odm/utils/relations.py

raw
1 from collections.abc import Mapping
2 from typing import TYPE_CHECKING, Any
3
4 from beanie.odm.fields import (
5 ExpressionField,
6 )
7
8 if TYPE_CHECKING:
9 from beanie import Document
10
11
12 def _translate_link_key(key: str, fetch_links: bool) -> str:
13 """Translate an ExpressionField path that crosses a Link boundary.
14
15 When the path was built through :pymethod:`ExpressionField.__getattr__`,
16 Pydantic alias resolution converts the ``id`` field to ``_id``. In
17 MongoDB, however, an unfetched Link is stored as a **DBRef** whose
18 identifier field is ``$id``, not ``_id``.
19
20 This function performs the conversion at query time so that:
21
22 * ``fetch_links=False`` -> ``door._id`` becomes ``door.$id``
23 * ``fetch_links=True`` -> ``door._id`` is kept as-is (the
24 ``$lookup`` stage replaces the DBRef with the full document).
25 """
26 if fetch_links:
27 return key
28 return key.replace("._id", ".$id")
29
30
31 def resolve_query_paths(
32 query: Mapping[str, Any],
33 doc: "Document",
34 fetch_links: bool,
35 ) -> dict[str, Any]:
36 """Resolve :class:`ExpressionField` paths for a MongoDB query.
37
38 Replaces the legacy ``convert_ids`` helper with a metadata-driven
39 approach: each :class:`ExpressionField` carries a
40 :class:`~beanie.odm.fields.FieldResolution` that records whether
41 the path crosses a ``Link`` / ``BackLink`` boundary. When it does,
42 the ``_id`` / ``$id`` translation is applied based on whether the
43 query will use ``$lookup`` (``fetch_links``).
44 """
45 new_query: dict[str, Any] = {}
46 for k, v in query.items():
47 if isinstance(k, ExpressionField) and k._field_resolution.is_link:
48 new_k = _translate_link_key(k, fetch_links)
49 else:
50 new_k = k
51
52 new_v: Any
53 if isinstance(v, Mapping):
54 new_v = resolve_query_paths(v, doc, fetch_links)
55 elif isinstance(v, list):
56 new_v = [
57 resolve_query_paths(ele, doc, fetch_links)
58 if isinstance(ele, Mapping)
59 else ele
60 for ele in v
61 ]
62 else:
63 new_v = v
64
65 new_query[new_k] = new_v
66 return new_query
67
68
69 def convert_ids(
70 query: Mapping[str, Any], doc: "Document", fetch_links: bool
71 ) -> dict[str, Any]:
72 """Deprecated -- use :func:`resolve_query_paths` instead."""
73 return resolve_query_paths(query, doc, fetch_links)