mapepire-python 2.0.0__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.
Files changed (39) hide show
  1. {mapepire_python-2.0.0 → mapepire_python-2.0.1}/PKG-INFO +1 -1
  2. {mapepire_python-2.0.0 → mapepire_python-2.0.1}/mapepire_python/async_base_job.py +14 -7
  3. {mapepire_python-2.0.0 → mapepire_python-2.0.1}/mapepire_python/asyncio/cursor.py +15 -3
  4. {mapepire_python-2.0.0 → mapepire_python-2.0.1}/mapepire_python/client/query.py +31 -8
  5. {mapepire_python-2.0.0 → mapepire_python-2.0.1}/mapepire_python/client/sql_job.py +8 -4
  6. {mapepire_python-2.0.0 → mapepire_python-2.0.1}/mapepire_python/client/websocket_client.py +2 -0
  7. {mapepire_python-2.0.0 → mapepire_python-2.0.1}/mapepire_python/core/cursor.py +19 -5
  8. mapepire_python-2.0.1/mapepire_python/core/exceptions.py +106 -0
  9. {mapepire_python-2.0.0 → mapepire_python-2.0.1}/mapepire_python/pool/async_websocket_client.py +2 -0
  10. {mapepire_python-2.0.0 → mapepire_python-2.0.1}/mapepire_python/pool/pool_query.py +25 -10
  11. {mapepire_python-2.0.0 → mapepire_python-2.0.1}/mapepire_python/version.py +1 -1
  12. {mapepire_python-2.0.0 → mapepire_python-2.0.1}/mapepire_python/websocket.py +26 -25
  13. {mapepire_python-2.0.0 → mapepire_python-2.0.1}/mapepire_python.egg-info/PKG-INFO +1 -1
  14. mapepire_python-2.0.0/mapepire_python/core/exceptions.py +0 -95
  15. {mapepire_python-2.0.0 → mapepire_python-2.0.1}/LICENSE +0 -0
  16. {mapepire_python-2.0.0 → mapepire_python-2.0.1}/README.md +0 -0
  17. {mapepire_python-2.0.0 → mapepire_python-2.0.1}/mapepire_python/__init__.py +0 -0
  18. {mapepire_python-2.0.0 → mapepire_python-2.0.1}/mapepire_python/asyncio/__init__.py +0 -0
  19. {mapepire_python-2.0.0 → mapepire_python-2.0.1}/mapepire_python/asyncio/connection.py +0 -0
  20. {mapepire_python-2.0.0 → mapepire_python-2.0.1}/mapepire_python/authentication/kerberosTokenProvider.py +0 -0
  21. {mapepire_python-2.0.0 → mapepire_python-2.0.1}/mapepire_python/base_job.py +0 -0
  22. {mapepire_python-2.0.0 → mapepire_python-2.0.1}/mapepire_python/client/__init__.py +0 -0
  23. {mapepire_python-2.0.0 → mapepire_python-2.0.1}/mapepire_python/client/async_sql_job.py +0 -0
  24. {mapepire_python-2.0.0 → mapepire_python-2.0.1}/mapepire_python/core/__init__.py +0 -0
  25. {mapepire_python-2.0.0 → mapepire_python-2.0.1}/mapepire_python/core/connection.py +0 -0
  26. {mapepire_python-2.0.0 → mapepire_python-2.0.1}/mapepire_python/core/utils.py +0 -0
  27. {mapepire_python-2.0.0 → mapepire_python-2.0.1}/mapepire_python/data_types.py +0 -0
  28. {mapepire_python-2.0.0 → mapepire_python-2.0.1}/mapepire_python/pool/__init__.py +0 -0
  29. {mapepire_python-2.0.0 → mapepire_python-2.0.1}/mapepire_python/pool/pool_client.py +0 -0
  30. {mapepire_python-2.0.0 → mapepire_python-2.0.1}/mapepire_python/pool/pool_job.py +0 -0
  31. {mapepire_python-2.0.0 → mapepire_python-2.0.1}/mapepire_python/py.typed +0 -0
  32. {mapepire_python-2.0.0 → mapepire_python-2.0.1}/mapepire_python/query_manager.py +0 -0
  33. {mapepire_python-2.0.0 → mapepire_python-2.0.1}/mapepire_python/ssl.py +0 -0
  34. {mapepire_python-2.0.0 → mapepire_python-2.0.1}/mapepire_python.egg-info/SOURCES.txt +0 -0
  35. {mapepire_python-2.0.0 → mapepire_python-2.0.1}/mapepire_python.egg-info/dependency_links.txt +0 -0
  36. {mapepire_python-2.0.0 → mapepire_python-2.0.1}/mapepire_python.egg-info/requires.txt +0 -0
  37. {mapepire_python-2.0.0 → mapepire_python-2.0.1}/mapepire_python.egg-info/top_level.txt +0 -0
  38. {mapepire_python-2.0.0 → mapepire_python-2.0.1}/pyproject.toml +0 -0
  39. {mapepire_python-2.0.0 → 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: 2.0.0
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
@@ -6,6 +6,7 @@ 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
@@ -20,6 +21,7 @@ from .data_types import (
20
21
  QueryOptions,
21
22
  RcclRequest,
22
23
  )
24
+ from .websocket import handle_ws_errors
23
25
 
24
26
  __all__ = ["AsyncBaseJob"]
25
27
 
@@ -76,11 +78,12 @@ class AsyncBaseJob(BaseJob):
76
78
  socket = AsyncWebSocketConnection(db2_server)
77
79
  return await socket.connect()
78
80
 
81
+ @handle_ws_errors
79
82
  async def send(self, content: str) -> Dict[str, Any]:
80
83
  logger.debug("sending data: %s", content)
81
84
  req = json.loads(content)
82
85
  if self.socket is None:
83
- raise RuntimeError("Socket is not connected")
86
+ raise OperationalError("Socket is not connected")
84
87
  req_id = req["id"]
85
88
  # Register the pending future *before* awaiting the socket so the
86
89
  # in-flight count (and Busy status) is reflected synchronously, before
@@ -102,7 +105,9 @@ class AsyncBaseJob(BaseJob):
102
105
 
103
106
  def get_running_count(self) -> int:
104
107
  count = len(self._pending)
105
- logger.debug("--- running count %s: %d, status: %s", self.unique_id, count, self.get_status())
108
+ logger.debug(
109
+ "--- running count %s: %d, status: %s", self.unique_id, count, self.get_status()
110
+ )
106
111
  return count
107
112
 
108
113
  async def connect( # type: ignore[override]
@@ -138,7 +143,7 @@ class AsyncBaseJob(BaseJob):
138
143
  self.status = JobStatus.NotStarted
139
144
  logger.error("Connection failed: %s", result.error or "unknown error")
140
145
  await self.close()
141
- raise Exception(result.error or "Failed to connect to server")
146
+ raise OperationalError(result.error or "Failed to connect to server")
142
147
 
143
148
  self._is_tracing_channel_data = False
144
149
 
@@ -158,7 +163,7 @@ class AsyncBaseJob(BaseJob):
158
163
  # Fail any still-in-flight requests so their awaiters don't hang forever.
159
164
  for future in self._pending.values():
160
165
  if not future.done():
161
- future.cancel()
166
+ future.set_exception(OperationalError("Connection to Mapepire server closed"))
162
167
  self._pending.clear()
163
168
 
164
169
  async def message_handler(self):
@@ -179,7 +184,8 @@ class AsyncBaseJob(BaseJob):
179
184
  else:
180
185
  logger.debug("No pending request for response id: %s", req_id)
181
186
  except websockets.exceptions.ConnectionClosedError:
182
- await self.dispose()
187
+ pass
188
+ await self.dispose()
183
189
 
184
190
  def query(
185
191
  self,
@@ -210,6 +216,8 @@ class AsyncBaseJob(BaseJob):
210
216
  try:
211
217
  async with self.query(sql, opts) as query:
212
218
  return await query.run(rows_to_fetch=rows_to_fetch)
219
+ except Error:
220
+ raise
213
221
  except Exception as e:
214
222
  raise RuntimeError(f"Failed to run query: {e}") from e
215
223
 
@@ -231,8 +239,7 @@ class AsyncBaseJob(BaseJob):
231
239
  await self.send(json.dumps(dataclasses.asdict(request)))
232
240
  )
233
241
 
234
- async def close(self) -> None: # type: ignore[override]
242
+ async def close(self) -> None: # type: ignore[override]
235
243
  logger.info("Closing job %s", self.id)
236
244
  await self.dispose()
237
245
  self.status = JobStatus.Ended
238
-
@@ -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
- opts = QueryOptions(parameters=parameters)
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
- result = await self._query.fetch_more(rows_to_fetch=size - len(rows))
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=100)
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()
@@ -34,13 +34,14 @@ class QueryState(Enum):
34
34
 
35
35
 
36
36
  class Query(Generic[T]):
37
-
38
37
 
39
38
  def __init__(self, job: SQLJob, query: str, opts: QueryOptions) -> None:
40
39
  self.job = job
41
40
  self.sql: str = query
42
41
  self.is_prepared: bool = True if opts.parameters is not None else False
43
- self.parameters: Union[Sequence[Any], Mapping[Union[str, int], Any]] = opts.parameters if opts.parameters is not None else []
42
+ self.parameters: Union[Sequence[Any], Mapping[Union[str, int], Any]] = (
43
+ opts.parameters if opts.parameters is not None else []
44
+ )
44
45
  self.is_remote_cl_command: Optional[bool] = opts.isRemoteClCommand
45
46
  self.is_cl_command: Optional[bool] = opts.isClCommand or opts.isRemoteClCommand
46
47
  self.should_auto_close: Optional[bool] = opts.autoClose
@@ -49,7 +50,6 @@ class Query(Generic[T]):
49
50
  self._rows_to_fetch: int = 100
50
51
  self.state: QueryState = QueryState.NOT_YET_RUN
51
52
  self._correlation_id: Optional[str] = None
52
-
53
53
 
54
54
  def __enter__(self):
55
55
  return self
@@ -82,6 +82,7 @@ class Query(Generic[T]):
82
82
  PrepareSqlExecuteRequest(
83
83
  id=self.job._get_unique_id("prepare_sql_execute"),
84
84
  sql=self.sql,
85
+ terse=self.is_terse_results,
85
86
  parameters=self.parameters,
86
87
  )
87
88
  )
