clear-skies 0.0.3a0__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 (248) hide show
  1. clear_skies-0.0.3a0.dist-info/LICENSE +7 -0
  2. clear_skies-0.0.3a0.dist-info/METADATA +46 -0
  3. clear_skies-0.0.3a0.dist-info/RECORD +248 -0
  4. clear_skies-0.0.3a0.dist-info/WHEEL +4 -0
  5. clearskies/__init__.py +62 -0
  6. clearskies/action.py +7 -0
  7. clearskies/authentication/__init__.py +15 -0
  8. clearskies/authentication/authentication.py +42 -0
  9. clearskies/authentication/authorization.py +12 -0
  10. clearskies/authentication/authorization_pass_through.py +20 -0
  11. clearskies/authentication/jwks.py +158 -0
  12. clearskies/authentication/public.py +5 -0
  13. clearskies/authentication/secret_bearer.py +553 -0
  14. clearskies/autodoc/__init__.py +8 -0
  15. clearskies/autodoc/formats/__init__.py +5 -0
  16. clearskies/autodoc/formats/oai3_json/__init__.py +7 -0
  17. clearskies/autodoc/formats/oai3_json/oai3_json.py +87 -0
  18. clearskies/autodoc/formats/oai3_json/oai3_schema_resolver.py +15 -0
  19. clearskies/autodoc/formats/oai3_json/parameter.py +35 -0
  20. clearskies/autodoc/formats/oai3_json/request.py +68 -0
  21. clearskies/autodoc/formats/oai3_json/response.py +28 -0
  22. clearskies/autodoc/formats/oai3_json/schema/__init__.py +11 -0
  23. clearskies/autodoc/formats/oai3_json/schema/array.py +9 -0
  24. clearskies/autodoc/formats/oai3_json/schema/default.py +13 -0
  25. clearskies/autodoc/formats/oai3_json/schema/enum.py +7 -0
  26. clearskies/autodoc/formats/oai3_json/schema/object.py +29 -0
  27. clearskies/autodoc/formats/oai3_json/test.json +1985 -0
  28. clearskies/autodoc/py.typed +0 -0
  29. clearskies/autodoc/request/__init__.py +15 -0
  30. clearskies/autodoc/request/header.py +6 -0
  31. clearskies/autodoc/request/json_body.py +6 -0
  32. clearskies/autodoc/request/parameter.py +8 -0
  33. clearskies/autodoc/request/request.py +38 -0
  34. clearskies/autodoc/request/url_parameter.py +6 -0
  35. clearskies/autodoc/request/url_path.py +6 -0
  36. clearskies/autodoc/response/__init__.py +5 -0
  37. clearskies/autodoc/response/response.py +9 -0
  38. clearskies/autodoc/schema/__init__.py +31 -0
  39. clearskies/autodoc/schema/array.py +10 -0
  40. clearskies/autodoc/schema/base64.py +8 -0
  41. clearskies/autodoc/schema/boolean.py +5 -0
  42. clearskies/autodoc/schema/date.py +5 -0
  43. clearskies/autodoc/schema/datetime.py +5 -0
  44. clearskies/autodoc/schema/double.py +5 -0
  45. clearskies/autodoc/schema/enum.py +17 -0
  46. clearskies/autodoc/schema/integer.py +6 -0
  47. clearskies/autodoc/schema/long.py +5 -0
  48. clearskies/autodoc/schema/number.py +6 -0
  49. clearskies/autodoc/schema/object.py +13 -0
  50. clearskies/autodoc/schema/password.py +5 -0
  51. clearskies/autodoc/schema/schema.py +11 -0
  52. clearskies/autodoc/schema/string.py +5 -0
  53. clearskies/backends/__init__.py +65 -0
  54. clearskies/backends/api_backend.py +1178 -0
  55. clearskies/backends/backend.py +123 -0
  56. clearskies/backends/cursor_backend.py +335 -0
  57. clearskies/backends/memory_backend.py +797 -0
  58. clearskies/backends/secrets_backend.py +107 -0
  59. clearskies/column.py +1232 -0
  60. clearskies/columns/__init__.py +71 -0
  61. clearskies/columns/audit.py +205 -0
  62. clearskies/columns/belongs_to_id.py +483 -0
  63. clearskies/columns/belongs_to_model.py +128 -0
  64. clearskies/columns/belongs_to_self.py +105 -0
  65. clearskies/columns/boolean.py +109 -0
  66. clearskies/columns/category_tree.py +275 -0
  67. clearskies/columns/category_tree_ancestors.py +51 -0
  68. clearskies/columns/category_tree_children.py +127 -0
  69. clearskies/columns/category_tree_descendants.py +48 -0
  70. clearskies/columns/created.py +94 -0
  71. clearskies/columns/created_by_authorization_data.py +116 -0
  72. clearskies/columns/created_by_header.py +99 -0
  73. clearskies/columns/created_by_ip.py +92 -0
  74. clearskies/columns/created_by_routing_data.py +96 -0
  75. clearskies/columns/created_by_user_agent.py +92 -0
  76. clearskies/columns/date.py +230 -0
  77. clearskies/columns/datetime.py +278 -0
  78. clearskies/columns/email.py +76 -0
  79. clearskies/columns/float.py +149 -0
  80. clearskies/columns/has_many.py +505 -0
  81. clearskies/columns/has_many_self.py +56 -0
  82. clearskies/columns/has_one.py +14 -0
  83. clearskies/columns/integer.py +156 -0
  84. clearskies/columns/json.py +122 -0
  85. clearskies/columns/many_to_many_ids.py +333 -0
  86. clearskies/columns/many_to_many_ids_with_data.py +270 -0
  87. clearskies/columns/many_to_many_models.py +154 -0
  88. clearskies/columns/many_to_many_pivots.py +133 -0
  89. clearskies/columns/phone.py +158 -0
  90. clearskies/columns/select.py +91 -0
  91. clearskies/columns/string.py +98 -0
  92. clearskies/columns/timestamp.py +160 -0
  93. clearskies/columns/updated.py +110 -0
  94. clearskies/columns/uuid.py +86 -0
  95. clearskies/configs/README.md +105 -0
  96. clearskies/configs/__init__.py +159 -0
  97. clearskies/configs/actions.py +43 -0
  98. clearskies/configs/any.py +13 -0
  99. clearskies/configs/any_dict.py +22 -0
  100. clearskies/configs/any_dict_or_callable.py +23 -0
  101. clearskies/configs/authentication.py +23 -0
  102. clearskies/configs/authorization.py +23 -0
  103. clearskies/configs/boolean.py +16 -0
  104. clearskies/configs/boolean_or_callable.py +18 -0
  105. clearskies/configs/callable_config.py +18 -0
  106. clearskies/configs/columns.py +34 -0
  107. clearskies/configs/conditions.py +30 -0
  108. clearskies/configs/config.py +21 -0
  109. clearskies/configs/datetime.py +18 -0
  110. clearskies/configs/datetime_or_callable.py +19 -0
  111. clearskies/configs/endpoint.py +23 -0
  112. clearskies/configs/float.py +16 -0
  113. clearskies/configs/float_or_callable.py +18 -0
  114. clearskies/configs/integer.py +16 -0
  115. clearskies/configs/integer_or_callable.py +18 -0
  116. clearskies/configs/joins.py +30 -0
  117. clearskies/configs/list_any_dict.py +30 -0
  118. clearskies/configs/list_any_dict_or_callable.py +31 -0
  119. clearskies/configs/model_class.py +35 -0
  120. clearskies/configs/model_column.py +65 -0
  121. clearskies/configs/model_columns.py +56 -0
  122. clearskies/configs/model_destination_name.py +25 -0
  123. clearskies/configs/model_to_id_column.py +43 -0
  124. clearskies/configs/readable_model_column.py +9 -0
  125. clearskies/configs/readable_model_columns.py +9 -0
  126. clearskies/configs/schema.py +23 -0
  127. clearskies/configs/searchable_model_columns.py +9 -0
  128. clearskies/configs/security_headers.py +39 -0
  129. clearskies/configs/select.py +26 -0
  130. clearskies/configs/select_list.py +47 -0
  131. clearskies/configs/string.py +29 -0
  132. clearskies/configs/string_dict.py +32 -0
  133. clearskies/configs/string_list.py +32 -0
  134. clearskies/configs/string_list_or_callable.py +35 -0
  135. clearskies/configs/string_or_callable.py +18 -0
  136. clearskies/configs/timedelta.py +18 -0
  137. clearskies/configs/timezone.py +18 -0
  138. clearskies/configs/url.py +23 -0
  139. clearskies/configs/validators.py +45 -0
  140. clearskies/configs/writeable_model_column.py +9 -0
  141. clearskies/configs/writeable_model_columns.py +9 -0
  142. clearskies/configurable.py +76 -0
  143. clearskies/contexts/__init__.py +11 -0
  144. clearskies/contexts/cli.py +7 -0
  145. clearskies/contexts/context.py +84 -0
  146. clearskies/contexts/wsgi.py +16 -0
  147. clearskies/contexts/wsgi_ref.py +49 -0
  148. clearskies/di/__init__.py +14 -0
  149. clearskies/di/additional_config.py +130 -0
  150. clearskies/di/additional_config_auto_import.py +17 -0
  151. clearskies/di/di.py +968 -0
  152. clearskies/di/inject/__init__.py +23 -0
  153. clearskies/di/inject/by_class.py +21 -0
  154. clearskies/di/inject/by_name.py +18 -0
  155. clearskies/di/inject/di.py +13 -0
  156. clearskies/di/inject/environment.py +14 -0
  157. clearskies/di/inject/input_output.py +20 -0
  158. clearskies/di/inject/now.py +13 -0
  159. clearskies/di/inject/requests.py +13 -0
  160. clearskies/di/inject/secrets.py +14 -0
  161. clearskies/di/inject/utcnow.py +13 -0
  162. clearskies/di/inject/uuid.py +15 -0
  163. clearskies/di/injectable.py +29 -0
  164. clearskies/di/injectable_properties.py +131 -0
  165. clearskies/di/test_module/__init__.py +6 -0
  166. clearskies/di/test_module/another_module/__init__.py +2 -0
  167. clearskies/di/test_module/module_class.py +5 -0
  168. clearskies/end.py +183 -0
  169. clearskies/endpoint.py +1309 -0
  170. clearskies/endpoint_group.py +297 -0
  171. clearskies/endpoints/__init__.py +23 -0
  172. clearskies/endpoints/advanced_search.py +526 -0
  173. clearskies/endpoints/callable.py +387 -0
  174. clearskies/endpoints/create.py +202 -0
  175. clearskies/endpoints/delete.py +139 -0
  176. clearskies/endpoints/get.py +275 -0
  177. clearskies/endpoints/health_check.py +181 -0
  178. clearskies/endpoints/list.py +573 -0
  179. clearskies/endpoints/restful_api.py +427 -0
  180. clearskies/endpoints/simple_search.py +286 -0
  181. clearskies/endpoints/update.py +190 -0
  182. clearskies/environment.py +104 -0
  183. clearskies/exceptions/__init__.py +17 -0
  184. clearskies/exceptions/authentication.py +2 -0
  185. clearskies/exceptions/authorization.py +2 -0
  186. clearskies/exceptions/client_error.py +2 -0
  187. clearskies/exceptions/input_errors.py +4 -0
  188. clearskies/exceptions/moved_permanently.py +3 -0
  189. clearskies/exceptions/moved_temporarily.py +3 -0
  190. clearskies/exceptions/not_found.py +2 -0
  191. clearskies/functional/__init__.py +7 -0
  192. clearskies/functional/routing.py +92 -0
  193. clearskies/functional/string.py +112 -0
  194. clearskies/functional/validations.py +76 -0
  195. clearskies/input_outputs/__init__.py +13 -0
  196. clearskies/input_outputs/cli.py +170 -0
  197. clearskies/input_outputs/exceptions/__init__.py +2 -0
  198. clearskies/input_outputs/exceptions/cli_input_error.py +2 -0
  199. clearskies/input_outputs/exceptions/cli_not_found.py +2 -0
  200. clearskies/input_outputs/headers.py +45 -0
  201. clearskies/input_outputs/input_output.py +138 -0
  202. clearskies/input_outputs/programmatic.py +69 -0
  203. clearskies/input_outputs/py.typed +0 -0
  204. clearskies/input_outputs/wsgi.py +77 -0
  205. clearskies/model.py +662 -0
  206. clearskies/parameters_to_properties.py +31 -0
  207. clearskies/py.typed +0 -0
  208. clearskies/query/__init__.py +12 -0
  209. clearskies/query/condition.py +223 -0
  210. clearskies/query/join.py +136 -0
  211. clearskies/query/query.py +196 -0
  212. clearskies/query/sort.py +27 -0
  213. clearskies/schema.py +82 -0
  214. clearskies/secrets/__init__.py +6 -0
  215. clearskies/secrets/additional_configs/__init__.py +32 -0
  216. clearskies/secrets/additional_configs/mysql_connection_dynamic_producer.py +61 -0
  217. clearskies/secrets/additional_configs/mysql_connection_dynamic_producer_via_ssh_cert_bastion.py +160 -0
  218. clearskies/secrets/akeyless.py +182 -0
  219. clearskies/secrets/exceptions/__init__.py +1 -0
  220. clearskies/secrets/exceptions/not_found.py +2 -0
  221. clearskies/secrets/secrets.py +38 -0
  222. clearskies/security_header.py +8 -0
  223. clearskies/security_headers/__init__.py +11 -0
  224. clearskies/security_headers/cache_control.py +67 -0
  225. clearskies/security_headers/cors.py +50 -0
  226. clearskies/security_headers/csp.py +94 -0
  227. clearskies/security_headers/hsts.py +22 -0
  228. clearskies/security_headers/x_content_type_options.py +0 -0
  229. clearskies/security_headers/x_frame_options.py +0 -0
  230. clearskies/test_base.py +8 -0
  231. clearskies/typing.py +11 -0
  232. clearskies/validator.py +25 -0
  233. clearskies/validators/__init__.py +33 -0
  234. clearskies/validators/after_column.py +62 -0
  235. clearskies/validators/before_column.py +13 -0
  236. clearskies/validators/in_the_future.py +32 -0
  237. clearskies/validators/in_the_future_at_least.py +11 -0
  238. clearskies/validators/in_the_future_at_most.py +10 -0
  239. clearskies/validators/in_the_past.py +32 -0
  240. clearskies/validators/in_the_past_at_least.py +10 -0
  241. clearskies/validators/in_the_past_at_most.py +10 -0
  242. clearskies/validators/maximum_length.py +26 -0
  243. clearskies/validators/maximum_value.py +29 -0
  244. clearskies/validators/minimum_length.py +26 -0
  245. clearskies/validators/minimum_value.py +29 -0
  246. clearskies/validators/required.py +35 -0
  247. clearskies/validators/timedelta.py +59 -0
  248. clearskies/validators/unique.py +31 -0
