clear-skies 2.0.4__py3-none-any.whl → 2.0.5__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of clear-skies might be problematic. Click here for more details.

Files changed (253) hide show
  1. clear_skies-2.0.5.dist-info/METADATA +74 -0
  2. clear_skies-2.0.5.dist-info/RECORD +4 -0
  3. {clear_skies-2.0.4.dist-info → clear_skies-2.0.5.dist-info}/WHEEL +1 -1
  4. clear_skies-2.0.4.dist-info/METADATA +0 -36
  5. clear_skies-2.0.4.dist-info/RECORD +0 -251
  6. clearskies/__init__.py +0 -61
  7. clearskies/action.py +0 -7
  8. clearskies/authentication/__init__.py +0 -15
  9. clearskies/authentication/authentication.py +0 -46
  10. clearskies/authentication/authorization.py +0 -16
  11. clearskies/authentication/authorization_pass_through.py +0 -20
  12. clearskies/authentication/jwks.py +0 -163
  13. clearskies/authentication/public.py +0 -5
  14. clearskies/authentication/secret_bearer.py +0 -553
  15. clearskies/autodoc/__init__.py +0 -8
  16. clearskies/autodoc/formats/__init__.py +0 -5
  17. clearskies/autodoc/formats/oai3_json/__init__.py +0 -7
  18. clearskies/autodoc/formats/oai3_json/oai3_json.py +0 -87
  19. clearskies/autodoc/formats/oai3_json/oai3_schema_resolver.py +0 -15
  20. clearskies/autodoc/formats/oai3_json/parameter.py +0 -35
  21. clearskies/autodoc/formats/oai3_json/request.py +0 -68
  22. clearskies/autodoc/formats/oai3_json/response.py +0 -28
  23. clearskies/autodoc/formats/oai3_json/schema/__init__.py +0 -11
  24. clearskies/autodoc/formats/oai3_json/schema/array.py +0 -9
  25. clearskies/autodoc/formats/oai3_json/schema/default.py +0 -13
  26. clearskies/autodoc/formats/oai3_json/schema/enum.py +0 -7
  27. clearskies/autodoc/formats/oai3_json/schema/object.py +0 -35
  28. clearskies/autodoc/formats/oai3_json/test.json +0 -1985
  29. clearskies/autodoc/py.typed +0 -0
  30. clearskies/autodoc/request/__init__.py +0 -15
  31. clearskies/autodoc/request/header.py +0 -6
  32. clearskies/autodoc/request/json_body.py +0 -6
  33. clearskies/autodoc/request/parameter.py +0 -8
  34. clearskies/autodoc/request/request.py +0 -47
  35. clearskies/autodoc/request/url_parameter.py +0 -6
  36. clearskies/autodoc/request/url_path.py +0 -6
  37. clearskies/autodoc/response/__init__.py +0 -5
  38. clearskies/autodoc/response/response.py +0 -9
  39. clearskies/autodoc/schema/__init__.py +0 -31
  40. clearskies/autodoc/schema/array.py +0 -10
  41. clearskies/autodoc/schema/base64.py +0 -8
  42. clearskies/autodoc/schema/boolean.py +0 -5
  43. clearskies/autodoc/schema/date.py +0 -5
  44. clearskies/autodoc/schema/datetime.py +0 -5
  45. clearskies/autodoc/schema/double.py +0 -5
  46. clearskies/autodoc/schema/enum.py +0 -17
  47. clearskies/autodoc/schema/integer.py +0 -6
  48. clearskies/autodoc/schema/long.py +0 -5
  49. clearskies/autodoc/schema/number.py +0 -6
  50. clearskies/autodoc/schema/object.py +0 -13
  51. clearskies/autodoc/schema/password.py +0 -5
  52. clearskies/autodoc/schema/schema.py +0 -11
  53. clearskies/autodoc/schema/string.py +0 -5
  54. clearskies/backends/__init__.py +0 -65
  55. clearskies/backends/api_backend.py +0 -1178
  56. clearskies/backends/backend.py +0 -136
  57. clearskies/backends/cursor_backend.py +0 -335
  58. clearskies/backends/memory_backend.py +0 -797
  59. clearskies/backends/secrets_backend.py +0 -106
  60. clearskies/column.py +0 -1233
  61. clearskies/columns/__init__.py +0 -71
  62. clearskies/columns/audit.py +0 -206
  63. clearskies/columns/belongs_to_id.py +0 -483
  64. clearskies/columns/belongs_to_model.py +0 -132
  65. clearskies/columns/belongs_to_self.py +0 -105
  66. clearskies/columns/boolean.py +0 -113
  67. clearskies/columns/category_tree.py +0 -275
  68. clearskies/columns/category_tree_ancestors.py +0 -51
  69. clearskies/columns/category_tree_children.py +0 -127
  70. clearskies/columns/category_tree_descendants.py +0 -48
  71. clearskies/columns/created.py +0 -95
  72. clearskies/columns/created_by_authorization_data.py +0 -116
  73. clearskies/columns/created_by_header.py +0 -99
  74. clearskies/columns/created_by_ip.py +0 -92
  75. clearskies/columns/created_by_routing_data.py +0 -97
  76. clearskies/columns/created_by_user_agent.py +0 -92
  77. clearskies/columns/date.py +0 -234
  78. clearskies/columns/datetime.py +0 -282
  79. clearskies/columns/email.py +0 -76
  80. clearskies/columns/float.py +0 -153
  81. clearskies/columns/has_many.py +0 -505
  82. clearskies/columns/has_many_self.py +0 -56
  83. clearskies/columns/has_one.py +0 -14
  84. clearskies/columns/integer.py +0 -160
  85. clearskies/columns/json.py +0 -126
  86. clearskies/columns/many_to_many_ids.py +0 -337
  87. clearskies/columns/many_to_many_ids_with_data.py +0 -274
  88. clearskies/columns/many_to_many_models.py +0 -158
  89. clearskies/columns/many_to_many_pivots.py +0 -134
  90. clearskies/columns/phone.py +0 -159
  91. clearskies/columns/select.py +0 -92
  92. clearskies/columns/string.py +0 -102
  93. clearskies/columns/timestamp.py +0 -164
  94. clearskies/columns/updated.py +0 -110
  95. clearskies/columns/uuid.py +0 -86
  96. clearskies/configs/README.md +0 -105
  97. clearskies/configs/__init__.py +0 -162
  98. clearskies/configs/actions.py +0 -43
  99. clearskies/configs/any.py +0 -13
  100. clearskies/configs/any_dict.py +0 -22
  101. clearskies/configs/any_dict_or_callable.py +0 -23
  102. clearskies/configs/authentication.py +0 -23
  103. clearskies/configs/authorization.py +0 -23
  104. clearskies/configs/boolean.py +0 -16
  105. clearskies/configs/boolean_or_callable.py +0 -18
  106. clearskies/configs/callable_config.py +0 -18
  107. clearskies/configs/columns.py +0 -34
  108. clearskies/configs/conditions.py +0 -30
  109. clearskies/configs/config.py +0 -24
  110. clearskies/configs/datetime.py +0 -18
  111. clearskies/configs/datetime_or_callable.py +0 -19
  112. clearskies/configs/endpoint.py +0 -23
  113. clearskies/configs/endpoint_list.py +0 -28
  114. clearskies/configs/float.py +0 -16
  115. clearskies/configs/float_or_callable.py +0 -18
  116. clearskies/configs/integer.py +0 -16
  117. clearskies/configs/integer_or_callable.py +0 -18
  118. clearskies/configs/joins.py +0 -30
  119. clearskies/configs/list_any_dict.py +0 -30
  120. clearskies/configs/list_any_dict_or_callable.py +0 -31
  121. clearskies/configs/model_class.py +0 -35
  122. clearskies/configs/model_column.py +0 -65
  123. clearskies/configs/model_columns.py +0 -56
  124. clearskies/configs/model_destination_name.py +0 -25
  125. clearskies/configs/model_to_id_column.py +0 -43
  126. clearskies/configs/readable_model_column.py +0 -9
  127. clearskies/configs/readable_model_columns.py +0 -9
  128. clearskies/configs/schema.py +0 -23
  129. clearskies/configs/searchable_model_columns.py +0 -9
  130. clearskies/configs/security_headers.py +0 -39
  131. clearskies/configs/select.py +0 -26
  132. clearskies/configs/select_list.py +0 -47
  133. clearskies/configs/string.py +0 -29
  134. clearskies/configs/string_dict.py +0 -32
  135. clearskies/configs/string_list.py +0 -32
  136. clearskies/configs/string_list_or_callable.py +0 -35
  137. clearskies/configs/string_or_callable.py +0 -18
  138. clearskies/configs/timedelta.py +0 -18
  139. clearskies/configs/timezone.py +0 -18
  140. clearskies/configs/url.py +0 -23
  141. clearskies/configs/validators.py +0 -45
  142. clearskies/configs/writeable_model_column.py +0 -9
  143. clearskies/configs/writeable_model_columns.py +0 -9
  144. clearskies/configurable.py +0 -76
  145. clearskies/contexts/__init__.py +0 -11
  146. clearskies/contexts/cli.py +0 -117
  147. clearskies/contexts/context.py +0 -98
  148. clearskies/contexts/wsgi.py +0 -76
  149. clearskies/contexts/wsgi_ref.py +0 -82
  150. clearskies/decorators.py +0 -33
  151. clearskies/di/__init__.py +0 -14
  152. clearskies/di/additional_config.py +0 -130
  153. clearskies/di/additional_config_auto_import.py +0 -17
  154. clearskies/di/di.py +0 -973
  155. clearskies/di/inject/__init__.py +0 -23
  156. clearskies/di/inject/by_class.py +0 -21
  157. clearskies/di/inject/by_name.py +0 -18
  158. clearskies/di/inject/di.py +0 -13
  159. clearskies/di/inject/environment.py +0 -14
  160. clearskies/di/inject/input_output.py +0 -20
  161. clearskies/di/inject/now.py +0 -13
  162. clearskies/di/inject/requests.py +0 -13
  163. clearskies/di/inject/secrets.py +0 -14
  164. clearskies/di/inject/utcnow.py +0 -13
  165. clearskies/di/inject/uuid.py +0 -15
  166. clearskies/di/injectable.py +0 -29
  167. clearskies/di/injectable_properties.py +0 -131
  168. clearskies/di/test_module/__init__.py +0 -6
  169. clearskies/di/test_module/another_module/__init__.py +0 -2
  170. clearskies/di/test_module/module_class.py +0 -5
  171. clearskies/end.py +0 -183
  172. clearskies/endpoint.py +0 -1314
  173. clearskies/endpoint_group.py +0 -338
  174. clearskies/endpoints/__init__.py +0 -25
  175. clearskies/endpoints/advanced_search.py +0 -526
  176. clearskies/endpoints/callable.py +0 -388
  177. clearskies/endpoints/create.py +0 -205
  178. clearskies/endpoints/delete.py +0 -139
  179. clearskies/endpoints/get.py +0 -271
  180. clearskies/endpoints/health_check.py +0 -183
  181. clearskies/endpoints/list.py +0 -574
  182. clearskies/endpoints/restful_api.py +0 -427
  183. clearskies/endpoints/schema.py +0 -189
  184. clearskies/endpoints/simple_search.py +0 -286
  185. clearskies/endpoints/update.py +0 -193
  186. clearskies/environment.py +0 -104
  187. clearskies/exceptions/__init__.py +0 -19
  188. clearskies/exceptions/authentication.py +0 -2
  189. clearskies/exceptions/authorization.py +0 -2
  190. clearskies/exceptions/client_error.py +0 -2
  191. clearskies/exceptions/input_errors.py +0 -4
  192. clearskies/exceptions/missing_dependency.py +0 -2
  193. clearskies/exceptions/moved_permanently.py +0 -3
  194. clearskies/exceptions/moved_temporarily.py +0 -3
  195. clearskies/exceptions/not_found.py +0 -2
  196. clearskies/functional/__init__.py +0 -7
  197. clearskies/functional/routing.py +0 -92
  198. clearskies/functional/string.py +0 -112
  199. clearskies/functional/validations.py +0 -76
  200. clearskies/input_outputs/__init__.py +0 -13
  201. clearskies/input_outputs/cli.py +0 -171
  202. clearskies/input_outputs/exceptions/__init__.py +0 -2
  203. clearskies/input_outputs/exceptions/cli_input_error.py +0 -2
  204. clearskies/input_outputs/exceptions/cli_not_found.py +0 -2
  205. clearskies/input_outputs/headers.py +0 -45
  206. clearskies/input_outputs/input_output.py +0 -138
  207. clearskies/input_outputs/programmatic.py +0 -69
  208. clearskies/input_outputs/py.typed +0 -0
  209. clearskies/input_outputs/wsgi.py +0 -77
  210. clearskies/model.py +0 -1922
  211. clearskies/py.typed +0 -0
  212. clearskies/query/__init__.py +0 -12
  213. clearskies/query/condition.py +0 -223
  214. clearskies/query/join.py +0 -136
  215. clearskies/query/query.py +0 -196
  216. clearskies/query/sort.py +0 -27
  217. clearskies/schema.py +0 -82
  218. clearskies/secrets/__init__.py +0 -6
  219. clearskies/secrets/additional_configs/__init__.py +0 -32
  220. clearskies/secrets/additional_configs/mysql_connection_dynamic_producer.py +0 -61
  221. clearskies/secrets/additional_configs/mysql_connection_dynamic_producer_via_ssh_cert_bastion.py +0 -160
  222. clearskies/secrets/akeyless.py +0 -182
  223. clearskies/secrets/exceptions/__init__.py +0 -1
  224. clearskies/secrets/exceptions/not_found.py +0 -2
  225. clearskies/secrets/secrets.py +0 -38
  226. clearskies/security_header.py +0 -15
  227. clearskies/security_headers/__init__.py +0 -11
  228. clearskies/security_headers/cache_control.py +0 -67
  229. clearskies/security_headers/cors.py +0 -50
  230. clearskies/security_headers/csp.py +0 -94
  231. clearskies/security_headers/hsts.py +0 -22
  232. clearskies/security_headers/x_content_type_options.py +0 -0
  233. clearskies/security_headers/x_frame_options.py +0 -0
  234. clearskies/test_base.py +0 -8
  235. clearskies/typing.py +0 -11
  236. clearskies/validator.py +0 -37
  237. clearskies/validators/__init__.py +0 -33
  238. clearskies/validators/after_column.py +0 -62
  239. clearskies/validators/before_column.py +0 -13
  240. clearskies/validators/in_the_future.py +0 -32
  241. clearskies/validators/in_the_future_at_least.py +0 -11
  242. clearskies/validators/in_the_future_at_most.py +0 -10
  243. clearskies/validators/in_the_past.py +0 -32
  244. clearskies/validators/in_the_past_at_least.py +0 -10
  245. clearskies/validators/in_the_past_at_most.py +0 -10
  246. clearskies/validators/maximum_length.py +0 -26
  247. clearskies/validators/maximum_value.py +0 -29
  248. clearskies/validators/minimum_length.py +0 -26
  249. clearskies/validators/minimum_value.py +0 -29
  250. clearskies/validators/required.py +0 -34
  251. clearskies/validators/timedelta.py +0 -59
  252. clearskies/validators/unique.py +0 -30
  253. {clear_skies-2.0.4.dist-info → clear_skies-2.0.5.dist-info/licenses}/LICENSE +0 -0