@@ -90,14 +91,24 @@ class Query(Generic[T]):
90
91
 
91
92
  if not query_result.success:
92
93
  self.state = QueryState.ERROR
93
- error_list = {k: v for k, v in {"error": query_result.error, "sql_state": query_result.sql_state, "sql_rc": query_result.sql_rc}.items() if v}
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
+ }
94
103
  if not error_list:
95
104
  error_list["error"] = "failed to run query for unknown reason"
96
105
  logger.error("Query preparation failed: %s", error_list)
97
106
  raise RuntimeError(error_list)
98
107
 
99
108
  self._correlation_id = query_result.id
100
- logger.debug("Query prepared: correlation_id=%s done=%s", self._correlation_id, query_result.is_done)
109
+ logger.debug(
110
+ "Query prepared: correlation_id=%s done=%s", self._correlation_id, query_result.is_done
111
+ )
101
112
 
102
113
  return query_result
103
114
 
@@ -155,14 +166,24 @@ class Query(Generic[T]):
155
166
 
156
167
  if not query_result.success and not self.is_cl_command:
157
168
  self.state = QueryState.ERROR
158
- error_list = {k: v for k, v in {"error": query_result.error, "sql_state": query_result.sql_state, "sql_rc": query_result.sql_rc}.items() if v}
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
+ }
159
178
  if not error_list:
