wherobots-python-dbapi 0.4.0__tar.gz

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.
Files changed (29) hide show
  1. wherobots_python_dbapi-0.4.0/LICENSE +201 -0
  2. wherobots_python_dbapi-0.4.0/PKG-INFO +75 -0
  3. wherobots_python_dbapi-0.4.0/README.md +51 -0
  4. wherobots_python_dbapi-0.4.0/pyproject.toml +41 -0
  5. wherobots_python_dbapi-0.4.0/wherobots/__init__.py +0 -0
  6. wherobots_python_dbapi-0.4.0/wherobots/db/__init__.py +6 -0
  7. wherobots_python_dbapi-0.4.0/wherobots/db/__pycache__/__init__.cpython-311.pyc +0 -0
  8. wherobots_python_dbapi-0.4.0/wherobots/db/__pycache__/__init__.cpython-39.pyc +0 -0
  9. wherobots_python_dbapi-0.4.0/wherobots/db/__pycache__/connection.cpython-311.pyc +0 -0
  10. wherobots_python_dbapi-0.4.0/wherobots/db/__pycache__/connection.cpython-39.pyc +0 -0
  11. wherobots_python_dbapi-0.4.0/wherobots/db/__pycache__/constants.cpython-311.pyc +0 -0
  12. wherobots_python_dbapi-0.4.0/wherobots/db/__pycache__/constants.cpython-39.pyc +0 -0
  13. wherobots_python_dbapi-0.4.0/wherobots/db/__pycache__/cursor.cpython-311.pyc +0 -0
  14. wherobots_python_dbapi-0.4.0/wherobots/db/__pycache__/cursor.cpython-39.pyc +0 -0
  15. wherobots_python_dbapi-0.4.0/wherobots/db/__pycache__/driver.cpython-311.pyc +0 -0
  16. wherobots_python_dbapi-0.4.0/wherobots/db/__pycache__/driver.cpython-39.pyc +0 -0
  17. wherobots_python_dbapi-0.4.0/wherobots/db/__pycache__/errors.cpython-311.pyc +0 -0
  18. wherobots_python_dbapi-0.4.0/wherobots/db/__pycache__/errors.cpython-39.pyc +0 -0
  19. wherobots_python_dbapi-0.4.0/wherobots/db/__pycache__/region.cpython-311.pyc +0 -0
  20. wherobots_python_dbapi-0.4.0/wherobots/db/__pycache__/region.cpython-39.pyc +0 -0
  21. wherobots_python_dbapi-0.4.0/wherobots/db/__pycache__/runtime.cpython-311.pyc +0 -0
  22. wherobots_python_dbapi-0.4.0/wherobots/db/__pycache__/runtime.cpython-39.pyc +0 -0
  23. wherobots_python_dbapi-0.4.0/wherobots/db/connection.py +219 -0
  24. wherobots_python_dbapi-0.4.0/wherobots/db/constants.py +60 -0
  25. wherobots_python_dbapi-0.4.0/wherobots/db/cursor.py +94 -0
  26. wherobots_python_dbapi-0.4.0/wherobots/db/driver.py +159 -0
  27. wherobots_python_dbapi-0.4.0/wherobots/db/errors.py +26 -0
  28. wherobots_python_dbapi-0.4.0/wherobots/db/region.py +5 -0
  29. wherobots_python_dbapi-0.4.0/wherobots/db/runtime.py +21 -0
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,75 @@
1
+ Metadata-Version: 2.1
2
+ Name: wherobots-python-dbapi
3
+ Version: 0.4.0
4
+ Summary: Python DB-API driver for Wherobots DB
5
+ License: Apache 2.0
6
+ Author: Maxime Petazzoni
7
+ Author-email: max@wherobots.com
8
+ Requires-Python: >=3.9,<4.0
9
+ Classifier: License :: Other/Proprietary License
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.9
12
+ Classifier: Programming Language :: Python :: 3.10
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Requires-Dist: StrEnum (>=0.4.15,<0.5.0)
16
+ Requires-Dist: cbor2 (>=5.6.3,<6.0.0)
17
+ Requires-Dist: pandas (>=2.2.2,<3.0.0)
18
+ Requires-Dist: pyarrow (>=15.0.2,<16.0.0)
19
+ Requires-Dist: requests (>=2.31.0,<3.0.0)
20
+ Requires-Dist: tenacity (>=8.2.3,<9.0.0)
21
+ Requires-Dist: websockets (>=12.0,<13.0)
22
+ Description-Content-Type: text/markdown
23
+
24
+ # wherobots-python-dbapi-driver
25
+
26
+ Python DB-API implementation for Wherobots DB. This package implements a
27
+ PEP-0249 compatible driver to programmatically connect to a Wherobots DB
28
+ runtime and execute Spatial SQL queries.
29
+
30
+ ## Installation
31
+
32
+ If you use [Poetry](https://python-poetry.org) in your project, add the
33
+ dependency with `poetry add`:
34
+
35
+ ```
36
+ $ poetry add git+https://github.com/wherobots/wherobots-python-dbapi-driver
37
+ ```
38
+
39
+ Otherwise, just `pip install` it:
40
+
41
+ ```
42
+ $ pip install git+https://github.com/wherobots/wherobots-python-dbapi-driver
43
+ ```
44
+
45
+ ## Usage
46
+
47
+ ```python
48
+ from wherobots.db import connect
49
+ from wherobots.db.region import Region
50
+ from wherobots.db.runtime import Runtime
51
+
52
+ with connect(
53
+ api_key='...',
54
+ runtime=Runtime.SEDONA,
55
+ region=Region.AWS_US_WEST_2) as conn:
56
+ curr = conn.cursor()
57
+ curr.execute("SHOW SCHEMAS IN wherobots_open_data")
58
+ results = curr.fetchall()
59
+ print(results)
60
+ ```
61
+
62
+ The `Cursor` also supports the context manager protocol, so you can use
63
+ it within a `with` statement when needed:
64
+
65
+ ```python
66
+ with connect(...) as conn:
67
+ with conn.cursor() as curr:
68
+ curr.execute(...)
69
+ results = curr.fetchall()
70
+ ```
71
+
72
+ It also implements the `close()` method, as suggested by the PEP-2049
73
+ specification, to support situations where the cursor is wrapped in a
74
+ `contextmanager.closing()`.
75
+
@@ -0,0 +1,51 @@
1
+ # wherobots-python-dbapi-driver
2
+
3
+ Python DB-API implementation for Wherobots DB. This package implements a
4
+ PEP-0249 compatible driver to programmatically connect to a Wherobots DB
5
+ runtime and execute Spatial SQL queries.
6
+
7
+ ## Installation
8
+
9
+ If you use [Poetry](https://python-poetry.org) in your project, add the
10
+ dependency with `poetry add`:
11
+
12
+ ```
13
+ $ poetry add git+https://github.com/wherobots/wherobots-python-dbapi-driver
14
+ ```
15
+
16
+ Otherwise, just `pip install` it:
17
+
18
+ ```
19
+ $ pip install git+https://github.com/wherobots/wherobots-python-dbapi-driver
20
+ ```
21
+
22
+ ## Usage
23
+
24
+ ```python
25
+ from wherobots.db import connect
26
+ from wherobots.db.region import Region
27
+ from wherobots.db.runtime import Runtime
28
+
29
+ with connect(
30
+ api_key='...',
31
+ runtime=Runtime.SEDONA,
32
+ region=Region.AWS_US_WEST_2) as conn:
33
+ curr = conn.cursor()
34
+ curr.execute("SHOW SCHEMAS IN wherobots_open_data")
35
+ results = curr.fetchall()
36
+ print(results)
37
+ ```
38
+
39
+ The `Cursor` also supports the context manager protocol, so you can use
40
+ it within a `with` statement when needed:
41
+
42
+ ```python
43
+ with connect(...) as conn:
44
+ with conn.cursor() as curr:
45
+ curr.execute(...)
46
+ results = curr.fetchall()
47
+ ```
48
+
49
+ It also implements the `close()` method, as suggested by the PEP-2049
50
+ specification, to support situations where the cursor is wrapped in a
51
+ `contextmanager.closing()`.
@@ -0,0 +1,41 @@
1
+ [tool.poetry]
2
+ name = "wherobots-python-dbapi"
3
+ version = "0.4.0"
4
+ description = "Python DB-API driver for Wherobots DB"
5
+ authors = ["Maxime Petazzoni <max@wherobots.com>"]
6
+ license = "Apache 2.0"
7
+ readme = "README.md"
8
+ packages = [{ include = "wherobots" }]
9
+
10
+ [project.urls]
11
+ Homepage = "https://github.com/wherobots/wherobots-python-dbapi-driver"
12
+ Tracker = "https://github.com/wherobots/wherobots-python-dbapi-driver/issues"
13
+
14
+ [tool.poetry.dependencies]
15
+ python = "^3.9"
16
+ requests = "^2.31.0"
17
+ websockets = "^12.0"
18
+ tenacity = "^8.2.3"
19
+ pyarrow = "^15.0.2"
20
+ cbor2 = "^5.6.3"
21
+ pandas = "^2.2.2"
22
+ StrEnum = "^0.4.15"
23
+
24
+ [tool.poetry.group.dev.dependencies]
25
+ mypy = "^1.8.0"
26
+ pytest = "^8.0.2"
27
+ black = "^24.2.0"
28
+ pre-commit = "^3.6.2"
29
+ conventional-pre-commit = "^3.1.0"
30
+ rich = "^13.7.1"
31
+
32
+ [build-system]
33
+ requires = ["poetry-core"]
34
+ build-backend = "poetry.core.masonry.api"
35
+
36
+ [tool.pylint.format]
37
+ max-line-length = "88"
38
+
39
+ [tool.mypy]
40
+ strict = true
41
+ show_error_codes = true
File without changes
@@ -0,0 +1,6 @@
1
+ from .connection import Connection
2
+ from .cursor import Cursor
3
+ from .driver import connect, connect_direct
4
+ from .errors import *
5
+ from .region import Region
6
+ from .runtime import Runtime
@@ -0,0 +1,219 @@
1
+ import json
2
+ import logging
3
+ import threading
4
+ import uuid
5
+ from dataclasses import dataclass
6
+ from typing import Callable, Any
7
+
8
+ import cbor2
9
+ import pyarrow
10
+ import websockets.exceptions
11
+ import websockets.protocol
12
+ import websockets.sync.client
13
+
14
+ from wherobots.db.constants import (
15
+ DEFAULT_READ_TIMEOUT_SECONDS,
16
+ RequestKind,
17
+ EventKind,
18
+ ExecutionState,
19
+ ResultsFormat,
20
+ DataCompression,
21
+ )
22
+ from wherobots.db.cursor import Cursor
23
+ from wherobots.db.errors import NotSupportedError, OperationalError
24
+
25
+ _DEFAULT_RESULTS_FORMAT = ResultsFormat.ARROW
26
+ _DEFAULT_DATA_COMPRESSION = DataCompression.BROTLI
27
+
28
+
29
+ @dataclass
30
+ class Query:
31
+ sql: str
32
+ execution_id: str
33
+ state: ExecutionState
34
+ handler: Callable[[Any], None]
35
+
36
+
37
+ class Connection:
38
+ """
39
+ A PEP-0249 compatible Connection object for Wherobots DB.
40
+
41
+ The connection is backed by the WebSocket connected to the Wherobots SQL session instance.
42
+ Transactions are not supported, so commit() and rollback() raise NotSupportedError.
43
+
44
+ This class handles all the interactions with the remote SQL session, and the details of the
45
+ Wherobots Spatial SQL API protocol. It supports multiple concurrent cursors, each one executing
46
+ a single query at a time.
47
+
48
+ A background thread listens for events from the SQL session, and handles update to the
49
+ corresponding query state. Queries are tracked by their unique execution ID.
50
+ """
51
+
52
+ def __init__(
53
+ self,
54
+ ws: websockets.sync.client.ClientConnection,
55
+ read_timeout: float = DEFAULT_READ_TIMEOUT_SECONDS,
56
+ ):
57
+ self.__ws = ws
58
+ self.__read_timeout = read_timeout
59
+ self.__queries: dict[str, Query] = {}
60
+ self.__thread = threading.Thread(
61
+ target=self.__main_loop, daemon=True, name="wherobots-connection"
62
+ )
63
+ self.__thread.start()
64
+
65
+ def __enter__(self):
66
+ return self
67
+
68
+ def __exit__(self, exc_type, exc_val, exc_tb):
69
+ self.close()
70
+
71
+ def close(self):
72
+ self.__ws.close()
73
+
74
+ def commit(self):
75
+ raise NotSupportedError
76
+
77
+ def rollback(self):
78
+ raise NotSupportedError
79
+
80
+ def cursor(self) -> Cursor:
81
+ return Cursor(self.__execute_sql, self.__cancel_query)
82
+
83
+ def __main_loop(self):
84
+ """Main background loop listening for messages from the SQL session."""
85
+ logging.info("Starting background connection handling loop...")
86
+ while self.__ws.protocol.state < websockets.protocol.State.CLOSING:
87
+ try:
88
+ self.__listen()
89
+ except TimeoutError:
90
+ # Expected, retry next time
91
+ continue
92
+ except websockets.exceptions.ConnectionClosedOK:
93
+ logging.info("Connection closed; stopping main loop.")
94
+ return
95
+ except Exception as e:
96
+ logging.exception("Error handling message from SQL session", exc_info=e)
97
+
98
+ def __listen(self):
99
+ """Waits for the next message from the SQL session and processes it.
100
+
101
+ The code in this method is purposefully defensive to avoid unexpected situations killing the thread.
102
+ """
103
+ message = self.__recv()
104
+ kind = message.get("kind")
105
+ execution_id = message.get("execution_id")
106
+ if not kind or not execution_id:
107
+ # Invalid event.
108
+ return
109
+
110
+ query = self.__queries.get(execution_id)
111
+ if not query:
112
+ logging.warning(
113
+ "Received %s event for unknown execution ID %s", kind, execution_id
114
+ )
115
+ return
116
+
117
+ if kind == EventKind.STATE_UPDATED:
118
+ try:
119
+ query.state = ExecutionState[message["state"].upper()]
120
+ logging.info("Query %s is now %s.", execution_id, query.state)
121
+ except KeyError:
122
+ logging.warning("Invalid state update message for %s", execution_id)
123
+ return
124
+
125
+ # Incoming state transitions are handled here.
126
+ if query.state == ExecutionState.SUCCEEDED:
127
+ self.__request_results(execution_id)
128
+ elif query.state == ExecutionState.FAILED:
129
+ query.handler(OperationalError("Query execution failed"))
130
+
131
+ elif kind == EventKind.EXECUTION_RESULT:
132
+ results = message.get("results")
133
+ if not results or not isinstance(results, dict):
134
+ logging.warning("Got no results back from %s.", execution_id)
135
+ return
136
+
137
+ result_bytes = results.get("result_bytes")
138
+ result_format = results.get("format")
139
+ result_compression = results.get("compression")
140
+ logging.info(
141
+ "Received %d bytes of %s-compressed %s results from %s.",
142
+ len(result_bytes),
143
+ result_compression,
144
+ result_format,
145
+ execution_id,
146
+ )
147
+
148
+ query.state = ExecutionState.COMPLETED
149
+ if result_format == ResultsFormat.JSON:
150
+ query.handler(json.loads(result_bytes.decode("utf-8")))
151
+ elif result_format == ResultsFormat.ARROW:
152
+ buffer = pyarrow.py_buffer(result_bytes)
153
+ stream = pyarrow.input_stream(buffer, result_compression)
154
+ with pyarrow.ipc.open_stream(stream) as reader:
155
+ query.handler(reader.read_pandas())
156
+ else:
157
+ query.handler(
158
+ OperationalError(
159
+ f"Unsupported results format {result_format}"
160
+ )
161
+ )
162
+ elif kind == EventKind.ERROR:
163
+ query.state = ExecutionState.FAILED
164
+ error = message.get("message")
165
+ query.handler(OperationalError(error))
166
+ else:
167
+ logging.warning("Received unknown %s event!", kind)
168
+
169
+ def __send(self, message: dict[str, Any]) -> None:
170
+ self.__ws.send(json.dumps(message))
171
+
172
+ def __recv(self) -> dict[str, Any]:
173
+ frame = self.__ws.recv(timeout=self.__read_timeout)
174
+ if isinstance(frame, str):
175
+ message = json.loads(frame)
176
+ elif isinstance(frame, bytes):
177
+ message = cbor2.loads(frame)
178
+ else:
179
+ raise ValueError("Unexpected frame type received")
180
+ return message
181
+
182
+ def __execute_sql(self, sql: str, handler: Callable[[Any], None]) -> str:
183
+ """Triggers the execution of the given SQL query."""
184
+ execution_id = str(uuid.uuid4())
185
+ request = {
186
+ "kind": RequestKind.EXECUTE_SQL.value,
187
+ "execution_id": execution_id,
188
+ "statement": sql,
189
+ }
190
+
191
+ self.__queries[execution_id] = Query(
192
+ sql=sql,
193
+ execution_id=execution_id,
194
+ state=ExecutionState.EXECUTION_REQUESTED,
195
+ handler=handler,
196
+ )
197
+ self.__send(request)
198
+ return execution_id
199
+
200
+ def __request_results(self, execution_id: str) -> None:
201
+ query = self.__queries.get(execution_id)
202
+ if not query:
203
+ return
204
+
205
+ request = {
206
+ "kind": RequestKind.RETRIEVE_RESULTS.value,
207
+ "execution_id": execution_id,
208
+ "format": _DEFAULT_RESULTS_FORMAT.value,
209
+ "compression": _DEFAULT_DATA_COMPRESSION.value,
210
+ }
211
+ query.state = ExecutionState.RESULTS_REQUESTED
212
+ logging.info("Requesting results from %s ...", execution_id)
213
+ self.__send(request)
214
+
215
+ def __cancel_query(self, execution_id: str) -> None:
216
+ query = self.__queries.pop(execution_id)
217
+ if query:
218
+ logging.info("Cancelled query %s.", execution_id)
219
+ # TODO: when protocol supports it, send cancellation request.
@@ -0,0 +1,60 @@
1
+ from enum import auto
2
+ from strenum import LowercaseStrEnum
3
+
4
+ from .region import Region
5
+ from .runtime import Runtime
6
+
7
+
8
+ DEFAULT_ENDPOINT: str = "api.wherobots.services" # "api.cloud.wherobots.com"
9
+ STAGING_ENDPOINT: str = "api.staging.wherobots.services" # "api.staging.wherobots.com"
10
+ DEFAULT_RUNTIME: Runtime = Runtime.SEDONA
11
+ DEFAULT_REGION: Region = Region.AWS_US_WEST_2
12
+ DEFAULT_READ_TIMEOUT_SECONDS: float = 0.25
13
+ DEFAULT_SESSION_WAIT_TIMEOUT_SECONDS: float = 300
14
+ MAX_MESSAGE_SIZE: int = 100 * 2**20 # 100MiB
15
+
16
+
17
+ class ExecutionState(LowercaseStrEnum):
18
+ IDLE = auto()
19
+ "Not executing any operation."
20
+
21
+ EXECUTION_REQUESTED = auto()
22
+ "Execution of a query has been requested by the driver."
23
+
24
+ RUNNING = auto()
25
+ "The SQL session has reported the query is running."
26
+
27
+ SUCCEEDED = auto()
28
+ "The SQL session has reported the query has completed successfully."
29
+
30
+ FAILED = auto()
31
+ "The SQL session has reported the query has failed."
32
+
33
+ RESULTS_REQUESTED = auto()
34
+ "The driver has requested the query results from the SQL session."
35
+
36
+ COMPLETED = auto()
37
+ "The driver has completed processing the query results."
38
+
39
+ def is_terminal_state(self):
40
+ return self in (ExecutionState.COMPLETED, ExecutionState.FAILED)
41
+
42
+
43
+ class RequestKind(LowercaseStrEnum):
44
+ EXECUTE_SQL = auto()
45
+ RETRIEVE_RESULTS = auto()
46
+
47
+
48
+ class EventKind(LowercaseStrEnum):
49
+ STATE_UPDATED = auto()
50
+ EXECUTION_RESULT = auto()
51
+ ERROR = auto()
52
+
53
+
54
+ class ResultsFormat(LowercaseStrEnum):
55
+ JSON = auto()
56
+ ARROW = auto()
57
+
58
+
59
+ class DataCompression(LowercaseStrEnum):
60
+ BROTLI = auto()
@@ -0,0 +1,94 @@
1
+ import queue
2
+ from typing import Any, Optional
3
+
4
+ from .errors import ProgrammingError, DatabaseError
5
+
6
+
7
+ class Cursor:
8
+
9
+ def __init__(self, exec_fn, cancel_fn):
10
+ self.__exec_fn = exec_fn
11
+ self.__cancel_fn = cancel_fn
12
+
13
+ self.__queue: queue.Queue = queue.Queue()
14
+ self.__results: Optional[list[Any]] = None
15
+ self.__current_execution_id: Optional[str] = None
16
+ self.__current_row: int = 0
17
+
18
+ # Description and row count are set by the last executed operation.
19
+ # Their default values are defined by PEP-0249.
20
+ self.__description: Optional[str] = None
21
+ self.__rowcount: int = -1
22
+
23
+ # Array-size is also defined by PEP-0249 and is expected to be read/writable.
24
+ self.arraysize: int = 1
25
+
26
+ @property
27
+ def description(self) -> Optional[str]:
28
+ return self.__description
29
+
30
+ @property
31
+ def rowcount(self) -> int:
32
+ return self.__rowcount
33
+
34
+ def __on_execution_result(self, result) -> None:
35
+ self.__queue.put(result)
36
+
37
+ def __get_results(self) -> Optional[list[Any]]:
38
+ if not self.__current_execution_id:
39
+ raise ProgrammingError("No query has been executed yet")
40
+ if self.__results is not None:
41
+ return self.__results
42
+
43
+ result = self.__queue.get()
44
+ if isinstance(result, DatabaseError):
45
+ raise result
46
+ self.__rowcount = len(result)
47
+ self.__results = result
48
+ return self.__results
49
+
50
+ def execute(self, operation: str, parameters: dict[str, Any] = None):
51
+ if self.__current_execution_id:
52
+ self.__cancel_fn(self.__current_execution_id)
53
+
54
+ self.__results = None
55
+ self.__current_row = 0
56
+ self.__rowcount = -1
57
+
58
+ sql = operation.format(**(parameters or {}))
59
+ self.__current_execution_id = self.__exec_fn(sql, self.__on_execution_result)
60
+
61
+ def executemany(self, operation: str, seq_of_parameters: list[dict[str, Any]]):
62
+ raise NotImplementedError
63
+
64
+ def fetchone(self):
65
+ results = self.__get_results()[self.__current_row :]
66
+ if not results:
67
+ return None
68
+ self.__current_row += 1
69
+ return results[0]
70
+
71
+ def fetchmany(self, size: int = None):
72
+ size = size or self.arraysize
73
+ results = self.__get_results()[self.__current_row : self.__current_row + size]
74
+ self.__current_row += size
75
+ return results
76
+
77
+ def fetchall(self):
78
+ return self.__get_results()[self.__current_row :]
79
+
80
+ def close(self):
81
+ """Close the cursor."""
82
+ pass
83
+
84
+ def __iter__(self):
85
+ return self
86
+
87
+ def __next__(self):
88
+ raise StopIteration
89
+
90
+ def __enter__(self):
91
+ return self
92
+
93
+ def __exit__(self, exc_type, exc_val, exc_tb):
94
+ self.close()
@@ -0,0 +1,159 @@
1
+ """Wherobots DB driver.
2
+
3
+ A PEP-0249 compatible driver for interfacing with Wherobots DB.
4
+ """
5
+
6
+ import logging
7
+ import urllib.parse
8
+ import queue
9
+ import requests
10
+ import tenacity
11
+ import threading
12
+ import websockets.sync.client
13
+
14
+ from .constants import (
15
+ DEFAULT_ENDPOINT,
16
+ DEFAULT_REGION,
17
+ DEFAULT_RUNTIME,
18
+ DEFAULT_READ_TIMEOUT_SECONDS,
19
+ DEFAULT_SESSION_WAIT_TIMEOUT_SECONDS,
20
+ MAX_MESSAGE_SIZE,
21
+ )
22
+ from .errors import (
23
+ InterfaceError,
24
+ OperationalError,
25
+ )
26
+ from .region import Region
27
+ from .runtime import Runtime
28
+ from .connection import Connection
29
+
30
+ apilevel = "2.0"
31
+ threadsafety = 1
32
+ paramstyle = "pyformat"
33
+
34
+
35
+ def connect(
36
+ host: str = DEFAULT_ENDPOINT,
37
+ token: str = None,
38
+ api_key: str = None,
39
+ runtime: Runtime = None,
40
+ region: Region = None,
41
+ wait_timeout: float = DEFAULT_SESSION_WAIT_TIMEOUT_SECONDS,
42
+ read_timeout: float = DEFAULT_READ_TIMEOUT_SECONDS,
43
+ ) -> Connection:
44
+ if not token and not api_key:
45
+ raise ValueError("At least one of `token` or `api_key` is required")
46
+ if token and api_key:
47
+ raise ValueError("`token` and `api_key` can't be both provided")
48
+
49
+ headers = {}
50
+ if token:
51
+ headers["Authorization"] = f"Bearer {token}"
52
+ elif api_key:
53
+ headers["X-API-Key"] = api_key
54
+
55
+ runtime = runtime or DEFAULT_RUNTIME
56
+ region = region or DEFAULT_REGION
57
+
58
+ logging.info(
59
+ "Requesting %s/%s runtime in %s from %s ...",
60
+ runtime.name,
61
+ runtime.value,
62
+ region.value,
63
+ host,
64
+ )
65
+
66
+ # Default to HTTPS if the hostname doesn't explicitly specify a scheme.
67
+ if not host.startswith("http:"):
68
+ host = f"https://{host}"
69
+
70
+ try:
71
+ resp = requests.post(
72
+ url=f"{host}/sql/session",
73
+ params={"region": region.value},
74
+ json={"runtimeId": runtime.value},
75
+ headers=headers,
76
+ )
77
+ resp.raise_for_status()
78
+ except requests.HTTPError as e:
79
+ raise InterfaceError("Failed to create SQL session!", e)
80
+
81
+ # At this point we've been redirected to /sql/session/{session_id}, which we'll need to keep polling until the
82
+ # session is in READY state.
83
+ session_id_url = resp.url
84
+
85
+ @tenacity.retry(
86
+ stop=tenacity.stop_after_delay(wait_timeout),
87
+ wait=tenacity.wait_exponential(multiplier=1, min=1, max=5),
88
+ retry=tenacity.retry_if_not_exception_type(
89
+ (requests.HTTPError, OperationalError)
90
+ ),
91
+ )
92
+ def get_session_uri() -> str:
93
+ r = requests.get(session_id_url, headers=headers)
94
+ r.raise_for_status()
95
+ payload = r.json()
96
+ status = payload.get("status")
97
+ logging.info(" ... %s", status)
98
+ if status in ("REQUESTED", "DEPLOYING", "DEPLOYED", "INITIALIZING"):
99
+ raise tenacity.TryAgain("SQL Session is not ready yet")
100
+ elif status == "READY":
101
+ return payload["appMeta"]["url"]
102
+ else:
103
+ logging.error("SQL session creation failed: %s; should not retry.", status)
104
+ raise OperationalError(f"Failed to create SQL session: {status}")
105
+
106
+ try:
107
+ logging.info("Getting SQL session status from %s ...", session_id_url)
108
+ session_uri = get_session_uri()
109
+ except Exception as e:
110
+ raise InterfaceError("Could not acquire SQL session!", e)
111
+
112
+ return connect_direct(
113
+ uri=http_to_ws(session_uri),
114
+ headers=headers,
115
+ read_timeout=read_timeout,
116
+ )
117
+
118
+
119
+ def http_to_ws(uri: str) -> str:
120
+ """Converts an HTTP URI to a WebSocket URI."""
121
+ parsed = urllib.parse.urlparse(uri)
122
+ for from_scheme, to_scheme in [("http", "ws"), ("https", "wss")]:
123
+ if parsed.scheme == from_scheme:
124
+ parsed = parsed._replace(scheme=to_scheme)
125
+ return str(urllib.parse.urlunparse(parsed))
126
+
127
+
128
+ def connect_direct(
129
+ uri: str,
130
+ headers: dict[str, str] = None,
131
+ read_timeout: float = DEFAULT_READ_TIMEOUT_SECONDS,
132
+ ) -> Connection:
133
+ q = queue.SimpleQueue()
134
+
135
+ def create_ws_connection():
136
+ try:
137
+ logging.info("Connecting to SQL session at %s ...", uri)
138
+ ws = websockets.sync.client.connect(
139
+ uri=uri,
140
+ additional_headers=headers,
141
+ max_size=MAX_MESSAGE_SIZE,
142
+ )
143
+ q.put(ws)
144
+ except Exception as e:
145
+ q.put(e)
146
+
147
+ dt = threading.Thread(
148
+ name="wherobots-ws-connector",
149
+ target=create_ws_connection,
150
+ daemon=True,
151
+ )
152
+ dt.start()
153
+ dt.join()
154
+
155
+ result = q.get()
156
+ if isinstance(result, Exception):
157
+ raise InterfaceError("Failed to connect to SQL session!") from result
158
+
159
+ return Connection(result, read_timeout)
@@ -0,0 +1,26 @@
1
+ class Error(Exception):
2
+ pass
3
+
4
+
5
+ class InterfaceError(Error):
6
+ pass
7
+
8
+
9
+ class DatabaseError(Error):
10
+ pass
11
+
12
+
13
+ class InternalError(DatabaseError):
14
+ pass
15
+
16
+
17
+ class OperationalError(DatabaseError):
18
+ pass
19
+
20
+
21
+ class ProgrammingError(DatabaseError):
22
+ pass
23
+
24
+
25
+ class NotSupportedError(DatabaseError):
26
+ pass
@@ -0,0 +1,5 @@
1
+ from enum import Enum
2
+
3
+
4
+ class Region(Enum):
5
+ AWS_US_WEST_2 = "aws-us-west-2"
@@ -0,0 +1,21 @@
1
+ from enum import Enum
2
+
3
+
4
+ class Runtime(Enum):
5
+ SEDONA = "TINY"
6
+ SAN_FRANCISCO = "SMALL"
7
+ NEW_YORK = "MEDIUM"
8
+ CAIRO = "LARGE"
9
+ DELHI = "XLARGE"
10
+ TOKYO = "XXLARGE"
11
+ ATLANTIS = "4x-large"
12
+
13
+ NEW_YORK_HIMEM = "medium-himem"
14
+ CAIRO_HIMEM = "large-himem"
15
+ DELHI_HIMEM = "x-large-himem"
16
+ TOKYO_HIMEM = "2x-large-himem"
17
+ ATLANTIS_HIMEM = "4x-large-himem"
18
+
19
+ SEDONA_GPU = "tiny-a10-gpu"
20
+ SAN_FRANCISCO_GPU = "small-a10-gpu"
21
+ NEW_YORK_GPU = "medium-a10-gpu"