@@ -1,797 +0,0 @@
1
- import inspect
2
- from functools import cmp_to_key
3
- from typing import Any, Callable
4
-
5
- import clearskies.model
6
- import clearskies.query
7
- from clearskies import functional
8
- from clearskies.autodoc.schema import Integer as AutoDocInteger
9
- from clearskies.autodoc.schema import Schema as AutoDocSchema
10
- from clearskies.backends.backend import Backend
11
- from clearskies.di import InjectableProperties, inject
12
-
13
-
14
- class Null:
15
- def __lt__(self, other):
16
- return True
17
-
18
- def __gt__(self, other):
19
- return False
20
-
21
- def __eq__(self, other):
22
- return isinstance(other, Null) or other is None
23
-
24
-
25
- # for some comparisons we prefer comparing floats, but we need to be able to
26
- # fall back on string comparison
27
- def gentle_float_conversion(value):
28
- try:
29
- return float(value)
30
- except:
31
- return value
32
-
33
-
34
- def _sort(row_a: Any, row_b: Any, sorts: list[clearskies.query.Sort], default_table_name: str) -> int:
35
- for sort in sorts:
36
- # so, if we've done a join then the rows will have data from all joined tables via a dict of dicts.
37
- # if there wasn't a join then we'll just have the data
38
- if sort.table_name in row_a and isinstance(row_a[sort.table_name], dict):
39
- sort_data_a = row_a[sort.table_name]
40
- elif not sort.table_name and default_table_name in row_a and isinstance(row_a[default_table_name], dict):
41
- sort_data_a = row_a[default_table_name]
42
- else:
43
- sort_data_a = row_a
44
-
45
- if sort.table_name in row_b and isinstance(row_b[sort.table_name], dict):
46
- sort_data_b = row_b[sort.table_name]
47
- elif not sort.table_name and default_table_name in row_b and isinstance(row_b[default_table_name], dict):
48
- sort_data_b = row_b[default_table_name]
49
- else:
50
- sort_data_b = row_b
51
-
52
- reverse = 1 if sort.direction.lower() == "asc" else -1
53
- value_a = sort_data_a[sort.column_name] if sort.column_name in sort_data_a else None
54
- value_b = sort_data_b[sort.column_name] if sort.column_name in sort_data_b else None
55
- if value_a == value_b:
56
- continue
57
- if value_a is None:
58
- return -1 * reverse
59
- if value_b is None:
60
- return 1 * reverse
61
- return reverse * (1 if value_a > value_b else -1)
62
- return 0
63
-
64
-
65
- def cheating_equals(column, values, null):
66
- """
67
- Cheating because this solves a very specific problem that likely is a generic issue.
68
-
69
- The memory backend has some matching failures because boolean columns stay boolean in the
70
- memory store, but the incoming search values are not converted to boolean and tend to be
71
- str(1) or str(0). The issue is that save data goes through the `to_backend` flow, but search
72
- data doesn't. This doesn't matter most of the time because, in practice, the backend itself
73
- often does its own type conversion, but it causes problems for the memory backend. I can't
74
- decide if fixing this will cause more problems than it solves, so for now I'm just cheating
75
- and putting in a hack for this specific use case :shame:.
76
- """
77
-
78
- def inner(row):
79
- backend_value = row[column] if column in row else null
80
- if isinstance(backend_value, bool):
81
- return backend_value == bool(values[0])
82
- return str(backend_value) == str(values[0])
83
-
84
- return inner
85
-
86
-
87
- class MemoryTable:
88
- _table_name: str = ""
89
- _column_names: list[str] = []
90
- _rows: list[dict[str, Any] | None] = []
91
- null: Null = Null()
92
- _id_index: dict[int | str, int] = {}
93
- id_column_name: str = ""
94
- _next_id: int = 1
95
- _model_class: type[clearskies.model.Model] = None # type: ignore
96
-
97
- # here be dragons. This is not a 100% drop-in replacement for the equivalent SQL operators
98
- # https://codereview.stackexchange.com/questions/259198/in-memory-table-filtering-in-python
99
- _operator_lambda_builders = {
100
- "<=>": lambda column, values, null: lambda row: row.get(column, null) == values[0],
101
- "!=": lambda column, values, null: lambda row: row.get(column, null) != values[0],
102
- "<=": (
103
- lambda column, values, null: lambda row: gentle_float_conversion(row.get(column, null))
104
- <= gentle_float_conversion(values[0])
105
- ),
106
- ">=": (
107
- lambda column, values, null: lambda row: gentle_float_conversion(row.get(column, null))
108
- >= gentle_float_conversion(values[0])
109
- ),
110
- ">": (
111
- lambda column, values, null: lambda row: gentle_float_conversion(row.get(column, null))
112
- > gentle_float_conversion(values[0])
113
- ),
114
- "<": (
115
- lambda column, values, null: lambda row: gentle_float_conversion(row.get(column, null))
116
- < gentle_float_conversion(values[0])
117
- ),
118
- "=": cheating_equals,
119
- "is not null": lambda column, values, null: lambda row: (column in row and row[column] is not None),
120
- "is null": lambda column, values, null: lambda row: (column not in row or row[column] is None),
121
- "is not": lambda column, values, null: lambda row: row.get(column, null) != values[0],
122
- "is": lambda column, values, null: lambda row: row.get(column, null) == str(values[0]),
123
- "like": lambda column, values, null: lambda row: row.get(column, null) == str(values[0]),
124
- "in": lambda column, values, null: lambda row: row.get(column, null) in values,
125
- }
126
-
127
- def __init__(self, model_class: type[clearskies.model.Model]) -> None:
128
- self._rows = []
129
- self._id_index = {}
130
- self.id_column_name = model_class.id_column_name
131
- self._next_id = 1
132
- self._model_class = model_class
133
-
134
- self._table_name = model_class.destination_name()
135
- self._column_names = list(model_class.get_columns().keys())
136
- if self.id_column_name not in self._column_names:
137
- self._column_names.append(self.id_column_name)
138
-
139
- def update(self, id: int | str, data: dict[str, Any]) -> dict[str, Any]:
140
- if id not in self._id_index:
141
- raise ValueError(f"Attempt to update non-existent record with '{self.id_column_name}' of '{id}'")
142
- index = self._id_index[id]
143
- row = self._rows[index]
144
- if row is None:
145
- raise ValueError(
146
- f"Cannot update record with '{self.id_column_name}' of '{id}' because it was already deleted"
147
- )
148
- for column_name in data.keys():
149
- if column_name not in self._column_names:
150
- raise ValueError(
151
- f"Cannot update record: column '{column_name}' does not exist in table '{self._table_name}'"
152
- )
153
- self._rows[index] = {
154
- **self._rows[index], # type: ignore
155
- **data,
156
- }
157
- return self._rows[index] # type: ignore
158
-
159
- def create(self, data: dict[str, Any]) -> dict[str, Any]:
160
- for column_name in data.keys():
161
- if column_name not in self._column_names:
162
- raise ValueError(
163
- f"Cannot create record: column '{column_name}' does not exist for model '{self._model_class.__name__}'"
164
- )
165
- incoming_id = data.get(self.id_column_name)
166
- if not incoming_id:
167
- incoming_id = self._next_id
168
- data[self.id_column_name] = incoming_id
169
- self._next_id += 1
170
- try:
171
- incoming_as_int = int(incoming_id)
172
- if incoming_as_int >= self._next_id:
173
- self._next_id = incoming_as_int + 1
174
- except:
175
- pass
176
- if incoming_id in self._id_index and self._rows[self._id_index[data[self.id_column_name]]] is not None:
177
- return self.update(data[self.id_column_name], data)
178
- for column_name in self._column_names:
179
- if column_name not in data:
180
- data[column_name] = None
181
- self._rows.append({**data})
182
- self._id_index[data[self.id_column_name]] = len(self._rows) - 1
183
- return data
184
-
185
- def delete(self, id):
186
- if id not in self._id_index:
187
- return True
188
- index = self._id_index[id]
189
- if self._rows[index] is None:
190
- return True
191
- # we set the row to None because if we remove it we'll change the indexes of the rest
192
- # of the rows, and I like being able to calculate the index from the id
193
- self._rows[index] = None
194
- return True
195
-
196
- def count(self, query: clearskies.query.Query):
197
- return len(self.rows(query, query.conditions, filter_only=True))
198
-
199
- def rows(
200
- self,
201
- query: clearskies.query.Query,
202
- conditions: list[clearskies.query.Condition],
203
- filter_only: bool = False,
204
- next_page_data: dict[str, Any] | None = None,
205
- ):
206
- rows = [row for row in self._rows if row is not None]
207
- for condition in conditions:
208
- rows = list(filter(self._condition_as_filter(condition), rows))
209
- rows = [*rows]
210
- if filter_only:
211
- return rows
212
- if query.sorts:
213
- rows = sorted(
214
- rows,
215
- key=cmp_to_key(
216
- lambda row_a, row_b: _sort(row_a, row_b, query.sorts, query.model_class.destination_name())
217
- ),
218
- )
219
- if query.limit or query.pagination.get("start"):
220
- number_rows = len(rows)
221
- start = int(query.pagination.get("start", 0))
222
- if not start:
223
- start = 0
224
- if int(start) >= number_rows:
225
- start = number_rows - 1
226
- end = len(rows)
227
- if query.limit and start + int(query.limit) <= number_rows:
228
- end = start + int(query.limit)
229
- if end < number_rows and type(next_page_data) == dict:
230
- next_page_data["start"] = start + int(query.limit)
231
- rows = rows[start:end]
232
- return rows
233
-
234
- @classmethod
235
- def _condition_as_filter(cls, condition: clearskies.query.Condition) -> Callable:
236
- column = condition.column_name
237
- values = condition.values
238
- return cls._operator_lambda_builders[condition.operator.lower()](column, values, cls.null)
239
-
240
-
241
- class MemoryBackend(Backend, InjectableProperties):
242
- """
243
- Store data in an in-memory store built in to clearskies.
244
-
245
- ## Usage
246
-
247
- Since the memory backend is built into clearskies, there's no configuration necessary to make it work:
248
- simply attach it to any of your models and it will manage data for you. If you want though, you can declare
249
- a binding named `memory_backend_default_data` which you fill with records for your models to pre-populate
250
- the memory backend. This can be helpful for tests as well as tables with fixed values.
251
-
252
- ### Testing
253
-
254
- A primary use case of the memory backend is for building unit tests of your code. You can use the dependency
255
- injection system to override other backends with the memory backend. You can still operate with model classes
256
- in the exact same way, so this can be an easy way to mock out databases/api endpoints/etc... Of course,
257
- there can be behavioral differences between the memory backend and other backends, so this isn't always perfect.
258
- Hence why this works well for unit tests, but can't replace all testing, especially integration tests or
259
- end-to-end tests. Here's an example of that. Note that the UserPreference model uses the cursor backend,
260
- but when you run this code it will actually end up with the memory backend, so the code will run even without
261
- attempting to connect to a database.
262
-
263
- ```python
264
- import clearskies
265
-
266
-
267
- class UserPreference(clearskies.Model):
268
- id_column_name = "id"
269
- backend = clearskies.backends.CursorBackend()
270
- id = clearskies.columns.Uuid()
271
-
272
-
273
- cli = clearskies.contexts.Cli(
274
- clearskies.endpoints.Callable(
275
- lambda user_preferences: user_preferences.create(no_data=True).id,
276
- ),
277
- classes=[UserPreference],
278
- class_overrides={
279
- clearskies.backends.CursorBackend: clearskies.backends.MemoryBackend(),
280
- },
281
- )
282
-
283
- if __name__ == "__main__":
284
- cli()
285
- ```
286
-
287
- Note that the model requests the CursorBackend, but then we switch that for the memory backend via the
288
- `class_overrides` kwarg to `clearskies.contexts.Cli`. Therefore, the above code works regardless of
289
- whether or not a database is running. Since the models are used to interact with the backend
290
- (rather than using the cursor directly), the above code works the same despite the change in backend.
291
-
292
- Again, this is helpful as a quick way to manage tests - swap out a database backend (or any other backend)
293
- for the memory backend, and then pre-populate records to test your application logic. Obviously, this
294
- won't cach backend-specific issues (e.g. forgetting to add a column to your database, mismatches between
295
- column schema and backend schema, missing indexes, etc...), which is why this helps for unit tests
296
- but not for integration tests.
297
-
298
- ### Production Usage
299
-
300
- You can use the memory backend in production if you want, although there are some important caveats to keep
301
- in mind:
302
-
303
- 1. There is limited attempts at performance optimization, so you should test it before putting it under
304
- substantial loads.
305
- 2. There's no concept of replication. If you have multiple workers, then write operations won't be
306
- persisted between them.
307
-
308
- So, while there may be some cases where this is useful in production, it's by no means a replacement for
309
- more typical in-memory data stores.
310
-
311
- ### Predefined Records
312
-
313
- You can declare a binding named `memory_backend_default_data` to seed the memory backend with records. This
314
- can be helpful in testing to setup your tests, and is occassionally helpful for keeping track of data in
315
- fixed, read-only tables. Here's an example:
316
-
317
- ```python
318
- import clearskies
319
-
320
-
321
- class Owner(clearskies.Model):
322
- id_column_name = "id"
323
- backend = clearskies.backends.MemoryBackend()
324
-
325
- id = clearskies.columns.Uuid()
326
- name = clearskies.columns.String()
327
- phone = clearskies.columns.Phone()
328
-
329
-
330
- class Pet(clearskies.Model):
331
- id_column_name = "id"
332
- backend = clearskies.backends.MemoryBackend()
333
-
334
- id = clearskies.columns.Uuid()
335
- name = clearskies.columns.String()
336
- species = clearskies.columns.String()
337
- owner_id = clearskies.columns.BelongsToId(Owner, readable_parent_columns=["id", "name"])
338
- owner = clearskies.columns.BelongsToModel("owner_id")
339
-
340
-
341
- wsgi = clearskies.contexts.WsgiRef(
342
- clearskies.endpoints.List(
343
- model_class=Pet,
344
- readable_column_names=["id", "name", "species", "owner"],
345
- sortable_column_names=["id", "name", "species"],
346
- default_sort_column_name="name",
347
- ),
348
- classes=[Owner, Pet],
349
- bindings={
350
- "memory_backend_default_data": [
351
- {
352
- "model_class": Owner,
353
- "records": [
354
- {"id": "1-2-3-4", "name": "John Doe", "phone": "555-123-4567"},
355
- {"id": "5-6-7-8", "name": "Jane Doe", "phone": "555-321-0987"},
356
- ],
357
- },
358
- {
359
- "model_class": Pet,
360
- "records": [
361
- {"id": "a-b-c-d", "name": "Fido", "species": "Dog", "owner_id": "1-2-3-4"},
362
- {"id": "e-f-g-h", "name": "Spot", "species": "Dog", "owner_id": "1-2-3-4"},
363
- {
364
- "id": "i-j-k-l",
365
- "name": "Puss in Boots",
366
- "species": "Cat",
367
- "owner_id": "5-6-7-8",
368
- },
369
- ],
370
- },
371
- ],
372
- },
373
- )
374
-
375
- if __name__ == "__main__":
376
- wsgi()
377
- ```
378
-
379
- And if you invoke it:
380
-
381
- ```bash
382
- $ curl 'http://localhost:8080' | jq
383
- {
384
- "status": "success",
385
- "error": "",
386
- "data": [
387
- {
388
- "id": "a-b-c-d",
389
- "name": "Fido",
390
- "species": "Dog",
391
- "owner": {
392
- "id": "1-2-3-4",
393
- "name": "John Doe"
394
- }
395
- },
396
- {
397
- "id": "i-j-k-l",
398
- "name": "Puss in Boots",
399
- "species": "Cat",
400
- "owner": {
401
- "id": "5-6-7-8",
402
- "name": "Jane Doe"
403
- }
404
- },
405
- {
406
- "id": "e-f-g-h",
407
- "name": "Spot",
408
- "species": "Dog",
409
- "owner": {
410
- "id": "1-2-3-4",
411
- "name": "John Doe"
412
- }
413
- }
414
- ],
415
- "pagination": {
416
- "number_results": 3,
417
- "limit": 50,
418
- "next_page": {}
419
- },
420
- "input_errors": {}
421
- }
422
- ```
423
- """
424
-
425
- default_data = inject.ByName("memory_backend_default_data")
426
- default_data_loaded = False
427
- _tables: dict[str, MemoryTable] = {}
428
- _silent_on_missing_tables: bool = True
429
-
430
- def __init__(self, silent_on_missing_tables=True):
431
- self.__class__._tables = {}
432
- self._silent_on_missing_tables = silent_on_missing_tables
433
-
434
- @classmethod
435
- def clear_table_cache(cls):
436
- cls._tables = {}
437
-
438
- def load_default_data(self):
439
- if self.default_data_loaded:
440
- return
441
- self.default_data_loaded = True
442
- if not isinstance(self.default_data, list):
443
- raise TypeError(
444
- f"'memory_backend_default_data' should be populated with a list, but I received a value of type '{self.default_data.__class__.__name__}'"
445
- )
446
- for index, table_data in enumerate(self.default_data):
447
- if "model_class" not in table_data:
448
- raise TypeError(
449
- f"Each entry in the 'memory_backend_default_data' list should have a key named 'model_class', but entry #{index + 1} is missing this key."
450
- )
451
- model_class = table_data["model_class"]
452
- if not functional.validations.is_model_class(table_data["model_class"]):
453
- raise TypeError(
454
- f"The 'model_class' key in 'memory_backend_default_data' for entry #{index + 1} is not a model class."
455
- )
456
- if "records" not in table_data:
457
- raise TypeError(
458
- f"Each entry in the 'memory_backend_default_data' list should have a key named 'records', but entry #{index + 1} is missing this key."
459
- )
460
- records = table_data["records"]
461
- if not isinstance(records, list):
462
- raise TypeError(
463
- f"The 'records' key in 'memory_backend_default_data' for entry #{index + 1} was not a list."
464
- )
465
- self.create_table(model_class)
466
- for record in records:
467
- self.create_with_model_class(record, model_class)
468
-
469
- def silent_on_missing_tables(self, silent=True):
470
- self._silent_on_missing_tables = silent
471
-
472
- def create_table(self, model_class: type[clearskies.model.Model]):
473
- self.load_default_data()
474
- table_name = model_class.destination_name()
475
- if table_name in self.__class__._tables:
476
- return
477
- self.__class__._tables[table_name] = MemoryTable(model_class)
478
-
479
- def has_table(self, model_class: type[clearskies.model.Model]) -> bool:
480
- self.load_default_data()
481
- table_name = model_class.destination_name()
482
- return table_name in self.__class__._tables
483
-
484
- def get_table(self, model_class: type[clearskies.model.Model], create_if_missing=False) -> MemoryTable:
485
- table_name = model_class.destination_name()
486
- if table_name not in self.__class__._tables:
487
- if create_if_missing:
488
- self.create_table(model_class)
489
- else:
490
- raise ValueError(
491
- f"The memory backend was asked to work with the model '{model_class.__name__}' but this model hasn't been explicitly added to the memory backend. This typically means that you are querying for records in a model but haven't created any yet."
492
- )
493
- return self.__class__._tables[table_name]
494
-
495
- def create_with_model_class(
496
- self, data: dict[str, Any], model_class: type[clearskies.model.Model]
497
- ) -> dict[str, Any]:
498
- self.create_table(model_class)
499
- return self.get_table(model_class).create(data)
500
-
501
- def update(self, id: int | str, data: dict[str, Any], model: clearskies.model.Model) -> dict[str, Any]:
502
- self.create_table(model.__class__)
503
- return self.get_table(model.__class__).update(id, data)
504
-
505
- def create(self, data: dict[str, Any], model: clearskies.model.Model) -> dict[str, Any]:
506
- self.create_table(model.__class__)
507
- return self.get_table(model.__class__).create(data)
508
-
509
- def delete(self, id: int | str, model: clearskies.model.Model) -> bool:
510
- self.create_table(model.__class__)
511
- return self.get_table(model.__class__).delete(id)
512
-
513
- def count(self, query: clearskies.query.Query) -> int:
514
- self.check_query(query)
515
- if not self.has_table(query.model_class):
516
- if self._silent_on_missing_tables:
517
- return 0
518
-
519
- raise ValueError(
520
- f"Attempt to count records for model '{query.model_class.__name__}' that hasn't yet been loaded into the MemoryBackend"
521
- )
522
-
523
- # this is easy if we have no joins, so just return early so I don't have to think about it
524
- if not query.joins:
525
- return self.get_table(query.model_class).count(query)
526
-
527
- # we can ignore left joins when counting
528
- query.joins = [join for join in query.joins if join.join_type != "LEFT"]
529
- return len(self.rows_with_joins(query))
530
-
531
- def records(
532
- self, query: clearskies.query.Query, next_page_data: dict[str, str | int] | None = None
533
- ) -> list[dict[str, Any]]:
534
- self.check_query(query)
535
- if not self.has_table(query.model_class):
536
- if self._silent_on_missing_tables:
537
- return []
538
-
539
- raise ValueError(
540
- f"Attempt to fetch records for model '{query.model_class.__name__} that hasn't yet been loaded into the MemoryBackend"
541
- )
542
-
543
- # this is easy if we have no joins, so just return early so I don't have to think about it
544
- if not query.joins:
545
- return self.get_table(query.model_class).rows(query, query.conditions, next_page_data=next_page_data)
546
- rows = self.rows_with_joins(query)
547
-
548
- if query.sorts:
549
- default_table_name = query.model_class.destination_name()
550
- rows = sorted(
551
- rows, key=cmp_to_key(lambda row_a, row_b: _sort(row_a, row_b, query.sorts, default_table_name))
552
- )
553
-
554
- # currently we don't do much with selects, so just limit results down to the data from the original
555
- # table.
556
- rows = [row[query.model_class.destination_name()] for row in rows]
557
-
558
- if "start" in query.pagination or query.limit:
559
- number_rows = len(rows)
560
- start = query.pagination.get("start", 0)
561
- if start >= number_rows:
562
- start = number_rows - 1
563
- end = len(rows)
564
- if query.limit and start + query.limit <= number_rows:
565
- end = start + query.limit
566
- rows = rows[start:end]
567
- if end < number_rows and type(next_page_data) == dict:
568
- next_page_data["start"] = start + query.limit
569
- return rows
570
-
571
- def rows_with_joins(self, query: clearskies.query.Query) -> list[dict[str, Any]]:
572
- joins = [*query.joins]
573
- conditions = [*query.conditions]
574
- # quick sanity check
575
- for join in query.joins:
576
- if join.unaliased_table_name not in self.__class__._tables:
577
- if not self._silent_on_missing_tables:
578
- raise ValueError(
579
- f"Join '{join._raw_join}' refrences table '{join.unaliased_table_name}' which does not exist in MemoryBackend"
580
- )
581
- return []
582
-
583
- # start with the matches in the main table
584
- left_table_name = query.model_class.destination_name()
585
- left_conditions = self.conditions_for_table(left_table_name, conditions, is_left=True)
586
- main_rows = self.get_table(query.model_class).rows(query, left_conditions, filter_only=True)
587
- # and now adjust the way data is stored in our rows list to support the joining process.
588
- # we're going to go from something like: `[{row_1}, {row_2}]` to something like:
589
- # [{table_1: table_1_row_1, table_2: table_2_row_1}, {table_1: table_1_row_2, table_2: table_2_row_2}]
590
- # etc...
591
- rows = [{left_table_name: row} for row in main_rows]
592
- joined_tables = [left_table_name]
593
-
594
- # and now work through our joins. The tricky part is order - we need to manage the joins in the
595
- # proper order, but they may not be in the correcet order in our join list. I still don't feel like building
596
- # a full graph, so cheat and be dumb: loop through them all and join in the ones we can, skipping the ones
597
- # we can't. If we get to the end and there are still joins left in the queue, then repeat, and eventually
598
- # complain (since the joins may not be a valid object graph)
599
- for i in range(10):
600
- for index, join in enumerate(joins):
601
- left_table_name = join.left_table_name
602
- alias = join.alias
603
- right_table_name = join.right_table_name
604
- table_name_for_join = alias if alias else right_table_name
605
- if left_table_name not in joined_tables:
606
- continue
607
-
608
- join_rows = self.__class__._tables[join.unaliased_table_name].rows(query, [], filter_only=True)
609
-
610
- rows = self.join_rows(rows, join_rows, join, joined_tables)
611
-
612
- # done with this one!
613
- del joins[index]
614
- joined_tables.append(table_name_for_join)
615
-
616
- # are we done yet?
617
- if not joins:
618
- break
619
-
620
- if joins:
621
- raise ValueError(
622
- "Unable to fulfill joins for query - perhaps a necessary join is missing? "
623
- + "One way to get this error is if you tried to join on another table which hasn't been "
624
- + "joined itself. e.g.: SELECT * FROM users JOIN type ON type.id=categories.type_id"
625
- )
626
-
627
- # now apply any remaining conditions.
628
- left_condition_ids = [id(condition) for condition in left_conditions]
629
- for condition in [condition for condition in conditions if id(condition) not in left_condition_ids]:
630
- condition_filter = MemoryTable._condition_as_filter(condition)
631
- rows = list(
632
- filter(lambda row: condition.table_name in row and condition_filter(row[condition.table_name]), rows)
633
- )
634
-
635
- return rows
636
-
637
- def all_rows(self, table_name: str) -> list[dict[str, Any]]:
638
- if table_name not in self.__class__._tables:
639
- if self._silent_on_missing_tables:
640
- return []
641
-
642
- raise ValueError(f"Cannot return rows for unknown table '{table_name}'")
643
- return list(filter(None, self.__class__._tables[table_name]._rows))
644
-
645
- def check_query(self, query: clearskies.query.Query) -> None:
646
- if query.group_by:
647
- raise KeyError(
648
- f"MemoryBackend does not support group_by clauses in queries. You may be using the wrong backend."
649
- )
650
-
651
- def conditions_for_table(
652
- self, table_name: str, conditions: list[clearskies.query.Condition], is_left=False
653
- ) -> list[clearskies.query.Condition]:
654
- """
655
- Return only the conditions for the given table.
656
-
657
- If you set is_left=True then it assumes this is the "default" table and so will also return conditions
658
- without a table name.
659
- """
660
- return [
661
- condition
662
- for condition in conditions
663
- if condition.table_name == table_name or (is_left and not condition.table_name)
664
- ]
665
-
666
- def join_rows(
667
- self,
668
- rows: list[dict[str, Any]],
669
- join_rows: list[dict[str, Any]],
670
- join: clearskies.query.Join,
671
- joined_tables: list[str],
672
- ) -> list[dict[str, Any]]:
673
- """
674
- Add the rows in `join_rows` in to the `rows` holder.
675
-
676
- `rows` should be something like:
677
-
678
- ```python
679
- [
680
- {
681
- "table_1": {"table_1_row_1"},
682
- "table_2": {"table_2_row_1"},
683
- },
684
- {
685
- "table_1": {"table_1_row_2"},
686
- "table_2": {"table_2_row_2"},
687
- },
688
- ]
689
- ```
690
-
691
- and join_rows should be the rows for the new table, something like:
692
-
693
- `[{table_3_row_1}, {table_3_row_2}]`
694
-
695
- which will then get merged into the rows variable properly (which it will return as a new list)
696
- """
697
- join_table_name = join.alias if join.alias else join.right_table_name
698
- join_type = join.join_type
699
-
700
- #######
701
- ########
702
- ## our problem is here. When we join rows we can end up with multiple copies of the records from the left table because
703
- # there can be more than one matching record in the right table. This isn't happening, and so we're not getting the
704
- # proper results because the one record that is chosen to match with the left table doesn't meet the where condition
705
- # that is applied at the very end. If we have multiple records that match, they all need to get retunred in the
706
- # final list of rows here, so we can properly search everything.
707
-
708
- # loop through each entry in rows, find a matching table in join_rows, and take action depending on join type
709
- rows = [*rows]
710
- matched_right_row_indexes = set()
711
- left_table_name = join.left_table_name
712
- left_column_name = join.left_column_name
713
- # we're
714
- for row_index in range(len(rows)):
715
- row = rows[row_index]
716
- matching_row = None
717
- if left_table_name not in row:
718
- raise ValueError("Attempted to check join data from unjoined table, which should not happen...")
719
- left_value = (
720
- row[left_table_name][left_column_name]
721
- if (row[left_table_name] is not None and left_column_name in row[left_table_name])
722
- else None
723
- )
724
- matching_rows = []
725
- for join_index, join_row in enumerate(join_rows):
726
- right_value = join_row[join.right_column_name] if join.right_column_name in join_row else None
727
- # for now we are assuming the operator for the matching is `=`. This is mainly because
728
- # our join parsing doesn't bother checking for the matching operator, because it is `=` in
729
- # 99% of cases. We can always adjust down the line.
730
- if (right_value is None and left_value is None) or (right_value == left_value):
731
- matching_rows.append(join_row)
732
- matched_right_row_indexes.add(right_value)
733
-
734
- # if we have matching rows then join them in.
735
- for index, matching_row in enumerate(matching_rows):
736
- if not index:
737
- rows[row_index][join_table_name] = matching_row
738
- else:
739
- rows.append({**row, **{join_table_name: matching_row}})
740
-
741
- # if we don't have matching rows then remove them for an inner or right join
742
- if not matching_rows:
743
- if join_type == "LEFT" or join_type == "OUTER":
744
- rows[row_index][join_table_name] = matching_row = None
745
- else:
746
- # we can't immediately delete the row because we're looping over the array it is in,
747
- # so just mark it as None and remove it later
748
- rows[row_index] = None # type: ignore
749
-
750
- rows = [row for row in rows if row is not None]
751
-
752
- # now for outer/right rows we add on any unmatched rows
753
- if (join_type == "OUTER" or join_type == "RIGHT") and len(matched_right_row_indexes) < len(join_rows):
754
- for join_index in set(range(len(join_rows))) - matched_right_row_indexes:
755
- rows.append(
756
- {
757
- join_table_name: join_rows[join_index],
758
- **{table_name: None for table_name in joined_tables},
759
- }
760
- )
761
-
762
- return rows
763
-
764
- def validate_pagination_data(self, data: dict[str, Any], case_mapping: Callable) -> str:
765
- extra_keys = set(data.keys()) - set(self.allowed_pagination_keys())
766
- if len(extra_keys):
767
- key_name = case_mapping("start")
768
- return "Invalid pagination key(s): '" + "','".join(extra_keys) + f"'. Only '{key_name}' is allowed"
769
- if "start" not in data:
770
- key_name = case_mapping("start")
771
- return f"You must specify '{key_name}' when setting pagination"
772
- start = data["start"]
773
- try:
774
- start = int(start)
775
- except:
776
- key_name = case_mapping("start")
777
- return f"Invalid pagination data: '{key_name}' must be a number"
778
- return ""
779
-
780
- def allowed_pagination_keys(self) -> list[str]:
781
- return ["start"]
782
-
783
- def documentation_pagination_next_page_response(self, case_mapping: Callable[[str], str]) -> list[Any]:
784
- return [AutoDocInteger(case_mapping("start"), example=0)]
785
-
786
- def documentation_pagination_next_page_example(self, case_mapping: Callable[[str], str]) -> dict[str, Any]:
787
- return {case_mapping("start"): 0}
788
-
789
- def documentation_pagination_parameters(
790
- self, case_mapping: Callable[[str], str]
791
- ) -> list[tuple[AutoDocSchema, str]]:
792
- return [
793
- (
794
- AutoDocInteger(case_mapping("start"), example=0),
795
- "The zero-indexed record number to start listing results from",
796
- )
797
- ]