160
179
  error_list["error"] = "failed to run query for unknown reason"
161
180
  logger.error("Query execution failed: %s", error_list)
162
181
  raise RuntimeError(error_list)
163
182
 
164
183
  self._correlation_id = query_result.id
165
- logger.debug("Query executed: correlation_id=%s done=%s", self._correlation_id, query_result.is_done)
184
+ logger.debug(
185
+ "Query executed: correlation_id=%s done=%s", self._correlation_id, query_result.is_done
186
+ )
166
187
 
167
188
  return query_result
168
189
 
@@ -179,7 +200,9 @@ class Query(Generic[T]):
179
200
  raise Exception("Statement has already been fully run")
180
201
 
181
202
  assert self._correlation_id is not None
182
- logger.debug("Fetching more rows: rows=%s correlation_id=%s", rows_to_fetch, self._correlation_id)
203
+ logger.debug(
204
+ "Fetching more rows: rows=%s correlation_id=%s", rows_to_fetch, self._correlation_id
205
+ )
183
206
  self._rows_to_fetch = rows_to_fetch
184
207
  query_result = SqlMoreResponse.from_dict( # type: ignore
185
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
@@ -106,7 +107,7 @@ class SQLJob(BaseJob):
106
107
  db2_server (Union[DaemonServer, Dict[str, Any]]): server credentials
107
108
 
108
109
  Raises:
109
- Exception: Failed to connect to server
110
+ OperationalError: Failed to connect to server
110
111
 
111
112
  Returns:
112
113
  Dict[Any, Any]: connection results from the server
@@ -129,11 +130,12 @@ class SQLJob(BaseJob):
129
130
  )
130
131
 
131
132
  self.send(json.dumps(dataclasses.asdict(connect_req)))
133
+ response = self._socket.recv()
132
134
  try:
133
- result = ConnectionResult.from_dict(json.loads(self._socket.recv())) # type: ignore
135
+ result = ConnectionResult.from_dict(json.loads(response)) # type: ignore
134
136
  except Exception as e:
