Debian Codegraph @

beanie/odm/utils/parsing.py

raw
1 from typing import TYPE_CHECKING, Any
2
3 from pydantic import BaseModel
4
5 from beanie.exceptions import (
6 ApplyChangesException,
7 DocWasNotRegisteredInUnionClass,
8 UnionHasNoRegisteredDocs,
9 )
10 from beanie.odm.interfaces.detector import ModelType
11 from beanie.odm.utils.pydantic import (
12 get_config_value,
13 get_model_fields,
14 parse_model,
15 )
16
17 if TYPE_CHECKING:
18 from beanie.odm.documents import Document
19
20
21 def _is_field_frozen(model: BaseModel, field_name: str) -> bool:
22 """Check if a specific field on a model is frozen."""
23 fields = get_model_fields(model)
24 field_info = fields.get(field_name)
25 if field_info is not None and field_info.frozen:
26 return True
27 return False
28
29
30 def _safe_setattr(model: BaseModel, field_name: str, value: Any) -> None:
31 """Set a field value, bypassing Pydantic validation for frozen fields."""
32 if _is_field_frozen(model, field_name):
33 # Bypass Pydantic's __setattr__ which raises ValidationError
34 # for frozen fields. This is safe because values being merged
35 # come from other already-validated models (e.g., DB-fetched
36 # documents or models built via model_dump), not from raw or
37 # otherwise untrusted user input.
38 object.__setattr__(model, field_name, value)
39 else:
40 model.__setattr__(field_name, value)
41
42
43 def merge_models(left: BaseModel, right: BaseModel) -> None:
44 """
45 Merge two models
46 :param left: left model
47 :param right: right model
48 :return: None
49 """
50 from beanie.odm.fields import BackLink, Link
51
52 # Use BaseModel.__iter__ to bypass custom __iter__ overrides
53 # (e.g. RootModel subclasses that yield non-tuple values).
54 for k, right_value in BaseModel.__iter__(right):
55 left_value = getattr(left, k, None)
56 if isinstance(right_value, BaseModel) and isinstance(
57 left_value, BaseModel
58 ):
59 if get_config_value(left_value, "frozen"):
60 _safe_setattr(left, k, right_value)
61 else:
62 merge_models(left_value, right_value)
63 continue
64 if isinstance(right_value, list):
65 if any(isinstance(i, (Link, BackLink)) for i in right_value):
66 continue
67 _safe_setattr(left, k, right_value)
68 elif not isinstance(right_value, (Link, BackLink)):
69 _safe_setattr(left, k, right_value)
70
71
72 def apply_changes(changes: dict[str, Any], target: BaseModel | dict[str, Any]):
73 for key, value in changes.items():
74 if "." in key:
75 key_parts = key.split(".")
76 current_target = target
77 try:
78 for part in key_parts[:-1]:
79 if isinstance(current_target, dict):
80 current_target = current_target[part]
81 elif isinstance(current_target, BaseModel):
82 current_target = getattr(current_target, part)
83 else:
84 raise ApplyChangesException(
85 f"Unexpected type of target: {type(target)}"
86 )
87 final_key = key_parts[-1]
88 if isinstance(current_target, dict):
89 current_target[final_key] = value
90 elif isinstance(current_target, BaseModel):
91 setattr(current_target, final_key, value)
92 else:
93 raise ApplyChangesException(
94 f"Unexpected type of target: {type(target)}"
95 )
96 except (KeyError, AttributeError) as e:
97 raise ApplyChangesException(
98 f"Failed to apply change for key '{key}': {e}"
99 )
100 else:
101 if isinstance(target, dict):
102 target[key] = value
103 elif isinstance(target, BaseModel):
104 setattr(target, key, value)
105 else:
106 raise ApplyChangesException(
107 f"Unexpected type of target: {type(target)}"
108 )
109
110
111 def save_state(item: BaseModel):
112 if hasattr(item, "_save_state"):
113 item._save_state() # type: ignore
114
115
116 def parse_obj(
117 model: type[BaseModel] | type["Document"],
118 data: Any,
119 lazy_parse: bool = False,
120 ) -> BaseModel:
121 if (
122 hasattr(model, "get_model_type")
123 and model.get_model_type() is ModelType.UnionDoc # type: ignore
124 ):
125 if model._document_models is None: # type: ignore
126 raise UnionHasNoRegisteredDocs
127
128 if isinstance(data, dict):
129 class_name = data[model.get_settings().class_id] # type: ignore
130 else:
131 class_name = data._class_id
132
133 if class_name not in model._document_models: # type: ignore
134 raise DocWasNotRegisteredInUnionClass
135 return parse_obj(
136 model=model._document_models[class_name], # type: ignore
137 data=data,
138 lazy_parse=lazy_parse,
139 ) # type: ignore
140 if (
141 hasattr(model, "get_model_type")
142 and model.get_model_type() is ModelType.Document # type: ignore
143 and model._inheritance_inited # type: ignore
144 ):
145 if isinstance(data, dict):
146 class_name = data.get(model.get_settings().class_id) # type: ignore
147 elif hasattr(data, model.get_settings().class_id): # type: ignore
148 class_name = data._class_id
149 else:
150 class_name = None
151
152 if model._children and class_name in model._children: # type: ignore
153 return parse_obj(
154 model=model._children[class_name], # type: ignore
155 data=data,
156 lazy_parse=lazy_parse,
157 ) # type: ignore
158
159 if (
160 lazy_parse
161 and hasattr(model, "get_model_type")
162 and model.get_model_type() is ModelType.Document # type: ignore
163 ):
164 o = model.lazy_parse(data, {"_id"}) # type: ignore
165 o._saved_state = {"_id": o.id}
166 return o
167 result = parse_model(model, data)
168 save_state(result)
169 return result