mapepire-python 1.0.1__tar.gz → 2.0.1__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.
- {mapepire_python-1.0.1 → mapepire_python-2.0.1}/PKG-INFO +22 -2
- {mapepire_python-1.0.1 → mapepire_python-2.0.1}/README.md +19 -0
- {mapepire_python-1.0.1 → mapepire_python-2.0.1}/mapepire_python/async_base_job.py +36 -7
- {mapepire_python-1.0.1 → mapepire_python-2.0.1}/mapepire_python/asyncio/cursor.py +15 -3
- {mapepire_python-1.0.1 → mapepire_python-2.0.1}/mapepire_python/client/query.py +49 -11
- {mapepire_python-1.0.1 → mapepire_python-2.0.1}/mapepire_python/client/sql_job.py +32 -4
- {mapepire_python-1.0.1 → mapepire_python-2.0.1}/mapepire_python/client/websocket_client.py +2 -0
- {mapepire_python-1.0.1 → mapepire_python-2.0.1}/mapepire_python/core/cursor.py +32 -4
- mapepire_python-2.0.1/mapepire_python/core/exceptions.py +106 -0
- {mapepire_python-1.0.1 → mapepire_python-2.0.1}/mapepire_python/data_types.py +28 -0
- {mapepire_python-1.0.1 → mapepire_python-2.0.1}/mapepire_python/pool/async_websocket_client.py +2 -0
- {mapepire_python-1.0.1 → mapepire_python-2.0.1}/mapepire_python/pool/pool_query.py +39 -12
- {mapepire_python-1.0.1 → mapepire_python-2.0.1}/mapepire_python/version.py +1 -1
- {mapepire_python-1.0.1 → mapepire_python-2.0.1}/mapepire_python/websocket.py +26 -25
- {mapepire_python-1.0.1 → mapepire_python-2.0.1}/mapepire_python.egg-info/PKG-INFO +22 -2
- {mapepire_python-1.0.1 → mapepire_python-2.0.1}/mapepire_python.egg-info/requires.txt +2 -1
- {mapepire_python-1.0.1 → mapepire_python-2.0.1}/pyproject.toml +2 -1
- mapepire_python-1.0.1/mapepire_python/core/exceptions.py +0 -95
- {mapepire_python-1.0.1 → mapepire_python-2.0.1}/LICENSE +0 -0
- {mapepire_python-1.0.1 → mapepire_python-2.0.1}/mapepire_python/__init__.py +0 -0
- {mapepire_python-1.0.1 → mapepire_python-2.0.1}/mapepire_python/asyncio/__init__.py +0 -0
- {mapepire_python-1.0.1 → mapepire_python-2.0.1}/mapepire_python/asyncio/connection.py +0 -0
- {mapepire_python-1.0.1 → mapepire_python-2.0.1}/mapepire_python/authentication/kerberosTokenProvider.py +0 -0
- {mapepire_python-1.0.1 → mapepire_python-2.0.1}/mapepire_python/base_job.py +0 -0
- {mapepire_python-1.0.1 → mapepire_python-2.0.1}/mapepire_python/client/__init__.py +0 -0
- {mapepire_python-1.0.1 → mapepire_python-2.0.1}/mapepire_python/client/async_sql_job.py +0 -0
- {mapepire_python-1.0.1 → mapepire_python-2.0.1}/mapepire_python/core/__init__.py +0 -0
- {mapepire_python-1.0.1 → mapepire_python-2.0.1}/mapepire_python/core/connection.py +0 -0
- {mapepire_python-1.0.1 → mapepire_python-2.0.1}/mapepire_python/core/utils.py +0 -0
- {mapepire_python-1.0.1 → mapepire_python-2.0.1}/mapepire_python/pool/__init__.py +0 -0
- {mapepire_python-1.0.1 → mapepire_python-2.0.1}/mapepire_python/pool/pool_client.py +0 -0
- {mapepire_python-1.0.1 → mapepire_python-2.0.1}/mapepire_python/pool/pool_job.py +0 -0
- {mapepire_python-1.0.1 → mapepire_python-2.0.1}/mapepire_python/py.typed +0 -0
- {mapepire_python-1.0.1 → mapepire_python-2.0.1}/mapepire_python/query_manager.py +0 -0
- {mapepire_python-1.0.1 → mapepire_python-2.0.1}/mapepire_python/ssl.py +0 -0
- {mapepire_python-1.0.1 → mapepire_python-2.0.1}/mapepire_python.egg-info/SOURCES.txt +0 -0
- {mapepire_python-1.0.1 → mapepire_python-2.0.1}/mapepire_python.egg-info/dependency_links.txt +0 -0
- {mapepire_python-1.0.1 → mapepire_python-2.0.1}/mapepire_python.egg-info/top_level.txt +0 -0
- {mapepire_python-1.0.1 → mapepire_python-2.0.1}/setup.cfg +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: mapepire-python
|
|
3
|
-
Version:
|
|
3
|
+
Version: 2.0.1
|
|
4
4
|
Author-email: Adam Shedivy <adam.shedivy@ibm.com>, Irfan Sharif <IrfanSharif@ibm.com>
|
|
5
5
|
License: Apache License
|
|
6
6
|
Version 2.0, January 2004
|
|
@@ -225,7 +225,7 @@ Requires-Dist: pywin32; sys_platform == "win32" and extra == "kerberos"
|
|
|
225
225
|
Provides-Extra: dev
|
|
226
226
|
Requires-Dist: ruff<0.16,>=0.15; extra == "dev"
|
|
227
227
|
Requires-Dist: mypy<2.4,>=1.0; extra == "dev"
|
|
228
|
-
Requires-Dist: black<27.0,>=
|
|
228
|
+
Requires-Dist: black<27.0,>=26.10.0; extra == "dev"
|
|
229
229
|
Requires-Dist: isort<8.1,>=5.12; extra == "dev"
|
|
230
230
|
Requires-Dist: pytest>=9.0.3; extra == "dev"
|
|
231
231
|
Requires-Dist: pep249abc; extra == "dev"
|
|
@@ -237,6 +237,7 @@ Requires-Dist: setuptools; extra == "dev"
|
|
|
237
237
|
Requires-Dist: wheel; extra == "dev"
|
|
238
238
|
Requires-Dist: packaging; extra == "dev"
|
|
239
239
|
Requires-Dist: pre-commit; extra == "dev"
|
|
240
|
+
Requires-Dist: virtualenv>=21.15.0; extra == "dev"
|
|
240
241
|
Requires-Dist: python-dotenv; extra == "dev"
|
|
241
242
|
Requires-Dist: pytest-env; extra == "dev"
|
|
242
243
|
Dynamic: license-file
|
|
@@ -763,6 +764,25 @@ with SQLJob("./mapepire.ini") as sql_job:
|
|
|
763
764
|
print(result)
|
|
764
765
|
```
|
|
765
766
|
|
|
767
|
+
### Run CL commands
|
|
768
|
+
|
|
769
|
+
- `clcommand()` runs a CL command in the SQL job (`cl` request)
|
|
770
|
+
- `rcclcommand()` runs it in the remote command job (`rccl` request)
|
|
771
|
+
|
|
772
|
+
Both need Mapepire Server v2.5.0 or later, which added `rccl` and the message format these methods return.
|
|
773
|
+
|
|
774
|
+
```python
|
|
775
|
+
from mapepire_python import SQLJob
|
|
776
|
+
|
|
777
|
+
with SQLJob("./mapepire.ini") as sql_job:
|
|
778
|
+
result = sql_job.rcclcommand("CHKOBJ OBJ(QSYS) OBJTYPE(*LIB)")
|
|
779
|
+
print(result.success, result.data)
|
|
780
|
+
```
|
|
781
|
+
|
|
782
|
+
Both return a `CLCommandResult` whose `data` is the list of messages the command produced. A failed command returns `success=False` and `error` instead of raising. `PoolJob` has async versions of both methods.
|
|
783
|
+
|
|
784
|
+
CL commands can also go through `query()` with `QueryOptions(isClCommand=True)` or `QueryOptions(isRemoteClCommand=True)`, or through the sync PEP 249 `Cursor` with `cursor.execute(cmd, isRemoteClCommand=True)`.
|
|
785
|
+
|
|
766
786
|
## 2. Using the `PoolJob` object to run queries asynchronously
|
|
767
787
|
|
|
768
788
|
The `PoolJob` object can be used to create and run queries asynchronously:
|
|
@@ -520,6 +520,25 @@ with SQLJob("./mapepire.ini") as sql_job:
|
|
|
520
520
|
print(result)
|
|
521
521
|
```
|
|
522
522
|
|
|
523
|
+
### Run CL commands
|
|
524
|
+
|
|
525
|
+
- `clcommand()` runs a CL command in the SQL job (`cl` request)
|
|
526
|
+
- `rcclcommand()` runs it in the remote command job (`rccl` request)
|
|
527
|
+
|
|
528
|
+
Both need Mapepire Server v2.5.0 or later, which added `rccl` and the message format these methods return.
|
|
529
|
+
|
|
530
|
+
```python
|
|
531
|
+
from mapepire_python import SQLJob
|
|
532
|
+
|
|
533
|
+
with SQLJob("./mapepire.ini") as sql_job:
|
|
534
|
+
result = sql_job.rcclcommand("CHKOBJ OBJ(QSYS) OBJTYPE(*LIB)")
|
|
535
|
+
print(result.success, result.data)
|
|
536
|
+
```
|
|
537
|
+
|
|
538
|
+
Both return a `CLCommandResult` whose `data` is the list of messages the command produced. A failed command returns `success=False` and `error` instead of raising. `PoolJob` has async versions of both methods.
|
|
539
|
+
|
|
540
|
+
CL commands can also go through `query()` with `QueryOptions(isClCommand=True)` or `QueryOptions(isRemoteClCommand=True)`, or through the sync PEP 249 `Cursor` with `cursor.execute(cmd, isRemoteClCommand=True)`.
|
|
541
|
+
|
|
523
542
|
## 2. Using the `PoolJob` object to run queries asynchronously
|
|
524
543
|
|
|
525
544
|
The `PoolJob` object can be used to create and run queries asynchronously:
|
|
@@ -6,16 +6,22 @@ from pathlib import Path
|
|
|
6
6
|
from typing import Any, Dict, Optional, Union
|
|
7
7
|
|
|
8
8
|
import websockets
|
|
9
|
+
from pep249 import Error, OperationalError
|
|
9
10
|
from websockets.asyncio.client import ClientConnection
|
|
10
11
|
|
|
11
12
|
from .base_job import BaseJob
|
|
12
13
|
from .data_types import (
|
|
14
|
+
BaseRequest,
|
|
15
|
+
CLCommandResult,
|
|
16
|
+
ClRequest,
|
|
13
17
|
ConnectionResult,
|
|
14
18
|
ConnectRequest,
|
|
15
19
|
DaemonServer,
|
|
16
20
|
JobStatus,
|
|
17
21
|
QueryOptions,
|
|
22
|
+
RcclRequest,
|
|
18
23
|
)
|
|
24
|
+
from .websocket import handle_ws_errors
|
|
19
25
|
|
|
20
26
|
__all__ = ["AsyncBaseJob"]
|
|
21
27
|
|
|
@@ -72,11 +78,12 @@ class AsyncBaseJob(BaseJob):
|
|
|
72
78
|
socket = AsyncWebSocketConnection(db2_server)
|
|
73
79
|
return await socket.connect()
|
|
74
80
|
|
|
81
|
+
@handle_ws_errors
|
|
75
82
|
async def send(self, content: str) -> Dict[str, Any]:
|
|
76
83
|
logger.debug("sending data: %s", content)
|
|
77
84
|
req = json.loads(content)
|
|
78
85
|
if self.socket is None:
|
|
79
|
-
raise
|
|
86
|
+
raise OperationalError("Socket is not connected")
|
|
80
87
|
req_id = req["id"]
|
|
81
88
|
# Register the pending future *before* awaiting the socket so the
|
|
82
89
|
# in-flight count (and Busy status) is reflected synchronously, before
|
|
@@ -98,7 +105,9 @@ class AsyncBaseJob(BaseJob):
|
|
|
98
105
|
|
|
99
106
|
def get_running_count(self) -> int:
|
|
100
107
|
count = len(self._pending)
|
|
101
|
-
logger.debug(
|
|
108
|
+
logger.debug(
|
|
109
|
+
"--- running count %s: %d, status: %s", self.unique_id, count, self.get_status()
|
|
110
|
+
)
|
|
102
111
|
return count
|
|
103
112
|
|
|
104
113
|
async def connect( # type: ignore[override]
|
|
@@ -134,7 +143,7 @@ class AsyncBaseJob(BaseJob):
|
|
|
134
143
|
self.status = JobStatus.NotStarted
|
|
135
144
|
logger.error("Connection failed: %s", result.error or "unknown error")
|
|
136
145
|
await self.close()
|
|
137
|
-
raise
|
|
146
|
+
raise OperationalError(result.error or "Failed to connect to server")
|
|
138
147
|
|
|
139
148
|
self._is_tracing_channel_data = False
|
|
140
149
|
|
|
@@ -154,7 +163,7 @@ class AsyncBaseJob(BaseJob):
|
|
|
154
163
|
# Fail any still-in-flight requests so their awaiters don't hang forever.
|
|
155
164
|
for future in self._pending.values():
|
|
156
165
|
if not future.done():
|
|
157
|
-
future.
|
|
166
|
+
future.set_exception(OperationalError("Connection to Mapepire server closed"))
|
|
158
167
|
self._pending.clear()
|
|
159
168
|
|
|
160
169
|
async def message_handler(self):
|
|
@@ -175,7 +184,8 @@ class AsyncBaseJob(BaseJob):
|
|
|
175
184
|
else:
|
|
176
185
|
logger.debug("No pending request for response id: %s", req_id)
|
|
177
186
|
except websockets.exceptions.ConnectionClosedError:
|
|
178
|
-
|
|
187
|
+
pass
|
|
188
|
+
await self.dispose()
|
|
179
189
|
|
|
180
190
|
def query(
|
|
181
191
|
self,
|
|
@@ -206,11 +216,30 @@ class AsyncBaseJob(BaseJob):
|
|
|
206
216
|
try:
|
|
207
217
|
async with self.query(sql, opts) as query:
|
|
208
218
|
return await query.run(rows_to_fetch=rows_to_fetch)
|
|
219
|
+
except Error:
|
|
220
|
+
raise
|
|
209
221
|
except Exception as e:
|
|
210
222
|
raise RuntimeError(f"Failed to run query: {e}") from e
|
|
211
223
|
|
|
212
|
-
async def
|
|
224
|
+
async def clcommand(self, cmd: str) -> CLCommandResult:
|
|
225
|
+
"""Run a CL command in the SQL job (``cl``)."""
|
|
226
|
+
return await self._run_cl_command(cmd, remote=False)
|
|
227
|
+
|
|
228
|
+
async def rcclcommand(self, cmd: str) -> CLCommandResult:
|
|
229
|
+
"""Run a CL command in the remote command job (``rccl``, Mapepire Server v2.5.0+)."""
|
|
230
|
+
return await self._run_cl_command(cmd, remote=True)
|
|
231
|
+
|
|
232
|
+
async def _run_cl_command(self, cmd: str, remote: bool) -> CLCommandResult:
|
|
233
|
+
request: BaseRequest = (
|
|
234
|
+
RcclRequest(id=self._get_unique_id("rcclcommand"), cmd=cmd)
|
|
235
|
+
if remote
|
|
236
|
+
else ClRequest(id=self._get_unique_id("clcommand"), cmd=cmd)
|
|
237
|
+
)
|
|
238
|
+
return CLCommandResult.from_dict( # type: ignore[attr-defined]
|
|
239
|
+
await self.send(json.dumps(dataclasses.asdict(request)))
|
|
240
|
+
)
|
|
241
|
+
|
|
242
|
+
async def close(self) -> None: # type: ignore[override]
|
|
213
243
|
logger.info("Closing job %s", self.id)
|
|
214
244
|
await self.dispose()
|
|
215
245
|
self.status = JobStatus.Ended
|
|
216
|
-
|
|
@@ -15,6 +15,7 @@ if TYPE_CHECKING:
|
|
|
15
15
|
from .connection import AsyncConnection
|
|
16
16
|
|
|
17
17
|
from ..client.async_sql_job import AsyncSQLJob
|
|
18
|
+
from ..core.exceptions import convert_runtime_errors
|
|
18
19
|
from ..core.utils import DB_TYPE_MAP, row_to_tuple
|
|
19
20
|
from ..data_types import QueryOptions
|
|
20
21
|
from ..pool.pool_query import PoolQuery
|
|
@@ -35,6 +36,9 @@ class AsyncCursor(
|
|
|
35
36
|
no thread delegation.
|
|
36
37
|
"""
|
|
37
38
|
|
|
39
|
+
# Most rows asked for in one sqlmore, matching the sync Cursor.
|
|
40
|
+
max_fetch_size = 1_000
|
|
41
|
+
|
|
38
42
|
def __init__(self, connection: "AsyncConnection", job: AsyncSQLJob) -> None:
|
|
39
43
|
super().__init__()
|
|
40
44
|
self._connection = weakref.proxy(connection)
|
|
@@ -76,11 +80,13 @@ class AsyncCursor(
|
|
|
76
80
|
def setoutputsize(self, size: int, column: Optional[int] = None) -> None:
|
|
77
81
|
pass
|
|
78
82
|
|
|
83
|
+
@convert_runtime_errors
|
|
79
84
|
async def execute(
|
|
80
85
|
self, operation: SQLQuery, parameters: Optional[QueryParameters] = None
|
|
81
86
|
) -> "AsyncCursor":
|
|
82
87
|
logger.debug("Executing statement")
|
|
83
|
-
|
|
88
|
+
# Keyed rows collapse duplicate column names; tuples are positional anyway.
|
|
89
|
+
opts = QueryOptions(parameters=parameters, isTerseResults=True)
|
|
84
90
|
self._query = self._job.query(operation, opts=opts)
|
|
85
91
|
result = await self._query.run()
|
|
86
92
|
self._buffer = list(result.data or [])
|
|
@@ -100,6 +106,7 @@ class AsyncCursor(
|
|
|
100
106
|
await self.execute(operation, params)
|
|
101
107
|
return self
|
|
102
108
|
|
|
109
|
+
@convert_runtime_errors
|
|
103
110
|
async def fetchone(self) -> Optional[ResultRow]:
|
|
104
111
|
if self._buffer:
|
|
105
112
|
return row_to_tuple(self._buffer.pop(0), self._metadata)
|
|
@@ -110,6 +117,7 @@ class AsyncCursor(
|
|
|
110
117
|
self._buffer.extend(result.data or [])
|
|
111
118
|
return row_to_tuple(self._buffer.pop(0), self._metadata) if self._buffer else None
|
|
112
119
|
|
|
120
|
+
@convert_runtime_errors
|
|
113
121
|
async def fetchmany(self, size: Optional[int] = None) -> ResultSet:
|
|
114
122
|
if size is None:
|
|
115
123
|
size = self.arraysize
|
|
@@ -120,16 +128,18 @@ class AsyncCursor(
|
|
|
120
128
|
elif self._is_done or self._query is None:
|
|
121
129
|
break
|
|
122
130
|
else:
|
|
123
|
-
|
|
131
|
+
rows_to_fetch = min(size - len(rows), self.max_fetch_size)
|
|
132
|
+
result = await self._query.fetch_more(rows_to_fetch=rows_to_fetch)
|
|
124
133
|
self._is_done = result.is_done
|
|
125
134
|
self._buffer.extend(result.data or [])
|
|
126
135
|
return rows
|
|
127
136
|
|
|
137
|
+
@convert_runtime_errors
|
|
128
138
|
async def fetchall(self) -> ResultSet:
|
|
129
139
|
rows = [row_to_tuple(r, self._metadata) for r in self._buffer]
|
|
130
140
|
self._buffer.clear()
|
|
131
141
|
while not self._is_done and self._query is not None:
|
|
132
|
-
result = await self._query.fetch_more(rows_to_fetch=
|
|
142
|
+
result = await self._query.fetch_more(rows_to_fetch=self.max_fetch_size)
|
|
133
143
|
self._is_done = result.is_done
|
|
134
144
|
rows.extend(row_to_tuple(r, self._metadata) for r in (result.data or []))
|
|
135
145
|
return rows
|
|
@@ -149,8 +159,10 @@ class AsyncCursor(
|
|
|
149
159
|
async def nextset(self) -> Optional[bool]:
|
|
150
160
|
return None
|
|
151
161
|
|
|
162
|
+
@convert_runtime_errors
|
|
152
163
|
async def commit(self) -> None:
|
|
153
164
|
await self._job.query("COMMIT").run()
|
|
154
165
|
|
|
166
|
+
@convert_runtime_errors
|
|
155
167
|
async def rollback(self) -> None:
|
|
156
168
|
await self._job.query("ROLLBACK").run()
|
|
@@ -12,6 +12,7 @@ from ..data_types import (
|
|
|
12
12
|
PrepareSqlExecuteRequest,
|
|
13
13
|
QueryOptions,
|
|
14
14
|
QueryResult,
|
|
15
|
+
RcclRequest,
|
|
15
16
|
SqlCloseRequest,
|
|
16
17
|
SqlCloseResponse,
|
|
17
18
|
SqlMoreRequest,
|
|
@@ -33,21 +34,22 @@ class QueryState(Enum):
|
|
|
33
34
|
|
|
34
35
|
|
|
35
36
|
class Query(Generic[T]):
|
|
36
|
-
|
|
37
37
|
|
|
38
38
|
def __init__(self, job: SQLJob, query: str, opts: QueryOptions) -> None:
|
|
39
39
|
self.job = job
|
|
40
40
|
self.sql: str = query
|
|
41
41
|
self.is_prepared: bool = True if opts.parameters is not None else False
|
|
42
|
-
self.parameters: Union[Sequence[Any], Mapping[Union[str, int], Any]] =
|
|
43
|
-
|
|
42
|
+
self.parameters: Union[Sequence[Any], Mapping[Union[str, int], Any]] = (
|
|
43
|
+
opts.parameters if opts.parameters is not None else []
|
|
44
|
+
)
|
|
45
|
+
self.is_remote_cl_command: Optional[bool] = opts.isRemoteClCommand
|
|
46
|
+
self.is_cl_command: Optional[bool] = opts.isClCommand or opts.isRemoteClCommand
|
|
44
47
|
self.should_auto_close: Optional[bool] = opts.autoClose
|
|
45
48
|
self.is_terse_results: Optional[bool] = opts.isTerseResults
|
|
46
49
|
|
|
47
50
|
self._rows_to_fetch: int = 100
|
|
48
51
|
self.state: QueryState = QueryState.NOT_YET_RUN
|
|
49
52
|
self._correlation_id: Optional[str] = None
|
|
50
|
-
|
|
51
53
|
|
|
52
54
|
def __enter__(self):
|
|
53
55
|
return self
|
|
@@ -71,28 +73,42 @@ class Query(Generic[T]):
|
|
|
71
73
|
if self.state == QueryState.RUN_DONE:
|
|
72
74
|
raise Exception("Statement has already been fully run")
|
|
73
75
|
|
|
76
|
+
if self.is_cl_command:
|
|
77
|
+
return self.run()
|
|
78
|
+
|
|
74
79
|
logger.debug("Preparing and executing query")
|
|
75
80
|
query_result = QueryResult.from_dict( # type: ignore
|
|
76
81
|
self._execute_query(
|
|
77
82
|
PrepareSqlExecuteRequest(
|
|
78
83
|
id=self.job._get_unique_id("prepare_sql_execute"),
|
|
79
84
|
sql=self.sql,
|
|
85
|
+
terse=self.is_terse_results,
|
|
80
86
|
parameters=self.parameters,
|
|
81
87
|
)
|
|
82
88
|
)
|
|
83
89
|
)
|
|
84
90
|
self.state = QueryState.RUN_DONE if query_result.is_done else QueryState.RUN_MORE_DATA_AVAIL
|
|
85
91
|
|
|
86
|
-
if not query_result.success
|
|
92
|
+
if not query_result.success:
|
|
87
93
|
self.state = QueryState.ERROR
|
|
88
|
-
error_list = {
|
|
94
|
+
error_list = {
|
|
95
|
+
k: v
|
|
96
|
+
for k, v in {
|
|
97
|
+
"error": query_result.error,
|
|
98
|
+
"sql_state": query_result.sql_state,
|
|
99
|
+
"sql_rc": query_result.sql_rc,
|
|
100
|
+
}.items()
|
|
101
|
+
if v
|
|
102
|
+
}
|
|
89
103
|
if not error_list:
|
|
90
104
|
error_list["error"] = "failed to run query for unknown reason"
|
|
91
105
|
logger.error("Query preparation failed: %s", error_list)
|
|
92
106
|
raise RuntimeError(error_list)
|
|
93
107
|
|
|
94
108
|
self._correlation_id = query_result.id
|
|
95
|
-
logger.debug(
|
|
109
|
+
logger.debug(
|
|
110
|
+
"Query prepared: correlation_id=%s done=%s", self._correlation_id, query_result.is_done
|
|
111
|
+
)
|
|
96
112
|
|
|
97
113
|
return query_result
|
|
98
114
|
|
|
@@ -111,7 +127,13 @@ class Query(Generic[T]):
|
|
|
111
127
|
|
|
112
128
|
logger.debug("Executing query: rows_to_fetch=%s", rows_to_fetch)
|
|
113
129
|
|
|
114
|
-
|
|
130
|
+
request: BaseRequest
|
|
131
|
+
if self.is_remote_cl_command:
|
|
132
|
+
request = RcclRequest(
|
|
133
|
+
id=self.job._get_unique_id("rcclcommand"),
|
|
134
|
+
cmd=self.sql,
|
|
135
|
+
)
|
|
136
|
+
elif self.is_cl_command:
|
|
115
137
|
request = ClRequest(
|
|
116
138
|
id=self.job._get_unique_id("clcommand"),
|
|
117
139
|
cmd=self.sql,
|
|
@@ -136,18 +158,32 @@ class Query(Generic[T]):
|
|
|
136
158
|
|
|
137
159
|
query_result = QueryResult.from_dict(self._execute_query(request)) # type: ignore
|
|
138
160
|
|
|
161
|
+
# CL commands return all messages in one response; mapepire-server 2.5.0+ omits is_done for them
|
|
162
|
+
if self.is_cl_command:
|
|
163
|
+
query_result.is_done = True
|
|
164
|
+
|
|
139
165
|
self.state = QueryState.RUN_DONE if query_result.is_done else QueryState.RUN_MORE_DATA_AVAIL
|
|
140
166
|
|
|
141
167
|
if not query_result.success and not self.is_cl_command:
|
|
142
168
|
self.state = QueryState.ERROR
|
|
143
|
-
error_list = {
|
|
169
|
+
error_list = {
|
|
170
|
+
k: v
|
|
171
|
+
for k, v in {
|
|
172
|
+
"error": query_result.error,
|
|
173
|
+
"sql_state": query_result.sql_state,
|
|
174
|
+
"sql_rc": query_result.sql_rc,
|
|
175
|
+
}.items()
|
|
176
|
+
if v
|
|
177
|
+
}
|
|
144
178
|
if not error_list:
|
|
145
179
|
error_list["error"] = "failed to run query for unknown reason"
|
|
146
180
|
logger.error("Query execution failed: %s", error_list)
|
|
147
181
|
raise RuntimeError(error_list)
|
|
148
182
|
|
|
149
183
|
self._correlation_id = query_result.id
|
|
150
|
-
logger.debug(
|
|
184
|
+
logger.debug(
|
|
185
|
+
"Query executed: correlation_id=%s done=%s", self._correlation_id, query_result.is_done
|
|
186
|
+
)
|
|
151
187
|
|
|
152
188
|
return query_result
|
|
153
189
|
|
|
@@ -164,7 +200,9 @@ class Query(Generic[T]):
|
|
|
164
200
|
raise Exception("Statement has already been fully run")
|
|
165
201
|
|
|
166
202
|
assert self._correlation_id is not None
|
|
167
|
-
logger.debug(
|
|
203
|
+
logger.debug(
|
|
204
|
+
"Fetching more rows: rows=%s correlation_id=%s", rows_to_fetch, self._correlation_id
|
|
205
|
+
)
|
|
168
206
|
self._rows_to_fetch = rows_to_fetch
|
|
169
207
|
query_result = SqlMoreResponse.from_dict( # type: ignore
|
|
170
208
|
self._execute_query(
|
|
@@ -4,6 +4,7 @@ import logging
|
|
|
4
4
|
from pathlib import Path
|
|
5
5
|
from typing import Any, Dict, Optional, Union
|
|
6
6
|
|
|
7
|
+
from pep249 import Error, OperationalError
|
|
7
8
|
from websockets.sync.client import ClientConnection
|
|
8
9
|
|
|
9
10
|
from mapepire_python.client.websocket_client import WebsocketConnection
|
|
@@ -11,11 +12,15 @@ from mapepire_python.websocket import handle_ws_errors
|
|
|
11
12
|
|
|
12
13
|
from ..base_job import BaseJob
|
|
13
14
|
from ..data_types import (
|
|
15
|
+
BaseRequest,
|
|
16
|
+
CLCommandResult,
|
|
17
|
+
ClRequest,
|
|
14
18
|
ConnectionResult,
|
|
15
19
|
ConnectRequest,
|
|
16
20
|
DaemonServer,
|
|
17
21
|
JobStatus,
|
|
18
22
|
QueryOptions,
|
|
23
|
+
RcclRequest,
|
|
19
24
|
)
|
|
20
25
|
|
|
21
26
|
__all__ = ["SQLJob"]
|
|
@@ -102,7 +107,7 @@ class SQLJob(BaseJob):
|
|
|
102
107
|
db2_server (Union[DaemonServer, Dict[str, Any]]): server credentials
|
|
103
108
|
|
|
104
109
|
Raises:
|
|
105
|
-
|
|
110
|
+
OperationalError: Failed to connect to server
|
|
106
111
|
|
|
107
112
|
Returns:
|
|
108
113
|
Dict[Any, Any]: connection results from the server
|
|
@@ -125,11 +130,12 @@ class SQLJob(BaseJob):
|
|
|
125
130
|
)
|
|
126
131
|
|
|
127
132
|
self.send(json.dumps(dataclasses.asdict(connect_req)))
|
|
133
|
+
response = self._socket.recv()
|
|
128
134
|
try:
|
|
129
|
-
result = ConnectionResult.from_dict(json.loads(
|
|
135
|
+
result = ConnectionResult.from_dict(json.loads(response)) # type: ignore
|
|
130
136
|
except Exception as e:
|
|
131
137
|
logger.error("Failed to parse connect response: %s", e)
|
|
132
|
-
raise
|
|
138
|
+
raise OperationalError(f"Failed to parse connect response: {e}") from e
|
|
133
139
|
|
|
134
140
|
if result.success:
|
|
135
141
|
self._status = JobStatus.Ready
|
|
@@ -139,7 +145,7 @@ class SQLJob(BaseJob):
|
|
|
139
145
|
self._status = JobStatus.NotStarted
|
|
140
146
|
logger.error("Connection failed: %s", result.error or "unknown error")
|
|
141
147
|
self.close()
|
|
142
|
-
raise
|
|
148
|
+
raise OperationalError(result.error or "Failed to connect to server")
|
|
143
149
|
|
|
144
150
|
self._is_tracing_channeldata = False
|
|
145
151
|
|
|
@@ -199,9 +205,31 @@ class SQLJob(BaseJob):
|
|
|
199
205
|
try:
|
|
200
206
|
with self.query(sql, opts) as query:
|
|
201
207
|
return query.run(**kwargs)
|
|
208
|
+
except Error:
|
|
209
|
+
raise
|
|
202
210
|
except Exception as e:
|
|
203
211
|
raise RuntimeError(f"Failed to run query: {e}")
|
|
204
212
|
|
|
213
|
+
def clcommand(self, cmd: str) -> CLCommandResult:
|
|
214
|
+
"""Run a CL command in the SQL job (``cl``)."""
|
|
215
|
+
return self._run_cl_command(cmd, remote=False)
|
|
216
|
+
|
|
217
|
+
def rcclcommand(self, cmd: str) -> CLCommandResult:
|
|
218
|
+
"""Run a CL command in the remote command job (``rccl``, Mapepire Server v2.5.0+)."""
|
|
219
|
+
return self._run_cl_command(cmd, remote=True)
|
|
220
|
+
|
|
221
|
+
@handle_ws_errors
|
|
222
|
+
def _run_cl_command(self, cmd: str, remote: bool) -> CLCommandResult:
|
|
223
|
+
request: BaseRequest = (
|
|
224
|
+
RcclRequest(id=self._get_unique_id("rcclcommand"), cmd=cmd)
|
|
225
|
+
if remote
|
|
226
|
+
else ClRequest(id=self._get_unique_id("clcommand"), cmd=cmd)
|
|
227
|
+
)
|
|
228
|
+
self.send(json.dumps(dataclasses.asdict(request)))
|
|
229
|
+
if self._socket is None:
|
|
230
|
+
raise RuntimeError("SQL Job not connected")
|
|
231
|
+
return CLCommandResult.from_dict(json.loads(self._socket.recv())) # type: ignore
|
|
232
|
+
|
|
205
233
|
def close(self) -> None:
|
|
206
234
|
logger.info("Closing job %s", self.id)
|
|
207
235
|
self._status = JobStatus.Ended
|
|
@@ -16,5 +16,7 @@ class WebsocketConnection(BaseConnection):
|
|
|
16
16
|
self.uri,
|
|
17
17
|
additional_headers=self.headers,
|
|
18
18
|
open_timeout=10,
|
|
19
|
+
# The 1 MiB default drops wide pages; 50 MiB fits them but still bounds huge CLOB pages.
|
|
20
|
+
max_size=50 * 2**20,
|
|
19
21
|
ssl=self._create_ssl_context(self.db2_server),
|
|
20
22
|
)
|
|
@@ -52,6 +52,8 @@ class Cursor(pep249.CursorConnectionMixin, pep249.IterableCursorMixin, pep249.Tr
|
|
|
52
52
|
max_rows = 2147483647
|
|
53
53
|
# Rows requested per round trip when fetchone() (and so iteration) needs more data.
|
|
54
54
|
fetch_size = 100
|
|
55
|
+
# Most rows asked for in one sqlmore, so fetchall() never pulls the whole result set in one message.
|
|
56
|
+
max_fetch_size = 1_000
|
|
55
57
|
|
|
56
58
|
def __init__(self, connection: "Connection", job: SQLJob) -> None:
|
|
57
59
|
super().__init__()
|
|
@@ -121,6 +123,7 @@ class Cursor(pep249.CursorConnectionMixin, pep249.IterableCursorMixin, pep249.Tr
|
|
|
121
123
|
else:
|
|
122
124
|
create_opts = QueryOptions(
|
|
123
125
|
isClCommand=kwargs.get("isClCommand", None),
|
|
126
|
+
isRemoteClCommand=kwargs.get("isRemoteClCommand", None),
|
|
124
127
|
isTerseResults=kwargs.get("isTerseResults", None),
|
|
125
128
|
parameters=parameters if parameters else None,
|
|
126
129
|
autoClose=kwargs.get("autoclose", None),
|
|
@@ -128,6 +131,25 @@ class Cursor(pep249.CursorConnectionMixin, pep249.IterableCursorMixin, pep249.Tr
|
|
|
128
131
|
|
|
129
132
|
query = Query(self.job, operation, create_opts)
|
|
130
133
|
|
|
134
|
+
if query.is_cl_command:
|
|
135
|
+
# CL commands return messages, not rows, and Query.run() does not raise when they fail.
|
|
136
|
+
cl_result = query.run()
|
|
137
|
+
self.query = None
|
|
138
|
+
self._metadata = None
|
|
139
|
+
self.__set_has_results(False)
|
|
140
|
+
self.rowcount = -1
|
|
141
|
+
if not cl_result["success"]:
|
|
142
|
+
raise RuntimeError(
|
|
143
|
+
{
|
|
144
|
+
"error": cl_result["error"] or "CL command failed for unknown reason",
|
|
145
|
+
"sql_state": cl_result["sql_state"],
|
|
146
|
+
"sql_rc": cl_result["sql_rc"],
|
|
147
|
+
}
|
|
148
|
+
)
|
|
149
|
+
return self
|
|
150
|
+
|
|
151
|
+
# Keyed rows collapse duplicate column names (e.g. a.ID, b.ID); tuples are positional anyway.
|
|
152
|
+
query.is_terse_results = True
|
|
131
153
|
prepare_result = query.prepare_sql_execute()
|
|
132
154
|
|
|
133
155
|
qs = QueryResultSet(prepare_result)
|
|
@@ -155,11 +177,15 @@ class Cursor(pep249.CursorConnectionMixin, pep249.IterableCursorMixin, pep249.Tr
|
|
|
155
177
|
seq_of_parameters: Sequence[QueryParameters],
|
|
156
178
|
**kwargs: Any,
|
|
157
179
|
) -> "Cursor":
|
|
158
|
-
return self.execute(
|
|
180
|
+
return self.execute(
|
|
181
|
+
operation=operation, parameters=cast(QueryParameters, seq_of_parameters)
|
|
182
|
+
)
|
|
159
183
|
|
|
160
184
|
@raise_if_closed
|
|
161
185
|
@convert_runtime_errors
|
|
162
|
-
def callproc(
|
|
186
|
+
def callproc(
|
|
187
|
+
self, procname: ProcName, parameters: Optional[ProcArgs] = None
|
|
188
|
+
) -> Optional[ProcArgs]:
|
|
163
189
|
self.execute(procname, parameters=parameters)
|
|
164
190
|
return parameters
|
|
165
191
|
|
|
@@ -186,7 +212,8 @@ class Cursor(pep249.CursorConnectionMixin, pep249.IterableCursorMixin, pep249.Tr
|
|
|
186
212
|
"""Return up to ``size`` rows of the current query as tuples.
|
|
187
213
|
|
|
188
214
|
Buffered rows are served first; the server is only asked for more once
|
|
189
|
-
the buffer is empty, and then for at least ``batch_size``
|
|
215
|
+
the buffer is empty, and then for at least ``batch_size`` and at most
|
|
216
|
+
``max_fetch_size`` rows. Once the
|
|
190
217
|
result set is exhausted this returns what it has (possibly ``[]``)
|
|
191
218
|
instead of raising.
|
|
192
219
|
"""
|
|
@@ -198,7 +225,8 @@ class Cursor(pep249.CursorConnectionMixin, pep249.IterableCursorMixin, pep249.Tr
|
|
|
198
225
|
if not state.rows:
|
|
199
226
|
if self.query.state == QueryState.RUN_DONE:
|
|
200
227
|
break
|
|
201
|
-
|
|
228
|
+
rows_to_fetch = min(max(size - len(rows), batch_size), self.max_fetch_size)
|
|
229
|
+
res = self.query.fetch_more(rows_to_fetch=rows_to_fetch)
|
|
202
230
|
if not res.data:
|
|
203
231
|
break
|
|
204
232
|
state.rows.extend(res.data)
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
"""
|
|
2
|
+
This module covers the exceptions outlined in PEP 249.
|
|
3
|
+
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
# pylint: disable=missing-class-docstring
|
|
7
|
+
import ast
|
|
8
|
+
import inspect
|
|
9
|
+
import json
|
|
10
|
+
from functools import wraps
|
|
11
|
+
from typing import Callable, TypeVar
|
|
12
|
+
|
|
13
|
+
from pep249 import (
|
|
14
|
+
DatabaseError,
|
|
15
|
+
DataError,
|
|
16
|
+
Error,
|
|
17
|
+
IntegrityError,
|
|
18
|
+
InterfaceError,
|
|
19
|
+
InternalError,
|
|
20
|
+
NotSupportedError,
|
|
21
|
+
OperationalError,
|
|
22
|
+
ProgrammingError,
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
ReturnType = TypeVar("ReturnType")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
__all__ = [
|
|
29
|
+
"DatabaseError",
|
|
30
|
+
"DataError",
|
|
31
|
+
"Error",
|
|
32
|
+
"InterfaceError",
|
|
33
|
+
"IntegrityError",
|
|
34
|
+
"InternalError",
|
|
35
|
+
"NotSupportedError",
|
|
36
|
+
"OperationalError",
|
|
37
|
+
"ProgrammingError",
|
|
38
|
+
"CONNECTION_CLOSED",
|
|
39
|
+
"convert_runtime_errors",
|
|
40
|
+
"ReturnType",
|
|
41
|
+
]
|
|
42
|
+
|
|
43
|
+
CONNECTION_CLOSED = ProgrammingError("Cannot operate on a closed connection.")
|
|
44
|
+
|
|
45
|
+
SQLSTATE_CLASS_ERRORS = {
|
|
46
|
+
"23": IntegrityError,
|
|
47
|
+
**dict.fromkeys(("21", "22"), DataError),
|
|
48
|
+
**dict.fromkeys(("24", "26", "34", "3F", "42"), ProgrammingError),
|
|
49
|
+
**dict.fromkeys(("08", "25", "40", "57"), OperationalError),
|
|
50
|
+
"0A": NotSupportedError,
|
|
51
|
+
**dict.fromkeys(("38", "39", "58"), InternalError),
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _error_payload(error: RuntimeError) -> dict:
|
|
56
|
+
"""Return the server error dict carried by a query-layer `RuntimeError`, or `{}`."""
|
|
57
|
+
if error.args and isinstance(error.args[0], dict):
|
|
58
|
+
return error.args[0]
|
|
59
|
+
for parse in (json.loads, ast.literal_eval):
|
|
60
|
+
try:
|
|
61
|
+
payload = parse(str(error))
|
|
62
|
+
except (ValueError, SyntaxError):
|
|
63
|
+
continue
|
|
64
|
+
return payload if isinstance(payload, dict) else {}
|
|
65
|
+
return {}
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _parse_runtime_error(error: RuntimeError) -> Error:
|
|
69
|
+
"""Map a query-layer `RuntimeError` onto the PEP 249 class for its SQLSTATE."""
|
|
70
|
+
if isinstance(error, Error) or not isinstance(error, RuntimeError):
|
|
71
|
+
return error
|
|
72
|
+
payload = _error_payload(error)
|
|
73
|
+
sqlstate = payload.get("sql_state") or None
|
|
74
|
+
error_type = SQLSTATE_CLASS_ERRORS.get((sqlstate or "")[:2].upper(), DatabaseError)
|
|
75
|
+
new_error = error_type(payload.get("error") or str(error))
|
|
76
|
+
new_error.sqlstate = sqlstate
|
|
77
|
+
new_error.sql_rc = payload.get("sql_rc") or None
|
|
78
|
+
return new_error
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def convert_runtime_errors(function: Callable[..., ReturnType]) -> Callable[..., ReturnType]:
|
|
82
|
+
"""Wrap a sync or async function, raising correct errors from `RuntimeError`s."""
|
|
83
|
+
|
|
84
|
+
if inspect.iscoroutinefunction(function):
|
|
85
|
+
|
|
86
|
+
@wraps(function)
|
|
87
|
+
async def async_wrapper(*args, **kwargs):
|
|
88
|
+
try:
|
|
89
|
+
return await function(*args, **kwargs)
|
|
90
|
+
except Error:
|
|
91
|
+
raise
|
|
92
|
+
except RuntimeError as err:
|
|
93
|
+
raise _parse_runtime_error(err) from err
|
|
94
|
+
|
|
95
|
+
return async_wrapper # type: ignore[return-value]
|
|
96
|
+
|
|
97
|
+
@wraps(function)
|
|
98
|
+
def wrapper(*args, **kwargs):
|
|
99
|
+
try:
|
|
100
|
+
return function(*args, **kwargs)
|
|
101
|
+
except Error:
|
|
102
|
+
raise
|
|
103
|
+
except RuntimeError as err:
|
|
104
|
+
raise _parse_runtime_error(err) from err
|
|
105
|
+
|
|
106
|
+
return wrapper
|
|
@@ -73,6 +73,7 @@ class MessageType(Enum):
|
|
|
73
73
|
SQL_MORE = "sqlmore"
|
|
74
74
|
SQL_CLOSE = "sqlclose"
|
|
75
75
|
CL = "cl"
|
|
76
|
+
RCCL = "rccl"
|
|
76
77
|
PING = "ping"
|
|
77
78
|
GET_DB_JOB = "getdbjob"
|
|
78
79
|
GET_VERSION = "getversion"
|
|
@@ -316,9 +317,28 @@ class JobLogEntry:
|
|
|
316
317
|
MESSAGE_SECOND_LEVEL_TEXT: str
|
|
317
318
|
|
|
318
319
|
|
|
320
|
+
@dataclass
|
|
321
|
+
class CLMessage:
|
|
322
|
+
id: Optional[str] = None
|
|
323
|
+
type: Optional[str] = None
|
|
324
|
+
severity: Optional[int] = None
|
|
325
|
+
text: Optional[str] = None
|
|
326
|
+
help: Optional[str] = None
|
|
327
|
+
time: Optional[int] = None
|
|
328
|
+
messageLibrary: Optional[str] = None
|
|
329
|
+
messageFile: Optional[str] = None
|
|
330
|
+
sendingProgram: Optional[str] = None
|
|
331
|
+
sendingInstruction: Optional[str] = None
|
|
332
|
+
receivingProgram: Optional[str] = None
|
|
333
|
+
receivingInstruction: Optional[str] = None
|
|
334
|
+
|
|
335
|
+
|
|
319
336
|
@dataclass_json
|
|
320
337
|
@dataclass
|
|
321
338
|
class CLCommandResult(ServerResponse):
|
|
339
|
+
# sql_rc and sql_state are only set by `cl` requests; `rccl` does not run SQL.
|
|
340
|
+
data: List[CLMessage] = field(default_factory=list)
|
|
341
|
+
# Deprecated: no longer sent by Mapepire Server, kept for backwards compatibility
|
|
322
342
|
joblog: List[JobLogEntry] = field(default_factory=list)
|
|
323
343
|
|
|
324
344
|
|
|
@@ -328,6 +348,8 @@ class QueryOptions:
|
|
|
328
348
|
isClCommand: Optional[bool] = None
|
|
329
349
|
parameters: Optional[Union[Sequence[Any], Mapping[Union[str, int], Any]]] = None
|
|
330
350
|
autoClose: Optional[bool] = None
|
|
351
|
+
# `rccl` instead of `cl` (Mapepire Server v2.5.0+); implies isClCommand
|
|
352
|
+
isRemoteClCommand: Optional[bool] = None
|
|
331
353
|
|
|
332
354
|
|
|
333
355
|
@dataclass_json
|
|
@@ -406,6 +428,12 @@ class ClRequest(BaseRequest):
|
|
|
406
428
|
type: str = field(default=MessageType.CL.value, init=False)
|
|
407
429
|
|
|
408
430
|
|
|
431
|
+
@dataclass
|
|
432
|
+
class RcclRequest(BaseRequest):
|
|
433
|
+
cmd: str = ""
|
|
434
|
+
type: str = field(default=MessageType.RCCL.value, init=False)
|
|
435
|
+
|
|
436
|
+
|
|
409
437
|
@dataclass
|
|
410
438
|
class PingRequest(BaseRequest):
|
|
411
439
|
type: str = field(default=MessageType.PING.value, init=False)
|
{mapepire_python-1.0.1 → mapepire_python-2.0.1}/mapepire_python/pool/async_websocket_client.py
RENAMED
|
@@ -13,6 +13,8 @@ class AsyncWebSocketConnection(BaseConnection):
|
|
|
13
13
|
self.uri,
|
|
14
14
|
additional_headers=self.headers,
|
|
15
15
|
open_timeout=10,
|
|
16
|
+
# The 1 MiB default drops wide pages; 50 MiB fits them but still bounds huge CLOB pages.
|
|
17
|
+
max_size=50 * 2**20,
|
|
16
18
|
ssl=self._create_ssl_context(self.db2_server),
|
|
17
19
|
)
|
|
18
20
|
return websocket
|
|
@@ -3,6 +3,8 @@ import json
|
|
|
3
3
|
import logging
|
|
4
4
|
from typing import Any, Dict, Mapping, Optional, Protocol, Sequence, Union
|
|
5
5
|
|
|
6
|
+
from pep249 import OperationalError
|
|
7
|
+
|
|
6
8
|
from mapepire_python.client.query import QueryState
|
|
7
9
|
from mapepire_python.data_types import (
|
|
8
10
|
BaseRequest,
|
|
@@ -10,6 +12,7 @@ from mapepire_python.data_types import (
|
|
|
10
12
|
PrepareSqlExecuteRequest,
|
|
11
13
|
QueryOptions,
|
|
12
14
|
QueryResult,
|
|
15
|
+
RcclRequest,
|
|
13
16
|
SqlCloseRequest,
|
|
14
17
|
SqlCloseResponse,
|
|
15
18
|
SqlMoreRequest,
|
|
@@ -35,14 +38,16 @@ class _SQLJobProtocol(Protocol):
|
|
|
35
38
|
|
|
36
39
|
|
|
37
40
|
class PoolQuery:
|
|
38
|
-
|
|
39
41
|
|
|
40
42
|
def __init__(self, job: _SQLJobProtocol, query: str, opts: QueryOptions) -> None:
|
|
41
43
|
self.job = job
|
|
42
44
|
self.sql: str = query
|
|
43
45
|
self.is_prepared: bool = True if opts.parameters is not None else False
|
|
44
|
-
self.parameters: Optional[Union[Sequence[Any], Mapping[Union[str, int], Any]]] =
|
|
45
|
-
|
|
46
|
+
self.parameters: Optional[Union[Sequence[Any], Mapping[Union[str, int], Any]]] = (
|
|
47
|
+
opts.parameters
|
|
48
|
+
)
|
|
49
|
+
self.is_remote_cl_command: Optional[bool] = opts.isRemoteClCommand
|
|
50
|
+
self.is_cl_command: Optional[bool] = opts.isClCommand or opts.isRemoteClCommand
|
|
46
51
|
self.should_auto_close: Optional[bool] = opts.autoClose
|
|
47
52
|
self.is_terse_results: Optional[bool] = opts.isTerseResults
|
|
48
53
|
|
|
@@ -50,8 +55,6 @@ class PoolQuery:
|
|
|
50
55
|
self.state: QueryState = QueryState.NOT_YET_RUN
|
|
51
56
|
self._correlation_id: Optional[str] = None
|
|
52
57
|
|
|
53
|
-
|
|
54
|
-
|
|
55
58
|
async def __aenter__(self):
|
|
56
59
|
return self
|
|
57
60
|
|
|
@@ -76,7 +79,13 @@ class PoolQuery:
|
|
|
76
79
|
|
|
77
80
|
logger.debug("Executing async query: rows_to_fetch=%s", rows_to_fetch)
|
|
78
81
|
|
|
79
|
-
|
|
82
|
+
request: BaseRequest
|
|
83
|
+
if self.is_remote_cl_command:
|
|
84
|
+
request = RcclRequest(
|
|
85
|
+
id=self.job._get_unique_id("rcclcommand"),
|
|
86
|
+
cmd=self.sql,
|
|
87
|
+
)
|
|
88
|
+
elif self.is_cl_command:
|
|
80
89
|
request = ClRequest(
|
|
81
90
|
id=self.job._get_unique_id("clcommand"),
|
|
82
91
|
cmd=self.sql,
|
|
@@ -101,18 +110,34 @@ class PoolQuery:
|
|
|
101
110
|
|
|
102
111
|
query_result = QueryResult.from_dict(await self._execute_query(request)) # type: ignore
|
|
103
112
|
|
|
113
|
+
# CL commands return all messages in one response; mapepire-server 2.5.0+ omits is_done for them
|
|
114
|
+
if self.is_cl_command:
|
|
115
|
+
query_result.is_done = True
|
|
116
|
+
|
|
104
117
|
self.state = QueryState.RUN_DONE if query_result.is_done else QueryState.RUN_MORE_DATA_AVAIL
|
|
105
118
|
|
|
106
119
|
if not query_result.success and not self.is_cl_command:
|
|
107
120
|
self.state = QueryState.ERROR
|
|
108
|
-
error_list = {
|
|
121
|
+
error_list = {
|
|
122
|
+
k: v
|
|
123
|
+
for k, v in {
|
|
124
|
+
"error": query_result.error,
|
|
125
|
+
"sql_state": query_result.sql_state,
|
|
126
|
+
"sql_rc": query_result.sql_rc,
|
|
127
|
+
}.items()
|
|
128
|
+
if v is not None
|
|
129
|
+
}
|
|
109
130
|
if not error_list:
|
|
110
131
|
error_list["error"] = "failed to run query for unknown reason"
|
|
111
132
|
logger.error("Async query execution failed: %s", error_list)
|
|
112
|
-
raise
|
|
133
|
+
raise RuntimeError(error_list)
|
|
113
134
|
|
|
114
135
|
self._correlation_id = query_result.id
|
|
115
|
-
logger.debug(
|
|
136
|
+
logger.debug(
|
|
137
|
+
"Async query executed: correlation_id=%s done=%s",
|
|
138
|
+
self._correlation_id,
|
|
139
|
+
query_result.is_done,
|
|
140
|
+
)
|
|
116
141
|
|
|
117
142
|
return query_result
|
|
118
143
|
|
|
@@ -128,7 +153,9 @@ class PoolQuery:
|
|
|
128
153
|
raise Exception("Statement has already been fully run")
|
|
129
154
|
|
|
130
155
|
assert self._correlation_id is not None
|
|
131
|
-
logger.debug(
|
|
156
|
+
logger.debug(
|
|
157
|
+
"Fetching more rows: rows=%s correlation_id=%s", rows_to_fetch, self._correlation_id
|
|
158
|
+
)
|
|
132
159
|
self._rows_to_fetch = rows_to_fetch
|
|
133
160
|
query_result = SqlMoreResponse.from_dict( # type: ignore
|
|
134
161
|
await self._execute_query(
|
|
@@ -146,13 +173,13 @@ class PoolQuery:
|
|
|
146
173
|
if not query_result.success:
|
|
147
174
|
self.state = QueryState.ERROR
|
|
148
175
|
logger.error("Async fetch failed: %s", query_result.error)
|
|
149
|
-
raise
|
|
176
|
+
raise RuntimeError(query_result.error or "Failed to run Query (unknown error)")
|
|
150
177
|
|
|
151
178
|
return query_result
|
|
152
179
|
|
|
153
180
|
async def close(self):
|
|
154
181
|
if not self.job.socket:
|
|
155
|
-
raise
|
|
182
|
+
raise OperationalError("SQL Job not connected")
|
|
156
183
|
logger.debug("Closing async query: correlation_id=%s", self._correlation_id)
|
|
157
184
|
if self._correlation_id and self.state is not QueryState.RUN_DONE:
|
|
158
185
|
self.state = QueryState.RUN_DONE
|
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
import base64
|
|
2
|
+
import inspect
|
|
2
3
|
import ssl
|
|
3
4
|
from functools import wraps
|
|
4
|
-
from typing import
|
|
5
|
+
from typing import Callable, TypeVar
|
|
5
6
|
|
|
6
|
-
from
|
|
7
|
+
from pep249 import OperationalError
|
|
8
|
+
from websockets import WebSocketException
|
|
7
9
|
|
|
8
10
|
from mapepire_python.data_types import DaemonServer
|
|
9
11
|
from mapepire_python.ssl import get_certificate
|
|
@@ -42,33 +44,32 @@ class BaseConnection:
|
|
|
42
44
|
return ssl_context
|
|
43
45
|
|
|
44
46
|
|
|
45
|
-
|
|
46
|
-
to_str = str(driver)
|
|
47
|
+
CONNECTION_ERRORS = (OSError, WebSocketException)
|
|
47
48
|
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
raise OSError(f"The TCP connection failed to connect to Mapepire server: {to_str}")
|
|
52
|
-
elif isinstance(error, InvalidHandshake):
|
|
53
|
-
raise InvalidHandshake("The opening handshake failed.")
|
|
54
|
-
elif isinstance(error, TimeoutError):
|
|
55
|
-
raise TimeoutError("The opening handshake timed out.")
|
|
56
|
-
elif isinstance(error, ConnectionClosed):
|
|
57
|
-
raise ConnectionClosed("The Conection was closed.")
|
|
58
|
-
elif isinstance(error, ConcurrencyError):
|
|
59
|
-
raise ConcurrencyError("Connection is sending a fragmented message")
|
|
60
|
-
elif isinstance(error, TypeError):
|
|
61
|
-
raise TypeError("Message doesn't have a supported type")
|
|
62
|
-
else:
|
|
63
|
-
return error
|
|
49
|
+
|
|
50
|
+
def _connection_error(error: Exception) -> OperationalError:
|
|
51
|
+
return OperationalError(f"Connection to Mapepire server failed: {error}")
|
|
64
52
|
|
|
65
53
|
|
|
66
54
|
def handle_ws_errors(function: Callable[..., ReturnType]) -> Callable[..., ReturnType]:
|
|
55
|
+
"""Wrap a sync or async function, raising `OperationalError` from socket and websocket errors."""
|
|
56
|
+
|
|
57
|
+
if inspect.iscoroutinefunction(function):
|
|
58
|
+
|
|
59
|
+
@wraps(function)
|
|
60
|
+
async def async_wrapper(*args, **kwargs):
|
|
61
|
+
try:
|
|
62
|
+
return await function(*args, **kwargs)
|
|
63
|
+
except CONNECTION_ERRORS as err:
|
|
64
|
+
raise _connection_error(err) from err
|
|
65
|
+
|
|
66
|
+
return async_wrapper # type: ignore[return-value]
|
|
67
|
+
|
|
67
68
|
@wraps(function)
|
|
68
|
-
def
|
|
69
|
+
def wrapper(*args, **kwargs):
|
|
69
70
|
try:
|
|
70
|
-
return function(
|
|
71
|
-
except
|
|
72
|
-
raise
|
|
71
|
+
return function(*args, **kwargs)
|
|
72
|
+
except CONNECTION_ERRORS as err:
|
|
73
|
+
raise _connection_error(err) from err
|
|
73
74
|
|
|
74
|
-
return
|
|
75
|
+
return wrapper
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: mapepire-python
|
|
3
|
-
Version:
|
|
3
|
+
Version: 2.0.1
|
|
4
4
|
Author-email: Adam Shedivy <adam.shedivy@ibm.com>, Irfan Sharif <IrfanSharif@ibm.com>
|
|
5
5
|
License: Apache License
|
|
6
6
|
Version 2.0, January 2004
|
|
@@ -225,7 +225,7 @@ Requires-Dist: pywin32; sys_platform == "win32" and extra == "kerberos"
|
|
|
225
225
|
Provides-Extra: dev
|
|
226
226
|
Requires-Dist: ruff<0.16,>=0.15; extra == "dev"
|
|
227
227
|
Requires-Dist: mypy<2.4,>=1.0; extra == "dev"
|
|
228
|
-
Requires-Dist: black<27.0,>=
|
|
228
|
+
Requires-Dist: black<27.0,>=26.10.0; extra == "dev"
|
|
229
229
|
Requires-Dist: isort<8.1,>=5.12; extra == "dev"
|
|
230
230
|
Requires-Dist: pytest>=9.0.3; extra == "dev"
|
|
231
231
|
Requires-Dist: pep249abc; extra == "dev"
|
|
@@ -237,6 +237,7 @@ Requires-Dist: setuptools; extra == "dev"
|
|
|
237
237
|
Requires-Dist: wheel; extra == "dev"
|
|
238
238
|
Requires-Dist: packaging; extra == "dev"
|
|
239
239
|
Requires-Dist: pre-commit; extra == "dev"
|
|
240
|
+
Requires-Dist: virtualenv>=21.15.0; extra == "dev"
|
|
240
241
|
Requires-Dist: python-dotenv; extra == "dev"
|
|
241
242
|
Requires-Dist: pytest-env; extra == "dev"
|
|
242
243
|
Dynamic: license-file
|
|
@@ -763,6 +764,25 @@ with SQLJob("./mapepire.ini") as sql_job:
|
|
|
763
764
|
print(result)
|
|
764
765
|
```
|
|
765
766
|
|
|
767
|
+
### Run CL commands
|
|
768
|
+
|
|
769
|
+
- `clcommand()` runs a CL command in the SQL job (`cl` request)
|
|
770
|
+
- `rcclcommand()` runs it in the remote command job (`rccl` request)
|
|
771
|
+
|
|
772
|
+
Both need Mapepire Server v2.5.0 or later, which added `rccl` and the message format these methods return.
|
|
773
|
+
|
|
774
|
+
```python
|
|
775
|
+
from mapepire_python import SQLJob
|
|
776
|
+
|
|
777
|
+
with SQLJob("./mapepire.ini") as sql_job:
|
|
778
|
+
result = sql_job.rcclcommand("CHKOBJ OBJ(QSYS) OBJTYPE(*LIB)")
|
|
779
|
+
print(result.success, result.data)
|
|
780
|
+
```
|
|
781
|
+
|
|
782
|
+
Both return a `CLCommandResult` whose `data` is the list of messages the command produced. A failed command returns `success=False` and `error` instead of raising. `PoolJob` has async versions of both methods.
|
|
783
|
+
|
|
784
|
+
CL commands can also go through `query()` with `QueryOptions(isClCommand=True)` or `QueryOptions(isRemoteClCommand=True)`, or through the sync PEP 249 `Cursor` with `cursor.execute(cmd, isRemoteClCommand=True)`.
|
|
785
|
+
|
|
766
786
|
## 2. Using the `PoolJob` object to run queries asynchronously
|
|
767
787
|
|
|
768
788
|
The `PoolJob` object can be used to create and run queries asynchronously:
|
|
@@ -5,7 +5,7 @@ pep249abc
|
|
|
5
5
|
[dev]
|
|
6
6
|
ruff<0.16,>=0.15
|
|
7
7
|
mypy<2.4,>=1.0
|
|
8
|
-
black<27.0,>=
|
|
8
|
+
black<27.0,>=26.10.0
|
|
9
9
|
isort<8.1,>=5.12
|
|
10
10
|
pytest>=9.0.3
|
|
11
11
|
pep249abc
|
|
@@ -17,6 +17,7 @@ setuptools
|
|
|
17
17
|
wheel
|
|
18
18
|
packaging
|
|
19
19
|
pre-commit
|
|
20
|
+
virtualenv>=21.15.0
|
|
20
21
|
python-dotenv
|
|
21
22
|
pytest-env
|
|
22
23
|
|
|
@@ -40,7 +40,7 @@ kerberos = [
|
|
|
40
40
|
dev = [
|
|
41
41
|
"ruff>=0.15,<0.16",
|
|
42
42
|
"mypy>=1.0,<2.4",
|
|
43
|
-
"black>=
|
|
43
|
+
"black>=26.10.0,<27.0",
|
|
44
44
|
"isort>=5.12,<8.1",
|
|
45
45
|
"pytest>=9.0.3",
|
|
46
46
|
"pep249abc",
|
|
@@ -52,6 +52,7 @@ dev = [
|
|
|
52
52
|
"wheel",
|
|
53
53
|
"packaging",
|
|
54
54
|
"pre-commit",
|
|
55
|
+
"virtualenv>=21.15.0",
|
|
55
56
|
"python-dotenv",
|
|
56
57
|
"pytest-env",
|
|
57
58
|
]
|
|
@@ -1,95 +0,0 @@
|
|
|
1
|
-
"""
|
|
2
|
-
This module covers the exceptions outlined in PEP 249.
|
|
3
|
-
|
|
4
|
-
"""
|
|
5
|
-
|
|
6
|
-
# pylint: disable=missing-class-docstring
|
|
7
|
-
import ast
|
|
8
|
-
import json
|
|
9
|
-
from functools import wraps
|
|
10
|
-
from typing import Callable, TypeVar
|
|
11
|
-
|
|
12
|
-
from pep249 import (
|
|
13
|
-
DatabaseError,
|
|
14
|
-
DataError,
|
|
15
|
-
Error,
|
|
16
|
-
IntegrityError,
|
|
17
|
-
InterfaceError,
|
|
18
|
-
InternalError,
|
|
19
|
-
NotSupportedError,
|
|
20
|
-
OperationalError,
|
|
21
|
-
ProgrammingError,
|
|
22
|
-
)
|
|
23
|
-
|
|
24
|
-
ReturnType = TypeVar("ReturnType")
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
__all__ = [
|
|
28
|
-
"DatabaseError",
|
|
29
|
-
"DataError",
|
|
30
|
-
"Error",
|
|
31
|
-
"InterfaceError",
|
|
32
|
-
"IntegrityError",
|
|
33
|
-
"InternalError",
|
|
34
|
-
"NotSupportedError",
|
|
35
|
-
"OperationalError",
|
|
36
|
-
"ProgrammingError",
|
|
37
|
-
"CONNECTION_CLOSED",
|
|
38
|
-
"convert_runtime_errors",
|
|
39
|
-
"ReturnType",
|
|
40
|
-
]
|
|
41
|
-
|
|
42
|
-
CONNECTION_CLOSED = ProgrammingError("Cannot operate on a closed connection.")
|
|
43
|
-
|
|
44
|
-
INTEGRITY_ERRORS = ("Constraint Error",)
|
|
45
|
-
PROGRAMMING_ERRORS = ("*FILE not found.",)
|
|
46
|
-
DATA_ERRORS = ("Invalid Input Error", "Out of Range Error")
|
|
47
|
-
INTERNAL_ERRORS = ()
|
|
48
|
-
OPERATIONAL_ERRORS = ()
|
|
49
|
-
NOT_SUPPORTED_ERRORS = ()
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
def _parse_runtime_error(error: RuntimeError) -> Error:
|
|
53
|
-
"""
|
|
54
|
-
Parse a runtime error straight from DuckDB and return a more
|
|
55
|
-
appropriate exception.
|
|
56
|
-
|
|
57
|
-
"""
|
|
58
|
-
if isinstance(error, Error) or not isinstance(error, RuntimeError):
|
|
59
|
-
return error
|
|
60
|
-
error_string = str(error)
|
|
61
|
-
error_message = None
|
|
62
|
-
new_error_type = DatabaseError
|
|
63
|
-
error_dict = None
|
|
64
|
-
|
|
65
|
-
try:
|
|
66
|
-
error_dict = json.loads(error_string)
|
|
67
|
-
except ValueError:
|
|
68
|
-
try:
|
|
69
|
-
error_dict = ast.literal_eval(error_string)
|
|
70
|
-
except (ValueError, SyntaxError):
|
|
71
|
-
error_dict = None
|
|
72
|
-
|
|
73
|
-
try:
|
|
74
|
-
if isinstance(error_dict, dict):
|
|
75
|
-
error_message = error_dict["error"]
|
|
76
|
-
if any(err in error_message for err in PROGRAMMING_ERRORS):
|
|
77
|
-
new_error_type = ProgrammingError
|
|
78
|
-
return new_error_type(error_message)
|
|
79
|
-
except KeyError:
|
|
80
|
-
pass
|
|
81
|
-
|
|
82
|
-
return new_error_type(error_string)
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
def convert_runtime_errors(function: Callable[..., ReturnType]) -> Callable[..., ReturnType]:
|
|
86
|
-
"""Wrap a function, raising correct errors from `RuntimeError`s."""
|
|
87
|
-
|
|
88
|
-
@wraps(function)
|
|
89
|
-
def wrapper(*args, **kwargs):
|
|
90
|
-
try:
|
|
91
|
-
return function(*args, **kwargs)
|
|
92
|
-
except RuntimeError as err:
|
|
93
|
-
raise _parse_runtime_error(err) from err
|
|
94
|
-
|
|
95
|
-
return wrapper
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{mapepire_python-1.0.1 → mapepire_python-2.0.1}/mapepire_python.egg-info/dependency_links.txt
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|