135
137
  logger.error("Failed to parse connect response: %s", e)
136
- raise Exception(f"Failed to parse connect response: {e}")
138
+ raise OperationalError(f"Failed to parse connect response: {e}") from e
137
139
 
138
140
  if result.success:
139
141
  self._status = JobStatus.Ready
@@ -143,7 +145,7 @@ class SQLJob(BaseJob):
143
145
  self._status = JobStatus.NotStarted
144
146
  logger.error("Connection failed: %s", result.error or "unknown error")
145
147
  self.close()
146
- raise Exception(result.error or "Failed to connect to server")
148
+ raise OperationalError(result.error or "Failed to connect to server")
147
149
 
148
150
  self._is_tracing_channeldata = False
149
151
 
@@ -203,6 +205,8 @@ class SQLJob(BaseJob):
203
205
  try:
204
206
  with self.query(sql, opts) as query:
205
207
  return query.run(**kwargs)
208
+ except Error:
209
+ raise
206
210
  except Exception as e:
207
211
  raise RuntimeError(f"Failed to run query: {e}")
208
212
 
@@ -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__()
@@ -138,10 +140,16 @@ class Cursor(pep249.CursorConnectionMixin, pep249.IterableCursorMixin, pep249.Tr
138
140
  self.rowcount = -1
139
141
  if not cl_result["success"]:
140
142
  raise RuntimeError(
141
- {"error": cl_result["error"] or "CL command failed for unknown reason"}
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
+ }
142
148
  )
143
149
  return self
144
150
 
151
+ # Keyed rows collapse duplicate column names (e.g. a.ID, b.ID); tuples are positional anyway.
152
+ query.is_terse_results = True
145
153
  prepare_result = query.prepare_sql_execute()
146
154
 
147
155
  qs = QueryResultSet(prepare_result)
@@ -169,11 +177,15 @@ class Cursor(pep249.CursorConnectionMixin, pep249.IterableCursorMixin, pep249.Tr
169
177
  seq_of_parameters: Sequence[QueryParameters],
170
178
  **kwargs: Any,
171
179
  ) -> "Cursor":
172
- return self.execute(operation=operation, parameters=cast(QueryParameters, seq_of_parameters))
180
+ return self.execute(
181
+ operation=operation, parameters=cast(QueryParameters, seq_of_parameters)
182
+ )
173
183
 
174
184
  @raise_if_closed
175
185
  @convert_runtime_errors
176
- def callproc(self, procname: ProcName, parameters: Optional[ProcArgs] = None) -> Optional[ProcArgs]:
186
+ def callproc(
187
+ self, procname: ProcName, parameters: Optional[ProcArgs] = None
188
+ ) -> Optional[ProcArgs]:
177
189
  self.execute(procname, parameters=parameters)
178
190
  return parameters
179
191
 
@@ -200,7 +212,8 @@ class Cursor(pep249.CursorConnectionMixin, pep249.IterableCursorMixin, pep249.Tr
200
212
  """Return up to ``size`` rows of the current query as tuples.
201
213
 
202
214
  Buffered rows are served first; the server is only asked for more once
203
- the buffer is empty, and then for at least ``batch_size`` rows. Once the
215
+ the buffer is empty, and then for at least ``batch_size`` and at most
216
+ ``max_fetch_size`` rows. Once the
204
217
  result set is exhausted this returns what it has (possibly ``[]``)
205
218
  instead of raising.
206
219
  """
@@ -212,7 +225,8 @@ class Cursor(pep249.CursorConnectionMixin, pep249.IterableCursorMixin, pep249.Tr
212
225
  if not state.rows:
213
226
  if self.query.state == QueryState.RUN_DONE:
214
227
  break
215
- res = self.query.fetch_more(rows_to_fetch=max(size - len(rows), batch_size))
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)
216
230
  if not res.data:
217
231
  break
218
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
@@ -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,
@@ -36,13 +38,14 @@ class _SQLJobProtocol(Protocol):
36
38
 
37
39
 
38
40
  class PoolQuery:
39
-
40
41
 
41
42
  def __init__(self, job: _SQLJobProtocol, query: str, opts: QueryOptions) -> None:
42
43
  self.job = job
43
44
  self.sql: str = query
44
45
  self.is_prepared: bool = True if opts.parameters is not None else False
45
- self.parameters: Optional[Union[Sequence[Any], Mapping[Union[str, int], Any]]] = opts.parameters
46
+ self.parameters: Optional[Union[Sequence[Any], Mapping[Union[str, int], Any]]] = (
47
+ opts.parameters
48
+ )
46
49
  self.is_remote_cl_command: Optional[bool] = opts.isRemoteClCommand
47
50
  self.is_cl_command: Optional[bool] = opts.isClCommand or opts.isRemoteClCommand
48
51
  self.should_auto_close: Optional[bool] = opts.autoClose
@@ -52,8 +55,6 @@ class PoolQuery:
52
55
  self.state: QueryState = QueryState.NOT_YET_RUN
53
56
  self._correlation_id: Optional[str] = None
54
57
 
55
-
56
-
57
58
  async def __aenter__(self):
58
59
  return self
59
60
 
@@ -117,14 +118,26 @@ class PoolQuery:
117
118
 
118
119
  if not query_result.success and not self.is_cl_command:
119
120
  self.state = QueryState.ERROR
120
- error_list = {k: v for k, v in {"error": query_result.error, "sql_state": query_result.sql_state, "sql_rc": query_result.sql_rc}.items() if v is not None}
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
+ }
121
130
  if not error_list:
