Coverage for mongodb_odm / utils / validation.py: 100%
25 statements
« prev ^ index » next coverage.py v7.12.0, created at 2025-12-07 08:37 +0000
« prev ^ index » next coverage.py v7.12.0, created at 2025-12-07 08:37 +0000
1from typing import Any 1fabcde
3from mongodb_odm.types import DICT_TYPE 1fabcde
4from mongodb_odm.utils.utils import get_model_fields, get_type_from_field 1fabcde
7def validate_filter_dict(model: Any, filter: DICT_TYPE) -> bool: 1fabcde
8 """
9 Field validation: Raise an error if a user passes a filter dict,
10 where the dict has some field that does not exist in the model.
12 This function will validate only the top level of the field.
13 It won't be looking into deep nested fields.
14 """
15 fields = model.get_parent_child_fields() 1fabcde
16 for key in filter.keys(): 1fabcde
17 if key[0] == "$": 1fabcde
18 # this is should be mongodb reserved keys like $or, $and, $text etc
19 continue 1fabcde
20 if key in fields or key == "_id": 1fabcde
21 # Valid single field
22 continue 1fabcde
23 if "." in key: 1fabcde
24 key_list = key.split(".") 1fabcde
25 first_key = key_list[0] 1fabcde
26 """ 1abcde
27 Here the first_key is the field that is defined in the top level of the model.
28 Not embedded/nested. But this field may contain nested data.
29 """
30 if first_key not in fields: 1fabcde
31 raise ValueError(f"Invalid key '{key}'. '{key_list[0]}' not found") 1fabcde
33 """ 1abcde
34 In this section, we will only check the embedded field.
35 """
36 temp_obj = get_type_from_field(fields[first_key]) 1fabcde
37 for nested_key in key_list[1:]: 1fabcde
38 if nested_key not in get_model_fields(temp_obj): 1fabcde
39 raise ValueError(f"Invalid key '{key}'. '{nested_key}' not found") 1fabcde
40 temp_obj = get_type_from_field(get_model_fields(temp_obj)[nested_key]) 1fabcde
41 continue 1fabcde
42 raise ValueError(f"Invalid key {key}") 1fabcde
44 return True 1fabcde