@@ -0,0 +1,123 @@
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
+ supports_n_plus_one = False
13
+ can_count = True
14
+
15
+ @abstractmethod
16
+ def update(self, id: int | str, data: dict[str, Any], model: clearskies.model.Model) -> dict[str, Any]:
17
+ """Update the record with the given id with the information from the data dictionary."""
18
+ pass
19
+
20
+ @abstractmethod
21
+ def create(self, data: dict[str, Any], model: clearskies.model.Model) -> dict[str, Any]:
22
+ """Create a record with the information from the data dictionary."""
23
+ pass
24
+
25
+ @abstractmethod
26
+ def delete(self, id: int | str, model: clearskies.model.Model) -> bool:
27
+ """Delete the record with the given id."""
28
+ pass
29
+
30
+ @abstractmethod
31
+ def count(self, query: clearskies.query.Query) -> int:
32
+ """Return the number of records which match the given query configuration."""
33
+ pass
34
+
35
+ @abstractmethod
36
+ def records(
37
+ self, query: clearskies.query.Query, next_page_data: dict[str, str | int] | None = None
38
+ ) -> list[dict[str, Any]]:
39
+ """
40
+ Return a list of records that match the given query configuration.
41
+
42
+ next_page_data is used to return data to the caller. Pass in an empty dictionary, and it will be populated
43
+ with the data needed to return the next page of results. If it is still an empty dictionary when returned,
44
+ then there is no additional data.
45
+ """
46
+ pass
47
+
48
+ @abstractmethod
49
+ def validate_pagination_data(self, data: dict[str, Any], case_mapping: Callable[[str], str]) -> str:
50
+ """
51
+ Check if the given dictionary is valid pagination data for the background.
52
+
53
+ Return a string with an error message, or an empty string if the data is valid
54
+ """
55
+ pass
56
+
57
+ @abstractmethod
58
+ def allowed_pagination_keys(self) -> list[str]:
59
+ """
60
+ Return the list of allowed keys in the pagination kwargs for the backend.
61
+
62
+ It must always return keys in snake_case so that the auto casing system can
63
+ adjust on the front-end for consistency.
64
+ """
65
+ pass
66
+
67
+ @abstractmethod
68
+ def documentation_pagination_next_page_response(self, case_mapping: Callable) -> list[Any]:
69
+ """
70
+ Return a list of autodoc schema objects.
71
+
72
+ It will describe the contents of the `next_page` dictionary
73
+ in the pagination section of the response
74
+ """
75
+ pass
76
+
77
+ @abstractmethod
78
+ def documentation_pagination_parameters(self, case_mapping: Callable) -> list[tuple[AutoDocSchema, str]]:
79
+ """
80
+ Return a list of autodoc schema objects describing the allowed input keys to set pagination.
81
+
82
+ It should return a list of tuples, with each tuple corresponding to an input key.
83
+ The first element in the tuple should be the schema, and the second should be the description.
84
+ """
85
+ pass
86
+
87
+ @abstractmethod
88
+ def documentation_pagination_next_page_example(self, case_mapping: Callable) -> dict[str, Any]:
89
+ """
90
+ Return an example for next page documentation.
91
+
92
+ Returns an example (as a simple dictionary) of what the next_page data in the pagination response
93
+ should look like
94
+ """
95
+ pass
96
+
97
+ def column_from_backend(self, column: clearskies.column.Column, value: Any) -> Any:
98
+ """
99
+ Manage transformations from the backend.
100
+
101
+ The idea with this (and `column_to_backend`) is that the transformations to
102
+ and from the backend are mostly determined by the column type - integer, string,
103
+ date, etc... However, there are cases where these are also backend specific: a datetime
104
+ column may be serialized different ways for different databases, a JSON column must be
105
+ serialized for a database but won't be serialized for an API call, etc... Therefore
106
+ we mostly just let the column handle this, but we want the backend to be in charge
107
+ in case it needs to make changes.
108
+ """
109
+ return column.from_backend(value)
110
+
111
+ def column_to_backend(self, column: clearskies.column.Column, backend_data: dict[str, Any]) -> dict[str, Any]:
112
+ """
113
+ Manage transformations to the backend.
114
+
115
+ The idea with this (and `column_from_backend`) is that the transformations to
116
+ and from the backend are mostly determined by the column type - integer, string,
117
+ date, etc... However, there are cases where these are also backend specific: a datetime
118
+ column may be serialized different ways for different databases, a JSON column must be
119
+ serialized for a database but won't be serialized for an API call, etc... Therefore
120
+ we mostly just let the column handle this, but we want the backend to be in charge
121
+ in case it needs to make changes.
122
+ """
123
+ return column.to_backend(backend_data)
@@ -0,0 +1,335 @@
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
+ ]