Debian Codegraph @

beanie/odm/utils/state.py

raw
1 import inspect
2 from functools import wraps
3 from typing import TYPE_CHECKING, Any, TypeVar, cast, overload
4
5 from typing_extensions import ParamSpec
6
7 from beanie.exceptions import StateManagementIsTurnedOff, StateNotSaved
8
9 if TYPE_CHECKING:
10 from beanie import Document
11 from beanie.odm.documents import AnyDocMethod, AsyncDocMethod, DocType
12
13 P = ParamSpec("P")
14 R = TypeVar("R")
15
16
17 def check_if_state_saved(self: "DocType"):
18 if not self.use_state_management():
19 raise StateManagementIsTurnedOff(
20 "State management is turned off for this document"
21 )
22 if self._saved_state is None:
23 raise StateNotSaved("No state was saved")
24
25
26 @overload
27 def saved_state_needed(
28 f: "AsyncDocMethod[P, R]",
29 ) -> "AsyncDocMethod[P, R]": ...
30 @overload
31 def saved_state_needed(
32 f: "AnyDocMethod[P, R]",
33 ) -> "AnyDocMethod[P, R]": ...
34
35
36 def saved_state_needed(
37 f: "AnyDocMethod[P, Any]",
38 ) -> "AnyDocMethod[P, Any]":
39 @wraps(f)
40 def sync_wrapper(*args: P.args, **kwargs: P.kwargs) -> Any:
41 self = cast("Document", args[0])
42 check_if_state_saved(self)
43 return f(*args, **kwargs)
44
45 @wraps(f)
46 async def async_wrapper(*args: P.args, **kwargs: P.kwargs) -> Any:
47 self = cast("Document", args[0])
48 check_if_state_saved(self)
49 return await f(*args, **kwargs)
50
51 if inspect.iscoroutinefunction(f):
52 return async_wrapper
53 return sync_wrapper
54
55
56 def check_if_previous_state_saved(self: "DocType"):
57 if not self.use_state_management():
58 raise StateManagementIsTurnedOff(
59 "State management is turned off for this document"
60 )
61 if not self.state_management_save_previous():
62 raise StateManagementIsTurnedOff(
63 "State management's option to save previous state is turned off for this document"
64 )
65
66
67 @overload
68 def previous_saved_state_needed(
69 f: "AsyncDocMethod[P, R]",
70 ) -> "AsyncDocMethod[P, R]": ...
71 @overload
72 def previous_saved_state_needed(
73 f: "AnyDocMethod[P, R]",
74 ) -> "AnyDocMethod[P, R]": ...
75
76
77 def previous_saved_state_needed(
78 f: "AnyDocMethod[P, Any]",
79 ) -> "AnyDocMethod[P, Any]":
80 @wraps(f)
81 def sync_wrapper(*args: P.args, **kwargs: P.kwargs) -> Any:
82 self = cast("Document", args[0])
83 check_if_previous_state_saved(self)
84 return f(*args, **kwargs)
85
86 @wraps(f)
87 async def async_wrapper(*args: P.args, **kwargs: P.kwargs) -> Any:
88 self = cast("Document", args[0])
89 check_if_previous_state_saved(self)
90 return await f(*args, **kwargs)
91
92 if inspect.iscoroutinefunction(f):
93 return async_wrapper
94 return sync_wrapper
95
96
97 def save_state_after(
98 f: "AsyncDocMethod[P, R]",
99 ) -> "AsyncDocMethod[P, R]":
100 @wraps(f)
101 async def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
102 self = cast("Document", args[0])
103 result = await f(*args, **kwargs)
104 self._save_state()
105 return result
106
107 return wrapper