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,136 +0,0 @@
1
- import inspect
2
- from abc import ABC, abstractmethod
3
- from typing import Any, Callable, Type
4
-
5
- import clearskies.column
6
- import clearskies.model
7
- import clearskies.query
8
- from clearskies.autodoc.schema import Schema as AutoDocSchema
9
-
10
-
11
- class Backend(ABC):
12
- """
13
- Connecting models to their data since 2020!.
14
-
15
- The backend system acts as a flexible layer between models and their data sources. By changing the backend attached to a model,
16
- you change where the model fetches and saves data. This might be a database, an in-memory data store, a dynamodb table,
17
- an API, and more. This allows you to interact with a variety of data sources with the models acting as a standardized API.
18
- Since endpoints also rely on the models for their functionality, this means that you can easily build API endpoints and
19
- more for a variety of data sources with a minimal amount of code.
20
-
21
- Of course, not all data sources support all functionality present in the model. Therefore, you do still need to have
22
- a fair understanding of how your data sources work.
23
- """
24
-
25
- supports_n_plus_one = False
26
- can_count = True
27
-
28
- @abstractmethod
29
- def update(self, id: int | str, data: dict[str, Any], model: clearskies.model.Model) -> dict[str, Any]:
30
- """Update the record with the given id with the information from the data dictionary."""
31
- pass
32
-
33
- @abstractmethod
34
- def create(self, data: dict[str, Any], model: clearskies.model.Model) -> dict[str, Any]:
35
- """Create a record with the information from the data dictionary."""
36
- pass
37
-
38
- @abstractmethod
39
- def delete(self, id: int | str, model: clearskies.model.Model) -> bool:
40
- """Delete the record with the given id."""
41
- pass
42
-
43
- @abstractmethod
44
- def count(self, query: clearskies.query.Query) -> int:
45
- """Return the number of records which match the given query configuration."""
46
- pass
47
-
48
- @abstractmethod
49
- def records(
50
- self, query: clearskies.query.Query, next_page_data: dict[str, str | int] | None = None
51
- ) -> list[dict[str, Any]]:
52
- """
53
- Return a list of records that match the given query configuration.
54
-
55
- next_page_data is used to return data to the caller. Pass in an empty dictionary, and it will be populated
56
- with the data needed to return the next page of results. If it is still an empty dictionary when returned,
57
- then there is no additional data.
58
- """
59
- pass
60
-
61
- @abstractmethod
62
- def validate_pagination_data(self, data: dict[str, Any], case_mapping: Callable[[str], str]) -> str:
63
- """
64
- Check if the given dictionary is valid pagination data for the background.
65
-
66
- Return a string with an error message, or an empty string if the data is valid
67
- """
68
- pass
69
-
70
- @abstractmethod
71
- def allowed_pagination_keys(self) -> list[str]:
72
- """
73
- Return the list of allowed keys in the pagination kwargs for the backend.
74
-
75
- It must always return keys in snake_case so that the auto casing system can
76
- adjust on the front-end for consistency.
77
- """
78
- pass
79
-
80
- @abstractmethod
81
- def documentation_pagination_next_page_response(self, case_mapping: Callable) -> list[Any]:
82
- """
83
- Return a list of autodoc schema objects.
84
-
85
- It will describe the contents of the `next_page` dictionary
86
- in the pagination section of the response
87
- """
88
- pass
89
-
90
- @abstractmethod
91
- def documentation_pagination_parameters(self, case_mapping: Callable) -> list[tuple[AutoDocSchema, str]]:
92
- """
93
- Return a list of autodoc schema objects describing the allowed input keys to set pagination.
94
-
95
- It should return a list of tuples, with each tuple corresponding to an input key.
96
- The first element in the tuple should be the schema, and the second should be the description.
97
- """
98
- pass
99
-
100
- @abstractmethod
101
- def documentation_pagination_next_page_example(self, case_mapping: Callable) -> dict[str, Any]:
102
- """
103
- Return an example for next page documentation.
104
-
105
- Returns an example (as a simple dictionary) of what the next_page data in the pagination response
106
- should look like
107
- """
108
- pass
109
-
110
- def column_from_backend(self, column: clearskies.column.Column, value: Any) -> Any:
111
- """
112
- Manage transformations from the backend.
113
-
114
- The idea with this (and `column_to_backend`) is that the transformations to
115
- and from the backend are mostly determined by the column type - integer, string,
116
- date, etc... However, there are cases where these are also backend specific: a datetime
117
- column may be serialized different ways for different databases, a JSON column must be
118
- serialized for a database but won't be serialized for an API call, etc... Therefore
119
- we mostly just let the column handle this, but we want the backend to be in charge
120
- in case it needs to make changes.
121
- """
122
- return column.from_backend(value)
123
-
124
- def column_to_backend(self, column: clearskies.column.Column, backend_data: dict[str, Any]) -> dict[str, Any]:
125
- """
126
- Manage transformations to the backend.
127
-
128
- The idea with this (and `column_from_backend`) is that the transformations to
129
- and from the backend are mostly determined by the column type - integer, string,
130
- date, etc... However, there are cases where these are also backend specific: a datetime
131
- column may be serialized different ways for different databases, a JSON column must be
132
- serialized for a database but won't be serialized for an API call, etc... Therefore
133
- we mostly just let the column handle this, but we want the backend to be in charge
134
- in case it needs to make changes.
135
- """
136
- return column.to_backend(backend_data)
@@ -1,335 +0,0 @@
1
- from typing import Any, Callable
2
-
3
- import clearskies.model
4
- import clearskies.query
5
- from clearskies.autodoc.schema import Integer as AutoDocInteger
6
- from clearskies.autodoc.schema import Schema as AutoDocSchema
7
- from clearskies.backends.backend import Backend
8
- from clearskies.di import InjectableProperties, inject
9
-
10
-
11
- class CursorBackend(Backend, InjectableProperties):
12
- """
13
- The cursor backend connects your models to a MySQL or MariaDB database.
14
-
15
- ## Installing Dependencies
16
-
17
- clearskies uses PyMySQL to manage the database connection and make queries. This is not installed by default,
18
- but is a named extra that you can install when needed via:
19
-
20
- ```bash
21
- pip install clear-skies[mysql]
22
- ```
23
-
24
- ## Connecting to your server
25
-
26
- By default, database credentials are expected in environment variables:
27
-
28
- | Name | Default | Value |
29
- |-------------|---------|---------------------------------------------------------------|
30
- | db_host | | The hostname where the database can be found |
31
- | db_username | | The username to connect as |
32
- | db_password | | The password to connect with |
33
- | db_database | | The name of the database to use |
34
- | db_port | 3306 | The network port to connect to |
35
- | db_ssl_ca | | Path to a certificate to use: enables SSL over the connection |
36
-
37
- However, you can fully control the credential provisioning process by declaring a dependency named `connection_details` and
38
- setting it to a dictionary with the above keys, minus the `db_` prefix:
39
-
40
- ```python
41
- class ConnectionDetails(clearskies.di.AdditionalConfig):
42
- provide_connection_details(self, secrets):
43
- return {
44
- "host": secrets.get("database_host"),
45
- "username": secrets.get("db_username"),
46
- "password": secrets.get("db_password"),
47
- "database": secrets.get("db_database"),
48
- "port": 3306,
49
- "ssl_ca": "/path/to/ca",
50
- }
51
-
52
- wsgi = clearskies.contexts.Wsgi(
53
- some_application,
54
- additional_configs=[ConnectionDetails()],
55
- bindings={
56
- "secrets": "" # some configuration here to point to your secret manager
57
- }
58
- )
59
- ```
60
-
61
- Similarly, some alternate credential provisioning schemes are built into clearskies. See the
62
- clearskies.secrets.additional_configs module for those options.
63
-
64
- ## Connecting models to tables
65
-
66
- The table name for your model comes from calling the `destination_name` class method of the model class. By
67
- default, this takes the class name, converts it to snake case, and then pluralizes it. So, if you have a model
68
- class named `UserPreference` then the cursor backend will look for a table called `user_preferences`. If this
69
- isn't what you want, then you can simply override `destination_name` to return whatever table you want:
70
-
71
- ```python
72
- class UserPreference(clearskies.Model):
73
- @classmethod
74
- def destination_name(cls):
75
- return "some_other_table_name"
76
- ```
77
-
78
- Additionally, the cursor backend accepts an argument called `table_prefix` which, if provided, will be prefixed
79
- to your table name. Finally, you can declare a dependency called `global_table_prefix` which will automatically
80
- be added to every table name. In the following example, the table name will be `user_configuration_preferences`
81
- due to:
82
-
83
- 1. The `destination_name` method sets the table name to `preferences`
84
- 2. The `table_prefix` argument to the CursorBackend constructor adds a prefix of `configuration_`
85
- 3. The `global_table_prefix` binding sets a prefix of `user_`, wihch goes before everything else.
86
-
87
- ```python
88
- import clearskies
89
-
90
-
91
- class UserPreference(clearskies.Model):
92
- id_column_name = "id"
93
- backend = clearskies.backends.CursorBackend(table_prefix="configuration_")
94
- id = clearskies.columns.Uuid()
95
-
96
- @classmethod
97
- def destination_name(cls):
98
- return "preferences"
99
-
100
-
101
- cli = clearskies.contexts.Cli(
102
- clearskies.endpoints.Callable(
103
- lambda user_preferences: user_preferences.create(no_data=True).id,
104
- ),
105
- classes=[UserPreference],
106
- bindings={
107
- "global_table_prefix": "user_",
108
- },
109
- )
110
- ```
111
-
112
- """
113
-
114
- supports_n_plus_one = True
115
- cursor = inject.ByName("cursor")
116
- global_table_prefix = inject.ByName("global_table_prefix")
117
- table_escape_character = "`"
118
- column_escape_character = "`"
119
- table_prefix = ""
120
-
121
- def __init__(self, table_escape_character="`", column_escape_character="`", table_prefix=""):
122
- self.table_escape_character = table_escape_character
123
- self.column_escape_character = column_escape_character
124
- self.table_prefix = table_prefix
125
-
126
- def _finalize_table_name(self, table_name):
127
- table_name = f"{self.global_table_prefix}{self.table_prefix}{table_name}"
128
- if "." not in table_name:
129
- return f"{self.table_escape_character}{table_name}{self.table_escape_character}"
130
- return (
131
- self.table_escape_character
132
- + f"{self.table_escape_character}.{self.table_escape_character}".join(table_name.split("."))
133
- + self.table_escape_character
134
- )
135
-
136
- def update(self, id: int | str, data: dict[str, Any], model: clearskies.model.Model) -> dict[str, Any]:
137
- query_parts = []
138
- parameters = []
139
- escape = self.column_escape_character
140
- for key, val in data.items():
141
- query_parts.append(f"{escape}{key}{escape}=%s")
142
- parameters.append(val)
143
- updates = ", ".join(query_parts)
144
-
145
- # update the record
146
- table_name = self._finalize_table_name(model.destination_name())
147
- self.cursor.execute(
148
- f"UPDATE {table_name} SET {updates} WHERE {model.id_column_name}=%s", tuple([*parameters, id])
149
- )
150
-
151
- # and now query again to fetch the updated record.
152
- return self.records(
153
- clearskies.query.Query(
154
- model.__class__, conditions=[clearskies.query.Condition(f"{model.id_column_name}={id}")]
155
- )
156
- )[0]
157
-
158
- def create(self, data: dict[str, Any], model: clearskies.model.Model) -> dict[str, Any]:
159
- escape = self.column_escape_character
160
- columns = escape + f"{escape}, {escape}".join(data.keys()) + escape
161
- placeholders = ", ".join(["%s" for i in range(len(data))])
162
-
163
- table_name = self._finalize_table_name(model.destination_name())
164
- self.cursor.execute(f"INSERT INTO {table_name} ({columns}) VALUES ({placeholders})", tuple(data.values()))
165
- new_id = data.get(model.id_column_name)
166
- if not new_id:
167
- new_id = self.cursor.lastrowid
168
- if not new_id:
169
- raise ValueError("I can't figure out what the id is for a newly created record :(")
170
-
171
- return self.records(
172
- clearskies.query.Query(
173
- model.__class__, conditions=[clearskies.query.Condition(f"{model.id_column_name}={new_id}")]
174
- )
175
- )[0]
176
-
177
- def delete(self, id: int | str, model: clearskies.model.Model) -> bool:
178
- table_name = self._finalize_table_name(model.destination_name())
179
- self.cursor.execute(f"DELETE FROM {table_name} WHERE {model.id_column_name}=%s", (id,))
180
- return True
181
-
182
- def count(self, query: clearskies.query.Query) -> int:
183
- (sql, parameters) = self.as_count_sql(query)
184
- self.cursor.execute(sql, parameters)
185
- for row in self.cursor:
186
- return row[0] if type(row) == tuple else row["count"]
187
- return 0
188
-
189
- def records(
190
- self, query: clearskies.query.Query, next_page_data: dict[str, str | int] | None = None
191
- ) -> list[dict[str, Any]]:
192
- # I was going to get fancy and have this return an iterator, but since I'm going to load up
193
- # everything into a list anyway, I may as well just return the list, right?
194
- (sql, parameters) = self.as_sql(query)
195
- self.cursor.execute(sql, parameters)
196
- records = [row for row in self.cursor]
197
- if type(next_page_data) == dict:
198
- limit = query.limit
199
- start = query.pagination.get("start", 0)
200
- if limit and len(records) == limit:
201
- next_page_data["start"] = int(start) + int(limit)
202
- return records
203
-
204
- def as_sql(self, query: clearskies.query.Query) -> tuple[str, tuple[Any]]:
205
- escape = self.column_escape_character
206
- table_name = query.model_class.destination_name()
207
- (wheres, parameters) = self.conditions_as_wheres_and_parameters(
208
- query.conditions, query.model_class.destination_name()
209
- )
210
- select_parts = []
211
- if query.select_all:
212
- select_parts.append(self._finalize_table_name(table_name) + ".*")
213
- if query.selects:
214
- select_parts.extend(query.selects)
215
- select = ", ".join(select_parts)
216
- if query.joins:
217
- joins = " " + " ".join([join._raw_join for join in query.joins])
218
- else:
219
- joins = ""
220
- if query.sorts:
221
- sort_parts = []
222
- for sort in query.sorts:
223
- table_name = sort.table_name
224
- column_name = sort.column_name
225
- direction = sort.direction
226
- prefix = self._finalize_table_name(table_name) + "." if table_name else ""
227
- sort_parts.append(f"{prefix}{escape}{column_name}{escape} {direction}")
228
- order_by = " ORDER BY " + ", ".join(sort_parts)
229
- else:
230
- order_by = ""
231
- group_by = self.group_by_clause(query.group_by)
232
- limit = ""
233
- if query.limit:
234
- start = 0
235
- limit_size = int(query.limit)
236
- if "start" in query.pagination:
237
- start = int(query.pagination["start"])
238
- limit = f" LIMIT {start}, {limit_size}"
239
-
240
- table_name = self._finalize_table_name(table_name)
241
- return (
242
- f"SELECT {select} FROM {table_name}{joins}{wheres}{group_by}{order_by}{limit}".strip(),
243
- parameters,
244
- )
245
-
246
- def as_count_sql(self, query: clearskies.query.Query) -> tuple[str, tuple[Any]]:
247
- escape = self.column_escape_character
248
- # note that this won't work if we start including a HAVING clause
249
- (wheres, parameters) = self.conditions_as_wheres_and_parameters(
250
- query.conditions, query.model_class.destination_name()
251
- )
252
- # we also don't currently support parameters in the join clause - I'll probably need that though
253
- if query.joins:
254
- # We can ignore left joins because they don't change the count
255
- join_sections = filter(lambda join: join.type != "LEFT", query.joins) # type: ignore
256
- joins = " " + " ".join([join._raw_join for join in join_sections])
257
- else:
258
- joins = ""
259
- table_name = self._finalize_table_name(query.model_class.destination_name())
260
- if not query.group_by:
261
- query_string = f"SELECT COUNT(*) AS count FROM {table_name}{joins}{wheres}"
262
- else:
263
- group_by = self.group_by_clause(query.group_by)
264
- query_string = (
265
- f"SELECT COUNT(*) AS count FROM (SELECT 1 FROM {table_name}{joins}{wheres}{group_by}) AS count_inner"
266
- )
267
- return (query_string, parameters)
268
-
269
- def conditions_as_wheres_and_parameters(
270
- self, conditions: list[clearskies.query.Condition], default_table_name: str
271
- ) -> tuple[str, tuple[Any]]:
272
- if not conditions:
273
- return ("", ()) # type: ignore
274
-
275
- parameters = []
276
- where_parts = []
277
- for condition in conditions:
278
- parameters.extend(condition.values)
279
- table = condition.table_name if condition.table_name else self._finalize_table_name(default_table_name)
280
- column = condition.column_name
281
- where_parts.append(
282
- condition._with_placeholders(
283
- f"{table}.{column}",
284
- condition.operator,
285
- condition.values,
286
- escape=False,
287
- )
288
- )
289
- return (" WHERE " + " AND ".join(where_parts), tuple(parameters)) # type: ignore
290
-
291
- def group_by_clause(self, group_by: str) -> str:
292
- if not group_by:
293
- return ""
294
- escape = self.column_escape_character
295
- if "." not in group_by:
296
- return f" GROUP BY {escape}{group_by}{escape}"
297
- parts = group_by.split(".", 1)
298
- table = parts[0]
299
- column = parts[1]
300
- return f" GROUP BY {escape}{table}{escape}.{escape}{column}{escape}"
301
-
302
- def validate_pagination_data(self, data: dict[str, Any], case_mapping: Callable) -> str:
303
- extra_keys = set(data.keys()) - set(self.allowed_pagination_keys())
304
- if len(extra_keys):
305
- key_name = case_mapping("start")
306
- return "Invalid pagination key(s): '" + "','".join(extra_keys) + f"'. Only '{key_name}' is allowed"
307
- if "start" not in data:
308
- key_name = case_mapping("start")
309
- return f"You must specify '{key_name}' when setting pagination"
310
- start = data["start"]
311
- try:
312
- start = int(start)
313
- except:
314
- key_name = case_mapping("start")
315
- return f"Invalid pagination data: '{key_name}' must be a number"
316
- return ""
317
-
318
- def allowed_pagination_keys(self) -> list[str]:
319
- return ["start"]
320
-
321
- def documentation_pagination_next_page_response(self, case_mapping: Callable[[str], str]) -> list[Any]:
322
- return [AutoDocInteger(case_mapping("start"), example=0)]
323
-
324
- def documentation_pagination_next_page_example(self, case_mapping: Callable[[str], str]) -> dict[str, Any]:
325
- return {case_mapping("start"): 0}
326
-
327
- def documentation_pagination_parameters(
328
- self, case_mapping: Callable[[str], str]
329
- ) -> list[tuple[AutoDocSchema, str]]:
330
- return [
331
- (
332
- AutoDocInteger(case_mapping("start"), example=0),
333
- "The zero-indexed record number to start listing results from",
334
- )
335
- ]