122
131
  error_list["error"] = "failed to run query for unknown reason"
123
132
  logger.error("Async query execution failed: %s", error_list)
124
- raise Exception(error_list)
133
+ raise RuntimeError(error_list)
125
134
 
126
135
  self._correlation_id = query_result.id
127
- logger.debug("Async query executed: correlation_id=%s done=%s", self._correlation_id, query_result.is_done)
136
+ logger.debug(
137
+ "Async query executed: correlation_id=%s done=%s",
138
+ self._correlation_id,
139
+ query_result.is_done,
140
+ )
128
141
 
129
142
  return query_result
130
143
 
@@ -140,7 +153,9 @@ class PoolQuery:
140
153
  raise Exception("Statement has already been fully run")
141
154
 
142
155
  assert self._correlation_id is not None
143
- logger.debug("Fetching more rows: rows=%s correlation_id=%s", rows_to_fetch, self._correlation_id)
156
+ logger.debug(
157
+ "Fetching more rows: rows=%s correlation_id=%s", rows_to_fetch, self._correlation_id
158
+ )
144
159
  self._rows_to_fetch = rows_to_fetch
145
160
  query_result = SqlMoreResponse.from_dict( # type: ignore
146
161
  await self._execute_query(
@@ -158,13 +173,13 @@ class PoolQuery:
158
173
  if not query_result.success:
159
174
  self.state = QueryState.ERROR
160
175
  logger.error("Async fetch failed: %s", query_result.error)
161
- raise Exception(query_result.error or "Failed to run Query (unknown error)")
176
+ raise RuntimeError(query_result.error or "Failed to run Query (unknown error)")
162
177
 
163
178
  return query_result
164
179
 
165
180
  async def close(self):
166
181
  if not self.job.socket:
167
- raise Exception("SQL Job not connected")
182
+ raise OperationalError("SQL Job not connected")
168
183
  logger.debug("Closing async query: correlation_id=%s", self._correlation_id)
169
184
  if self._correlation_id and self.state is not QueryState.RUN_DONE:
170
185
  self.state = QueryState.RUN_DONE
@@ -2,7 +2,7 @@ _MAJOR = "2"
2
2
  _MINOR = "0"
3
3
  # On main and in a nightly release the patch should be one ahead of the last
4
4
  # released build.
5
- _PATCH = "0"
5
+ _PATCH = "1"
6
6
  # This is mainly for nightly builds which have the suffix ".dev$DATE". See
7
7
  # https://semver.org/#is-v123-a-semantic-version for the semantics.
8
8
  _SUFFIX = ""
@@ -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 Any, Callable, TypeVar
5
+ from typing import Callable, TypeVar
5
6
 
6
- from websockets import ConcurrencyError, ConnectionClosed, InvalidHandshake, InvalidURI
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
- def _parse_ws_error(error: Exception, driver: Any = None):
46
- to_str = str(driver)
47
+ CONNECTION_ERRORS = (OSError, WebSocketException)
47
48
 
48
- if isinstance(error, InvalidURI):
49
- raise InvalidURI(f"The provided URI is not a valid WebSocket URI: {to_str}")
50
- elif isinstance(error, OSError):
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 _impl(self, *args, **kwargs):
69
+ def wrapper(*args, **kwargs):
69
70
  try:
70
- return function(self, *args, **kwargs)
71
- except RuntimeError as err:
72
- raise _parse_ws_error(err, driver=self) from err
71
+ return function(*args, **kwargs)
72
+ except CONNECTION_ERRORS as err:
73
+ raise _connection_error(err) from err
73
74
 
74
- return _impl
75
+ return wrapper
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: mapepire-python
3
- Version: 2.0.0
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
@@ -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