From b907a9376677d648fdd7d02cd858947b9449b984 Mon Sep 17 00:00:00 2001 From: Marco Vogt Date: Sat, 21 Nov 2026 23:58:23 +0100 Subject: [PATCH 1/7] Route Prism server errors through PEP 249 --- .github/workflows/test.yaml | 2 +- README.md | 4 +- docs/polypheny.rst | 29 ++-- polypheny/__init__.py | 31 +++-- polypheny/connection.py | 170 ++++++++++++----------- polypheny/exceptions.py | 37 ++++- polypheny/rpc.py | 163 ++++++++++++++-------- polypheny/serialize.py | 21 ++- requirements.txt | 2 +- setup.py | 5 +- tests/test_error_mapping.py | 140 +++++++++++++++++++ tests/test_error_mapping_unit.py | 230 +++++++++++++++++++++++++++++++ tests/test_graph.py | 20 ++- tests/test_graph_protocol.py | 6 +- tests/test_serialize.py | 2 +- tests/test_unix.py | 5 +- 16 files changed, 686 insertions(+), 181 deletions(-) create mode 100644 tests/test_error_mapping.py create mode 100644 tests/test_error_mapping_unit.py diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml index d66256a1..6b4ed429 100644 --- a/.github/workflows/test.yaml +++ b/.github/workflows/test.yaml @@ -12,7 +12,7 @@ jobs: - uses: actions/checkout@v4 with: repository: polypheny/Polypheny-DB - ref: ${{ vars.POLYPHENY_DB_REF || 'ebcf8e5b09cbae409526c017f509c7a55d07b0a4' }} + ref: ${{ vars.POLYPHENY_DB_REF || '18586fb885329cd3b0d61d7af7696a44328c34b1' }} - uses: actions/setup-java@v4 with: diff --git a/README.md b/README.md index 8b924530..d25940b4 100644 --- a/README.md +++ b/README.md @@ -25,9 +25,11 @@ cd /path/to/polyphney-connector-python-x.y.z/ python setup.py install ``` -The connector uses the Prism 2.2 client definitions and connects to servers +The connector uses the Prism 2.4 client definitions and connects to servers that report a compatible Prism 2.x API. The minor versions do not have to match. Document collection metadata requires server-side support introduced in Prism 2.2. +PEP 249 error classification uses SQLSTATE details from Prism 2.4 servers. +Errors from older servers raise `DatabaseError` with `sqlstate=None`. ## Getting Started diff --git a/docs/polypheny.rst b/docs/polypheny.rst index d56f71af..65e95e1c 100644 --- a/docs/polypheny.rst +++ b/docs/polypheny.rst @@ -51,7 +51,8 @@ Obtain a cursor from ``Connection.cursor()``. Each new execution releases the previous result on that cursor. ``execute()`` runs SQL. ``executeany()`` takes an explicit language and can select a default namespace for the statement. Use ``?`` with a list or tuple of parameters, or ``:name`` with a dictionary -for named SQL parameters. Cypher execution uses the direct statement path. +for named SQL parameters. For servers that support prepared Cypher, bind +``$name`` with a dictionary. .. autoclass:: polypheny.Cursor() @@ -89,13 +90,25 @@ at exhaustion. Exceptions ---------- -The connector exports ``Warning`` and ``Error``. Prism server errors use -``Error``. The DB-API subclasses are ``InterfaceError`` and ``DatabaseError``. -The latter has subclasses ``DataError``, ``OperationalError``, -``IntegrityError``, ``InternalError``, ``ProgrammingError``, and -``NotSupportedError``. Closed connection operations such as -``cursor()``, ``commit()``, or ``rollback()`` raise ``ProgrammingError``. -Socket failures can surface as ``OSError`` or ``EOFError``. +The connector exports ``Warning`` and ``Error``. The DB-API subclasses are +``InterfaceError`` and ``DatabaseError``. The latter has subclasses +``DataError``, ``OperationalError``, ``IntegrityError``, ``InternalError``, +``ProgrammingError``, and ``NotSupportedError``. + +Prism server errors use the SQLSTATE class to select the exception type. +An unknown class or a response from a server without structured error +details raises ``DatabaseError``. Every ``Error`` exposes ``sqlstate`` +and ``errorcode``, which are ``None`` when unavailable. ``str(error)`` +returns the original server message. + +Invalid cursor or connection use raises ``ProgrammingError``. A transport +configuration or protocol mismatch raises ``InterfaceError``. A refused or +lost connection raises ``OperationalError``. Unsupported result frames +and value types raise ``NotSupportedError``. + +After transport loss, ``rollback()`` also raises ``OperationalError``. +Handle that error if you attempt a rollback during cleanup, and use a new +connection for subsequent operations. See the `official Python API reference `_ and `error handling guide `_. diff --git a/polypheny/__init__.py b/polypheny/__init__.py index 3f4dbfcf..3d25b5ba 100644 --- a/polypheny/__init__.py +++ b/polypheny/__init__.py @@ -16,6 +16,7 @@ from polypheny.exceptions import * import datetime +import time from typing import Union # See https://peps.python.org/pep-0249/#globals @@ -24,36 +25,42 @@ paramstyle = 'qmark' +def _make_value(constructor, *args): + try: + return constructor(*args) + except (TypeError, ValueError, OverflowError, OSError) as e: + raise DataError(str(e)) from e + + def Date(year, month, day): - return datetime.date(year, month, day) + return _make_value(datetime.date, year, month, day) def Time(hour, minute, second): - return datetime.time(hour, minute, second) + return _make_value(datetime.time, hour, minute, second) def Timestamp(year, month, day, hour, minute, second): - return datetime.datetime(year, month, day, hour, minute, second) - - -# See PEP 249 -import time + return _make_value(datetime.datetime, year, month, day, hour, minute, second) def DateFromTicks(ticks): - return Date(*time.localtime(ticks)[:3]) # TODO: Really local time? + return Date(*_make_value(time.localtime, ticks)[:3]) def TimeFromTicks(ticks): - return Time(*time.localtime(ticks)[3:6]) + return Time(*_make_value(time.localtime, ticks)[3:6]) def TimestampFromTicks(ticks): - return Timestamp(*time.localtime(ticks)[:6]) + return Timestamp(*_make_value(time.localtime, ticks)[:6]) def Binary(string): - return string.encode('UTF-8') + try: + return _make_value(string.encode, 'UTF-8') + except AttributeError as e: + raise DataError(str(e)) from e # Intentionally omitted, we always give type_code = None, like sqlite3 @@ -80,6 +87,6 @@ def connect(address: Union[tuple[str, int], str] = None, *, username: str = None if address is None and transport is None and username is None and password is None and len(kwargs) == 0: transport = 'unix' elif address is None or transport is None: - raise Error("Address and transport must be given") + raise InterfaceError("Address and transport must be given") return Connection(address, username, password, transport, kwargs) diff --git a/polypheny/connection.py b/polypheny/connection.py index 2ce45ffc..018e4fe7 100644 --- a/polypheny/connection.py +++ b/polypheny/connection.py @@ -12,11 +12,12 @@ # See the License for the specific language governing permissions and # limitations under the License. +from contextlib import suppress from typing import List, Any from org.polypheny.prism import graph_frame_pb2, relational_frame_pb2, value_pb2 from polypheny import rpc -from polypheny.exceptions import * +from polypheny.exceptions import Error, InterfaceError, NotSupportedError, ProgrammingError from polypheny.serialize import proto2py, proto_graph_element2py @@ -25,22 +26,16 @@ def __init__(self, address, username, password, transport, kwargs): self.cursors = set() self.con = None # Needed so destructor works - try: - self.con = rpc.Connection(address, transport, kwargs) - except ConnectionRefusedError: - raise Error("Connection refused") from None - + self.con = rpc.Connection(address, transport, kwargs) try: resp = self.con.connect(username, password, False) if not resp.is_compatible: - raise Error( + raise InterfaceError( f"Client ({rpc.POLYPHENY_API_MAJOR}.{rpc.POLYPHENY_API_MINOR}) is incompatible with Server version ({resp.major_api_version}.{resp.minor_api_version})") - except Exception as e: - # This manual dance prevents the disconnect message from being sent - self.con.con.close() - self.con.con = None + except Error: + self.con.abort() self.con = None - raise Error(str(e)) + raise def cursor(self): if self.con is None: @@ -83,20 +78,19 @@ def rollback(self): self.con.rollback() def __del__(self): - # TODO Thread-safety? - self.close() + with suppress(Error): + self.close() def close(self): if self.con is None: - assert len(self.cursors) == 0 return - for cur in list(self.cursors): # self.cursors is materialized because cur.close modifies it - cur.close() - assert len(self.cursors) == 0 - try: - self.rollback() + for cur in list(self.cursors): + with suppress(Error): + cur.close() + if self.con.con is not None: + self.rollback() finally: self.con.close() self.con = None @@ -120,20 +114,15 @@ def __init__(self, con, statement_id, frame, fetch_size): def _frame_items(self, frame): result_type = frame.WhichOneof('result') if result_type not in self._FRAME_ITEMS: - self.close() - raise InterfaceError(f'Unsupported Prism result frame: {result_type}') + raise NotSupportedError(f'Unsupported Prism result frame: {result_type}') return iter(getattr(getattr(frame, result_type), self._FRAME_ITEMS[result_type])) - def __del__(self): - assert self.closed - self.close() - def close(self): if self.closed: return - assert self.con.con is not None try: - self.con.con.close_statement(self.statement_id) + if self.con.con is not None: + self.con.con.close_statement(self.statement_id) finally: self.con = None self.closed = True @@ -141,9 +130,7 @@ def close(self): def __next__(self): # frame is None when there were no results if self.frame is None: - raise Error("Previous statement did not produce any results") - - assert self.rows is not None + raise ProgrammingError("Previous statement did not produce any results") while True: try: @@ -162,28 +149,41 @@ def __init__(self, con): self.reset() def reset(self): - if self.result is not None: - self.result.close() + self._require_open() + previous, self.result = self.result, None self.description = None self.rowcount = -1 self.arraysize = 1 - self.result = None + if previous is not None: + previous.close() # def callproc(self): # optional def __del__(self): - self.close() + with suppress(Error): + self.close() def close(self): - # TODO: Error when already closed? - assert self.con is not None or self.result is None if self.con is not None: - if self.result is not None: - self.result.close() + try: + if self.result is not None: + self.result.close() + finally: self.result = None - self.con.cursors.remove(self) - self.con = None + self.con.cursors.discard(self) + self.con = None + + def _require_open(self): + if self.con is None: + raise ProgrammingError("Cursor is closed") + + def _require_result(self): + self._require_open() + if self.result is None: + raise ProgrammingError("No statement was yet executed") + if self.result.frame is None: + raise ProgrammingError("Previous statement did not produce any results") def __iter__(self): return self @@ -210,8 +210,12 @@ def executemany(self, query: str, params: List[List[Any]]): """ Execute `query` once with each item in `params` as parameters. """ - # TODO: Optimize, this is to exercise the execute code more - for param in params: + self._require_open() + try: + batch = iter(params) + except TypeError as e: + raise ProgrammingError(str(e)) from e + for param in batch: self.execute(query, param) def executeany(self, lang: str, query: str, params: List[Any] = None, *, @@ -237,46 +241,44 @@ def executeany(self, lang: str, query: str, params: List[Any] = None, *, as relational rows can contain graph values alongside scalar values. """ - if self.con is None: - raise Error("Cursor is closed") - self.reset() - - if params is None: # Unparameterized query - r = self.con.con.execute_unparameterized_statement(lang, query, fetch_size, namespace) - assert r.HasField("result") # Is this always true? - statement_id = r.statement_id - result = r.result - elif type(params) == list or type(params) == tuple: - resp = self.con.con.prepare_indexed_statement(lang, query, namespace) - statement_id = resp.statement_id - result = self.con.con.execute_indexed_statement(statement_id, params, fetch_size) - elif type(params) == dict: - resp = self.con.con.prepare_named_statement(lang, query, namespace) - statement_id = resp.statement_id - result = self.con.con.execute_named_statement(statement_id, params, fetch_size) - else: - raise Error("Unexpected type for params " + str(type(params))) - - if result.HasField( - "frame"): # TODO Better Error when one of the fetch* methods is invoked. Empty fake result? - self.rowcount = -1 - if result.frame.WhichOneof('result') == 'relational_frame': - self.derive_description(result.frame.relational_frame) - frame = result.frame - else: + statement_id = None + connection = self.con.con + try: + if params is None: # Unparameterized query + response = connection.execute_unparameterized_statement(lang, query, fetch_size, namespace) + statement_id = response.statement_id + if not response.HasField("result"): + raise InterfaceError("Prism statement response did not contain a result") + result = response.result + elif type(params) in (list, tuple): + response = connection.prepare_indexed_statement(lang, query, namespace) + statement_id = response.statement_id + result = connection.execute_indexed_statement(statement_id, params, fetch_size) + elif type(params) is dict: + response = connection.prepare_named_statement(lang, query, namespace) + statement_id = response.statement_id + result = connection.execute_named_statement(statement_id, params, fetch_size) + else: + raise ProgrammingError("Unexpected type for params " + str(type(params))) + + frame = result.frame if result.HasField("frame") else None + self.result = ResultCursor(self.con, statement_id, frame, fetch_size) + except (Error, TypeError, ValueError, OverflowError) as e: + if statement_id is not None: + with suppress(Error): + connection.close_statement(statement_id) + if isinstance(e, Error): + raise + raise ProgrammingError(str(e)) from e + + if frame is None: self.rowcount = result.scalar - frame = None - - self.result = ResultCursor(self.con, statement_id, frame, fetch_size) + elif frame.WhichOneof('result') == 'relational_frame': + self.derive_description(frame.relational_frame) def fetchone(self): - if self.con is None: - raise ProgrammingError("Cursor is closed") - - if self.result is None: - raise ProgrammingError("No statement was yet executed") - + self._require_result() try: n = next(self.result) except StopIteration: @@ -294,14 +296,18 @@ def fetchone(self): elif isinstance(n, graph_frame_pb2.GraphElement): return proto_graph_element2py(n) else: - raise Error(f"Unknown result of type {type(n)}") + raise NotSupportedError(f"Unknown result of type {type(n)}") def fetchmany(self, size=None): - # TODO: Optimize, this is to exercise the fetch code more + self._require_result() if size is None: size = self.arraysize + try: + batch = range(size) + except (TypeError, ValueError, OverflowError) as e: + raise ProgrammingError(str(e)) from e results = [] - for _ in range(size): + for _ in batch: row = self.fetchone() if row is None: break diff --git a/polypheny/exceptions.py b/polypheny/exceptions.py index 5dc7911e..d171cb34 100644 --- a/polypheny/exceptions.py +++ b/polypheny/exceptions.py @@ -12,12 +12,18 @@ # See the License for the specific language governing permissions and # limitations under the License. +import re as _re + + class Warning(Exception): pass class Error(Exception): - pass + def __init__(self, *args, sqlstate=None, errorcode=None): + super().__init__(*args) + self.sqlstate = sqlstate + self.errorcode = errorcode class InterfaceError(Error): @@ -50,3 +56,32 @@ class ProgrammingError(DatabaseError): class NotSupportedError(DatabaseError): pass + + +_SQLSTATE_CLASSES = { + "08": OperationalError, + "28": OperationalError, + "40": OperationalError, + "53": OperationalError, + "57": OperationalError, + "58": OperationalError, + "0A": NotSupportedError, + "22": DataError, + "23": IntegrityError, + "24": InternalError, + "25": InternalError, + "26": InternalError, + "2D": InternalError, + "XX": InternalError, + "I9": InternalError, + "3F": ProgrammingError, + "42": ProgrammingError, +} + + +def _server_error(response): + details = response.details + sqlstate = details.state if _re.fullmatch(r"[A-Z0-9]{5}", details.state) else None + errorcode = details.error_code if details.HasField("error_code") else None + error_type = _SQLSTATE_CLASSES.get(sqlstate[:2], DatabaseError) if sqlstate else DatabaseError + return error_type(response.message, sqlstate=sqlstate, errorcode=errorcode) diff --git a/polypheny/rpc.py b/polypheny/rpc.py index 236b9fcf..19ba2bf8 100644 --- a/polypheny/rpc.py +++ b/polypheny/rpc.py @@ -16,8 +16,10 @@ import socket from contextlib import suppress -from polypheny.exceptions import Error -from polypheny.serialize import * +from google.protobuf.message import DecodeError + +from polypheny.exceptions import Error, InterfaceError, OperationalError, _server_error +from polypheny.serialize import py2proto from org.polypheny.prism import protointerface_pb2 from org.polypheny.prism import statement_requests_pb2 from org.polypheny.prism import transaction_requests_pb2 @@ -32,20 +34,25 @@ class PlainTransport: def __init__(self, address): self.con = socket.create_connection(address) - self.con.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) - self.exchange_version(self.VERSION) + try: + self.con.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) + self.exchange_version(self.VERSION) + except (Error, OSError): + with suppress(OSError): + self.close() + raise def exchange_version(self, version): bl = self._recv_exact(1) n = int.from_bytes(bl, byteorder='little') if n > 127: - raise Error("Invalid version length") + raise InterfaceError("Invalid version length") remote_version = self._recv_exact(n) if not remote_version.endswith(b'\n'): - raise Error("Invalid version message") + raise InterfaceError("Invalid version message") if remote_version[0:-1] != version.encode(): - raise Error(f"Unsupported version: {repr(remote_version[0:-1])} expected {version.encode()}") + raise InterfaceError(f"Unsupported version: {repr(remote_version[0:-1])} expected {version.encode()}") self.con.sendall(bl + remote_version) @@ -59,7 +66,7 @@ def _recv_exact(self, size): while len(data) < size: chunk = self.con.recv(size - len(data)) if not chunk: - raise EOFError + raise OperationalError() data.extend(chunk) return bytes(data) @@ -80,18 +87,30 @@ def __init__(self, path): self.con = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) if path is None: path = os.path.expanduser("~/.polypheny/polypheny-prism.sock") - self.con.connect(path) - self.exchange_version(self.VERSION) + try: + self.con.connect(path) + self.exchange_version(self.VERSION) + except (Error, OSError, TypeError, ValueError): + with suppress(OSError): + self.close() + raise class Connection: def __init__(self, address, transport, kwargs): - if transport == "plain": - self.con = PlainTransport(address) - elif transport == "unix": - self.con = UnixTransport(address) - else: - raise Exception("Unknown transport: " + transport) + try: + if transport == "plain": + self.con = PlainTransport(address) + elif transport == "unix": + self.con = UnixTransport(address) + else: + raise InterfaceError(f"Unknown transport: {transport}") + except ConnectionRefusedError: + raise OperationalError("Connection refused") from None + except OSError as e: + raise OperationalError(str(e)) from e + except (AttributeError, TypeError, ValueError, OverflowError) as e: + raise InterfaceError(str(e)) from e self.id = 1 def close(self): @@ -99,14 +118,17 @@ def close(self): return try: self.disconnect() - except Exception: + except Error: pass + finally: + self.abort() - try: - self.con.close() - except Exception: - pass + def abort(self): + transport = self.con self.con = None + if transport is not None: + with suppress(OSError): + transport.close() def new_request(self): msg = protointerface_pb2.Request() @@ -115,57 +137,84 @@ def new_request(self): return msg def send_msg(self, msg): - self.con.send_msg(msg.SerializeToString()) + if self.con is None: + raise OperationalError("Connection to the server is lost") + try: + self.con.send_msg(msg.SerializeToString()) + except OSError as e: + self.abort() + raise OperationalError(str(e)) from e - def recv_msg(self): + def recv_msg(self, request_id=None): + if self.con is None: + raise OperationalError("Connection to the server is lost") r = protointerface_pb2.Response() - r.ParseFromString(self.con.recv_msg()) + try: + r.ParseFromString(self.con.recv_msg()) + except OperationalError: + self.abort() + raise + except OSError as e: + self.abort() + raise OperationalError(str(e)) from e + except (DecodeError, ValueError, OverflowError) as e: + self.abort() + raise InterfaceError(str(e)) from e + if request_id is not None and r.id != request_id: + self.abort() + raise InterfaceError(f"Unexpected Prism response ID {r.id}, expected {request_id}") if r.WhichOneof('type') == 'error_response': - # TODO: Add to error_response something to decide if this is necessary - # self.con.close() - # self.con = None - raise Error(r.error_response.message) + self._require_response(r, 'error_response') + raise _server_error(r.error_response) return r - def call(self, msg): + def _require_response(self, response, response_type, *, last=True): + actual_type = response.WhichOneof('type') + if response.last != last or actual_type is None or (response_type and actual_type != response_type): + self.abort() + raise InterfaceError(f"Unexpected Prism response: {actual_type} (last={response.last})") + + def call(self, msg, response_type=None): self.send_msg(msg) - response = self.recv_msg() - assert response.id == msg.id - assert response.last + response = self.recv_msg(msg.id) + self._require_response(response, response_type) return response def connect(self, username, password, auto_commit): msg = self.new_request() req = msg.connection_request - if username is not None: - req.username = username - if password is not None: - req.password = password - req.major_api_version = POLYPHENY_API_MAJOR - req.minor_api_version = POLYPHENY_API_MINOR - req.connection_properties.is_auto_commit = auto_commit - - return self.call(msg).connection_response + try: + if username is not None: + req.username = username + if password is not None: + req.password = password + req.major_api_version = POLYPHENY_API_MAJOR + req.minor_api_version = POLYPHENY_API_MINOR + req.connection_properties.is_auto_commit = auto_commit + except (TypeError, ValueError, OverflowError) as e: + raise InterfaceError(str(e)) from e + + return self.call(msg, 'connection_response').connection_response def disconnect(self): msg = self.new_request() req = connection_requests_pb2.DisconnectRequest() msg.disconnect_request.MergeFrom(req) - return self.call(msg).disconnect_response + return self.call(msg, 'disconnect_response').disconnect_response def commit(self): msg = self.new_request() req = transaction_requests_pb2.CommitRequest() msg.commit_request.MergeFrom(req) - return self.call(msg).commit_response + return self.call(msg, 'commit_response').commit_response def rollback(self): msg = self.new_request() req = transaction_requests_pb2.RollbackRequest() msg.rollback_request.MergeFrom(req) - return self.call(msg).rollback_response + return self.call(msg, 'rollback_response').rollback_response def execute_unparameterized_statement(self, language_name, statement, fetch_size, namespace): msg = self.new_request() @@ -180,18 +229,16 @@ def execute_unparameterized_statement(self, language_name, statement, fetch_size msg.execute_unparameterized_statement_request.MergeFrom(req) self.send_msg(msg) - started = self.recv_msg() - assert started.id == msg.id - assert not started.last and started.HasField("statement_response") + started = self.recv_msg(msg.id) + self._require_response(started, 'statement_response', last=False) try: - completed = self.recv_msg() + completed = self.recv_msg(msg.id) except Error: # Prism allocated a statement before evaluating the query. - with suppress(Error, OSError, EOFError): + with suppress(Error): self.close_statement(started.statement_response.statement_id) raise - assert completed.id == msg.id - assert completed.last + self._require_response(completed, 'statement_response') return completed.statement_response def prepare_indexed_statement(self, language_name, statement, namespace): @@ -201,7 +248,7 @@ def prepare_indexed_statement(self, language_name, statement, namespace): req.statement = statement if namespace: req.namespace_name = namespace - return self.call(msg).prepared_statement_signature + return self.call(msg, 'prepared_statement_signature').prepared_statement_signature def execute_indexed_statement(self, statement_id, params, fetch_size): msg = self.new_request() @@ -210,7 +257,7 @@ def execute_indexed_statement(self, statement_id, params, fetch_size): req.parameters.parameters.extend(list(map(py2proto, params))) if fetch_size: req.fetch_size = fetch_size - return self.call(msg).statement_result + return self.call(msg, 'statement_result').statement_result def prepare_named_statement(self, language_name, statement, namespace): msg = self.new_request() @@ -219,7 +266,7 @@ def prepare_named_statement(self, language_name, statement, namespace): req.statement = statement if namespace: req.namespace_name = namespace - return self.call(msg).prepared_statement_signature + return self.call(msg, 'prepared_statement_signature').prepared_statement_signature def execute_named_statement(self, statement_id, params, fetch_size): msg = self.new_request() @@ -229,7 +276,7 @@ def execute_named_statement(self, statement_id, params, fetch_size): req.fetch_size = fetch_size for k, v in params.items(): py2proto(v, req.parameters.parameters[k]) - return self.call(msg).statement_result + return self.call(msg, 'statement_result').statement_result def fetch(self, statement_id, fetch_size): msg = self.new_request() @@ -238,9 +285,11 @@ def fetch(self, statement_id, fetch_size): if fetch_size: req.fetch_size = fetch_size - return self.call(msg).frame + return self.call(msg, 'frame').frame def close_statement(self, statement_id): + if self.con is None: + return msg = self.new_request() msg.close_statement_request.statement_id = statement_id - return self.call(msg).close_statement_response + return self.call(msg, 'close_statement_response').close_statement_response diff --git a/polypheny/serialize.py b/polypheny/serialize.py index 85506bb4..8e147fb9 100644 --- a/polypheny/serialize.py +++ b/polypheny/serialize.py @@ -18,7 +18,7 @@ import polypheny.interval as interval from org.polypheny.prism import value_pb2 -from polypheny.exceptions import InterfaceError +from polypheny.exceptions import DataError, InterfaceError, InternalError, NotSupportedError def serialize_big_decimal(v, value): @@ -33,6 +33,13 @@ def serialize_big_decimal(v, value): # See ProtoValueDeserializer def py2proto(value, v=None): + try: + return _py2proto(value, v) + except (TypeError, ValueError, OverflowError, OSError, RecursionError) as e: + raise DataError(str(e)) from e + + +def _py2proto(value, v): if v is None: v = value_pb2.ProtoValue() if type(value) is bool: @@ -66,7 +73,7 @@ def py2proto(value, v=None): for element in value: v.list.values.append(py2proto(element)) else: - raise NotImplementedError + raise NotSupportedError() return v @@ -83,8 +90,14 @@ def parse_big_decimal(value): def proto2py(value): + try: + return _proto2py(value) + except (ValueError, OverflowError, OSError, RecursionError) as e: + raise InternalError(str(e)) from e + + +def _proto2py(value): name = value.WhichOneof("value") - assert name is not None if name == "boolean": return value.boolean.boolean elif name == "integer": @@ -132,7 +145,7 @@ def proto2py(value): "edges": [_proto_node_or_edge2py(edge) for edge in graph.edges], } else: - raise RuntimeError("Unhandled value type") + raise NotSupportedError("Unhandled value type") def _proto_node_or_edge2py(element): diff --git a/requirements.txt b/requirements.txt index 4916e690..e6891817 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,4 +1,4 @@ -polypheny-prism-api==2.3 +polypheny-prism-api==2.4 pytest coverage Sphinx diff --git a/setup.py b/setup.py index d574b638..09906b0b 100644 --- a/setup.py +++ b/setup.py @@ -5,8 +5,7 @@ THIS_DIR = os.path.dirname(os.path.realpath(__file__)) CONNECTOR_SRC_DIR = os.path.join(THIS_DIR, "polypheny") -VERSION = (0, 0, 0, None) # Default -VERSION = "v0.0.0" # Default +VERSION = "v2.2.0" version_file = 'polypheny-connector-version.txt' @@ -77,6 +76,6 @@ def readme(): }, python_requires=">=3.9", install_requires=[ - "polypheny-prism-api==2.3", + "polypheny-prism-api==2.4", ], ) diff --git a/tests/test_error_mapping.py b/tests/test_error_mapping.py new file mode 100644 index 00000000..01dd9905 --- /dev/null +++ b/tests/test_error_mapping.py @@ -0,0 +1,140 @@ +# Copyright 2024 The Polypheny Project +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +import os +from contextlib import contextmanager + +import pytest + +import polypheny +from polypheny import rpc +from test_helper import con + + +@pytest.fixture +def errtest(con): + cursor = con.cursor() + cursor.execute("CREATE NAMESPACE errtest") + try: + cursor.execute("CREATE TABLE errtest.t (id INTEGER PRIMARY KEY, name VARCHAR(50) NOT NULL)") + cursor.execute("INSERT INTO errtest.t VALUES (1, 'first')") + con.commit() + yield cursor + finally: + con.rollback() + cursor.execute("DROP NAMESPACE errtest") + cursor.close() + + +def assert_error(caught, exception_type, sqlstates): + assert type(caught.value) is exception_type + assert caught.value.sqlstate in sqlstates + + +def assert_recovered(connection, cursor): + connection.rollback() + cursor.execute("SELECT id, name FROM errtest.t") + assert cursor.fetchall() == [[1, "first"]] + connection.commit() + + +@pytest.mark.parametrize(("statement", "exception_type", "sqlstates"), [ + pytest.param("SELECT * FROM does_not_exist.t", polypheny.ProgrammingError, ("42P01", "3F000"), id="S1"), + pytest.param("SELECT * FROM errtest.nope", polypheny.ProgrammingError, ("42P01",), id="S2"), + pytest.param("SELECT nope FROM errtest.t", polypheny.ProgrammingError, ("42703",), id="S3"), + pytest.param("SELEC * FROM errtest.t", polypheny.ProgrammingError, ("42601",), id="S4"), + pytest.param("INSERT INTO errtest.t (id, name) VALUES (2, NULL)", polypheny.IntegrityError, ("23502",), id="S5"), + pytest.param("INSERT INTO errtest.t (id, name) VALUES ('abc', 'x')", polypheny.ProgrammingError, ("42804",), id="S6"), + pytest.param("SELECT CAST('abc' AS INTEGER) FROM errtest.t", polypheny.DataError, ("22018", "22P02"), id="S7"), + pytest.param("SELECT 1/0 FROM errtest.t", polypheny.DataError, ("22012",), id="S8"), + pytest.param("CREATE TABLE errtest.nopk (a INTEGER)", polypheny.ProgrammingError, ("42P16",), id="S9"), +]) +def test_sql_statement_error(con, errtest, statement, exception_type, sqlstates): + with pytest.raises(exception_type) as caught: + errtest.execute(statement) + if errtest.description is not None: + errtest.fetchall() + assert_error(caught, exception_type, sqlstates) + assert_recovered(con, errtest) + + +@contextmanager +def enable_constraint_enforcement(connection, cursor, key): + cursor.execute(f"ALTER CONFIG 'runtime/{key}' SET true") + try: + yield + finally: + connection.rollback() + cursor.execute(f"ALTER CONFIG 'runtime/{key}' SET false") + + +def test_s10_duplicate_primary_key_enforced(con, errtest): + with enable_constraint_enforcement(con, errtest, "uniqueConstraintEnforcement"): + with pytest.raises(polypheny.IntegrityError) as caught: + errtest.execute("INSERT INTO errtest.t VALUES (1, 'duplicate')") + con.commit() + assert_error(caught, polypheny.IntegrityError, ("23505",)) + assert_recovered(con, errtest) + + +def test_s11_duplicate_primary_key_default(con, errtest): + errtest.execute("INSERT INTO errtest.t VALUES (1, 'duplicate')") + if os.getenv("DEFAULT_STORE") == "file": + # The File adapter's physical row names enforce primary-key uniqueness. + with pytest.raises(polypheny.IntegrityError) as caught: + con.commit() + assert_error(caught, polypheny.IntegrityError, ("23505",)) + assert_recovered(con, errtest) + return + + con.commit() + errtest.execute("SELECT COUNT(*) FROM errtest.t WHERE id = 1") + assert errtest.fetchone() == [2] + + +def test_s12_foreign_key_violation(con, errtest): + with enable_constraint_enforcement(con, errtest, "foreignKeyEnforcement"): + errtest.execute("CREATE TABLE errtest.child (id INTEGER PRIMARY KEY, parent INTEGER)") + errtest.execute( + "ALTER TABLE errtest.child ADD CONSTRAINT fk_errtest " + "FOREIGN KEY (parent) REFERENCES errtest.t(id) ON UPDATE RESTRICT ON DELETE RESTRICT" + ) + with pytest.raises(polypheny.IntegrityError) as caught: + errtest.execute("INSERT INTO errtest.child VALUES (1, 42)") + con.commit() + assert_error(caught, polypheny.IntegrityError, ("23503",)) + assert_recovered(con, errtest) + + +def test_s13_unsupported_query_language(con, errtest): + with pytest.raises(polypheny.NotSupportedError) as caught: + errtest.executeany("nosuchlanguage", "x") + assert_error(caught, polypheny.NotSupportedError, ("0A000",)) + assert_recovered(con, errtest) + + +def test_s14_unknown_user(con, errtest): + with pytest.raises(polypheny.OperationalError) as caught: + polypheny.connect(("127.0.0.1", 20590), username="unknown", password="", transport="plain") + assert_error(caught, polypheny.OperationalError, ("28000", "28P01")) + assert_recovered(con, errtest) + + +def test_s15_incompatible_api_major(con, errtest, monkeypatch): + monkeypatch.setattr(rpc, "POLYPHENY_API_MAJOR", rpc.POLYPHENY_API_MAJOR - 1) + with pytest.raises(polypheny.InterfaceError, match="incompatible with Server version") as caught: + polypheny.connect(("127.0.0.1", 20590), username="pa", password="", transport="plain") + assert_error(caught, polypheny.InterfaceError, (None,)) + assert_recovered(con, errtest) diff --git a/tests/test_error_mapping_unit.py b/tests/test_error_mapping_unit.py new file mode 100644 index 00000000..8f116af9 --- /dev/null +++ b/tests/test_error_mapping_unit.py @@ -0,0 +1,230 @@ +# Copyright 2024 The Polypheny Project +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +import pickle +from types import SimpleNamespace +from unittest.mock import Mock + +import pytest +from org.polypheny.prism import protointerface_pb2, statement_responses_pb2, value_pb2 + +import polypheny +from polypheny import rpc +from polypheny.serialize import proto2py, py2proto + + +@pytest.mark.parametrize(("sqlstate", "exception_type"), [ + ("08006", polypheny.OperationalError), + ("28P01", polypheny.OperationalError), + ("40001", polypheny.OperationalError), + ("53100", polypheny.OperationalError), + ("57014", polypheny.OperationalError), + ("58000", polypheny.OperationalError), + ("0A000", polypheny.NotSupportedError), + ("22012", polypheny.DataError), + ("23505", polypheny.IntegrityError), + ("24000", polypheny.InternalError), + ("25000", polypheny.InternalError), + ("26000", polypheny.InternalError), + ("2D000", polypheny.InternalError), + ("XX000", polypheny.InternalError), + ("I9000", polypheny.InternalError), + ("3F000", polypheny.ProgrammingError), + ("42601", polypheny.ProgrammingError), + ("ZZ123", polypheny.DatabaseError), + ("42", polypheny.DatabaseError), + ("42???", polypheny.DatabaseError), + (None, polypheny.DatabaseError), +]) +def test_server_error_mapping(sqlstate, exception_type): + # The legacy message is authoritative even when the details carry different text. + message = "server message: duplicate primary key\n" + response = protointerface_pb2.Response(id=1, last=True) + response.error_response.message = message + if sqlstate is not None: + response.error_response.details.state = sqlstate + response.error_response.details.error_code = 0 + response.error_response.details.message = "different text" + + connection = rpc.Connection.__new__(rpc.Connection) + connection.con = Mock() + connection.con.recv_msg.return_value = response.SerializeToString() + + with pytest.raises(exception_type) as caught: + connection.recv_msg(1) + error = caught.value + assert type(error) is exception_type + assert str(error) == message + assert error.sqlstate == (None if sqlstate in ("42", "42???") else sqlstate) + assert error.errorcode == (0 if sqlstate is not None else None) + + restored = pickle.loads(pickle.dumps(error)) + assert type(restored) is exception_type + assert restored.args == (message,) + assert str(restored) == message + assert restored.sqlstate == error.sqlstate + assert restored.errorcode == error.errorcode + + +def test_exception_constructible_with_message(): + error = polypheny.ProgrammingError("x") + assert str(error) == "x" + assert error.args == ("x",) + assert error.sqlstate is None + assert error.errorcode is None + + +def test_prism_error_without_vendor_code(): + response = protointerface_pb2.Response(id=1, last=True) + response.error_response.details.state = "23502" + connection = rpc.Connection.__new__(rpc.Connection) + connection.con = Mock() + connection.con.recv_msg.return_value = response.SerializeToString() + + with pytest.raises(polypheny.IntegrityError) as caught: + connection.recv_msg(1) + assert caught.value.sqlstate == "23502" + assert caught.value.errorcode is None + + +@pytest.fixture +def connection(monkeypatch): + prism = Mock() + prism.connect.return_value = SimpleNamespace(is_compatible=True) + monkeypatch.setattr(rpc, "Connection", Mock(return_value=prism)) + connection = polypheny.connect(("localhost", 20590), transport="plain") + yield connection + connection.close() + + +@pytest.mark.parametrize(("operation", "args"), [ + ("execute", ("SELECT 1",)), + ("executeany", ("sql", "SELECT 1")), + ("executemany", ("SELECT 1", [])), + ("fetchone", ()), + ("fetchmany", (0,)), + ("fetchall", ()), +]) +def test_closed_cursor(connection, operation, args): + cursor = connection.cursor() + cursor.close() + with pytest.raises(polypheny.ProgrammingError, match="Cursor is closed"): + getattr(cursor, operation)(*args) + + +@pytest.mark.parametrize(("operation", "args"), [ + ("fetchone", ()), + ("fetchmany", (0,)), + ("fetchall", ()), +]) +def test_fetch_without_result(connection, operation, args): + cursor = connection.cursor() + fetch = getattr(cursor, operation) + with pytest.raises(polypheny.ProgrammingError, match="No statement was yet executed"): + fetch(*args) + + connection.con.execute_unparameterized_statement.return_value = ( + statement_responses_pb2.StatementResponse( + statement_id=42, result=statement_responses_pb2.StatementResult(scalar=1), + ) + ) + cursor.execute("INSERT INTO t VALUES (1)") + with pytest.raises(polypheny.ProgrammingError, match="Previous statement did not produce any results"): + fetch(*args) + + +@pytest.mark.parametrize("params", [1, "string", object()]) +def test_invalid_query_parameters(connection, params): + with pytest.raises(polypheny.ProgrammingError, match="Unexpected type for params"): + connection.cursor().execute("SELECT ?", params) + + +@pytest.mark.parametrize("operation", ["cursor", "commit", "rollback"]) +def test_closed_connection(connection, operation): + connection.close() + with pytest.raises(polypheny.ProgrammingError, match="Connection is closed"): + getattr(connection, operation)() + + +@pytest.mark.parametrize("options", [ + {"address": ("localhost", 20590)}, + {"username": "pa"}, + {"transport": "plain"}, + {"address": ("localhost", 20590), "transport": "unknown"}, +]) +def test_connection_configuration(options): + with pytest.raises(polypheny.InterfaceError): + polypheny.connect(**options) + + +def test_connection_refused(monkeypatch): + monkeypatch.setattr(rpc.socket, "create_connection", Mock(side_effect=ConnectionRefusedError)) + with pytest.raises(polypheny.OperationalError, match="^Connection refused$"): + polypheny.connect(("localhost", 20590), transport="plain") + + +@pytest.mark.parametrize("during_fetch", [False, True]) +def test_peer_closes_during_request(monkeypatch, during_fetch): + def frame(response): + wire = response.SerializeToString() + return [len(wire).to_bytes(8, "little"), wire] + + connect = protointerface_pb2.Response(id=1, last=True) + connect.connection_response.is_compatible = True + messages = frame(connect) + if during_fetch: + started = protointerface_pb2.Response(id=2) + started.statement_response.statement_id = 42 + completed = protointerface_pb2.Response(id=2, last=True) + completed.statement_response.statement_id = 42 + completed.statement_response.result.frame.relational_frame.SetInParent() + messages.extend(frame(started) + frame(completed)) + + transport = rpc.PlainTransport.__new__(rpc.PlainTransport) + socket = transport.con = Mock() + socket.recv.side_effect = messages + [(3).to_bytes(8, "little"), b"x", b""] + monkeypatch.setattr(rpc, "PlainTransport", Mock(return_value=transport)) + + connection = polypheny.connect(("localhost", 20590), transport="plain") + try: + cursor = connection.cursor() + if during_fetch: + cursor.execute("SELECT 1") + with pytest.raises(polypheny.OperationalError): + if during_fetch: + cursor.fetchone() + else: + cursor.execute("SELECT 1") + with pytest.raises(polypheny.OperationalError): + connection.rollback() + cursor.close() + finally: + connection.close() + socket.close.assert_called_once_with() + assert socket.sendall.call_count == (3 if during_fetch else 2) + + +def test_unsupported_values_and_result_frames(connection): + with pytest.raises(polypheny.NotSupportedError): + py2proto(object()) + with pytest.raises(polypheny.NotSupportedError): + proto2py(value_pb2.ProtoValue()) + + response = statement_responses_pb2.StatementResponse(statement_id=42) + response.result.frame.SetInParent() + connection.con.execute_unparameterized_statement.return_value = response + with pytest.raises(polypheny.NotSupportedError, match="Unsupported Prism result frame"): + connection.cursor().execute("SELECT 1") + connection.con.close_statement.assert_called_once_with(42) diff --git a/tests/test_graph.py b/tests/test_graph.py index 58a20c7f..81159bc9 100644 --- a/tests/test_graph.py +++ b/tests/test_graph.py @@ -260,15 +260,25 @@ def test_rejects_multiple_cypher_statements_and_recovers(graph): assert len(cur.fetchall()) == 3 -@pytest.mark.parametrize("params", [[], {"name": "Alice"}]) -def test_reports_server_limit_on_prepared_cypher(graph, params): - _, cur, namespace = graph - with pytest.raises(polypheny.Error, match="Prepared Cypher statements are not supported by Prism"): - cur.executeany("cypher", "MATCH (n:Person) RETURN n", params, namespace=namespace) +def test_reports_server_limit_on_indexed_cypher(graph): + con, cur, namespace = graph + with pytest.raises(polypheny.NotSupportedError, match="Indexed prepared Cypher statements are not supported") as caught: + cur.executeany("cypher", "MATCH (n:Person) RETURN n", [], namespace=namespace) + assert caught.value.sqlstate == "0A000" + con.rollback() cur.executeany("cypher", "MATCH (n:Person) RETURN n.name AS name ORDER BY name", namespace=namespace) assert cur.fetchall() == [[name] for name in PEOPLE] +def test_prepared_named_cypher(graph): + _, cur, namespace = graph + cur.executeany( + "cypher", "MATCH (n:Person) WHERE n.name = $name RETURN n.name AS name", + {"name": "Alice"}, namespace=namespace, + ) + assert cur.fetchall() == [["Alice"]] + + def test_graph_namespace_metadata(graph): con, _, namespace = graph request = con.con.new_request() diff --git a/tests/test_graph_protocol.py b/tests/test_graph_protocol.py index 58f8bb84..6a031ac3 100644 --- a/tests/test_graph_protocol.py +++ b/tests/test_graph_protocol.py @@ -18,7 +18,7 @@ from org.polypheny.prism import graph_frame_pb2, protointerface_pb2, statement_responses_pb2, value_pb2 from polypheny.connection import ResultCursor -from polypheny.exceptions import Error, InterfaceError +from polypheny.exceptions import Error, InterfaceError, OperationalError from polypheny.rpc import Connection, PlainTransport from polypheny.serialize import proto2py, proto_graph_element2py, py2proto @@ -113,12 +113,12 @@ def test_fragmented_graph_message_is_read_in_full(): assert statement_responses_pb2.Frame.FromString(transport.recv_msg()) == response -def test_truncated_message_raises_eof(): +def test_truncated_message_raises_operational_error(): transport = PlainTransport.__new__(PlainTransport) transport.con = Mock() transport.con.recv.side_effect = [(3).to_bytes(8, "little"), b"x", b""] - with pytest.raises(EOFError): + with pytest.raises(OperationalError): transport.recv_msg() diff --git a/tests/test_serialize.py b/tests/test_serialize.py index 21894a8c..ea8d35c6 100644 --- a/tests/test_serialize.py +++ b/tests/test_serialize.py @@ -228,7 +228,7 @@ def test_serialize_varbinary(cur): def test_serialize_not_implemented(cur): cur.execute('DROP TABLE IF EXISTS t') cur.execute('CREATE TABLE t(i INTEGER NOT NULL, a INTEGER, PRIMARY KEY(i))') - with pytest.raises(NotImplementedError): + with pytest.raises(polypheny.NotSupportedError): cur.execute('INSERT INTO t(i, a) VALUES (0, ?)', ({'a': 'b'},)) def test_trailing_semicolon(cur): diff --git a/tests/test_unix.py b/tests/test_unix.py index 188e958a..d564ffbd 100644 --- a/tests/test_unix.py +++ b/tests/test_unix.py @@ -28,9 +28,10 @@ def unix_connect(args): def test_connect_unix(): if sys.platform == 'win32': # TODO: Once this works the documentation needs to be updated - with pytest.raises(AttributeError): + unavailable = (polypheny.InterfaceError, polypheny.OperationalError) + with pytest.raises(unavailable): unix_connect(False) - with pytest.raises(AttributeError): + with pytest.raises(unavailable): unix_connect(True) else: unix_connect(True) From 6b9db61e8dced375b9d47ceab8c43d94f3d7c713 Mon Sep 17 00:00:00 2001 From: Marco Vogt Date: Sun, 22 Nov 2026 22:22:23 +0100 Subject: [PATCH 2/7] Validate Prism 2.4 against the merged backend --- .github/workflows/test.yaml | 2 +- README.md | 3 +- docs/polypheny.rst | 21 +++- polypheny/connection.py | 9 +- tests/test_error_mapping_unit.py | 176 +++++++++++++++++++++++++++++++ 5 files changed, 206 insertions(+), 5 deletions(-) diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml index 6b4ed429..e1a696ad 100644 --- a/.github/workflows/test.yaml +++ b/.github/workflows/test.yaml @@ -12,7 +12,7 @@ jobs: - uses: actions/checkout@v4 with: repository: polypheny/Polypheny-DB - ref: ${{ vars.POLYPHENY_DB_REF || '18586fb885329cd3b0d61d7af7696a44328c34b1' }} + ref: ${{ vars.POLYPHENY_DB_REF || '01a2e438d761190e889f1a9f91426d3264b3e6d8' }} - uses: actions/setup-java@v4 with: diff --git a/README.md b/README.md index d25940b4..05c81054 100644 --- a/README.md +++ b/README.md @@ -29,7 +29,8 @@ The connector uses the Prism 2.4 client definitions and connects to servers that report a compatible Prism 2.x API. The minor versions do not have to match. Document collection metadata requires server-side support introduced in Prism 2.2. PEP 249 error classification uses SQLSTATE details from Prism 2.4 servers. -Errors from older servers raise `DatabaseError` with `sqlstate=None`. +Errors from older servers raise `DatabaseError` with `sqlstate=None` and +`errorcode=None`. ## Getting Started diff --git a/docs/polypheny.rst b/docs/polypheny.rst index 65e95e1c..95a1f8a9 100644 --- a/docs/polypheny.rst +++ b/docs/polypheny.rst @@ -98,9 +98,28 @@ The connector exports ``Warning`` and ``Error``. The DB-API subclasses are Prism server errors use the SQLSTATE class to select the exception type. An unknown class or a response from a server without structured error details raises ``DatabaseError``. Every ``Error`` exposes ``sqlstate`` -and ``errorcode``, which are ``None`` when unavailable. ``str(error)`` +and ``errorcode``. Each attribute is ``None`` when unavailable, and an +explicit vendor code of zero is returned as ``0``. ``str(error)`` returns the original server message. +.. list-table:: + :header-rows: 1 + + * - SQLSTATE classes + - Exception + * - ``08``, ``28``, ``40``, ``53``, ``57``, ``58`` + - ``OperationalError`` + * - ``0A`` + - ``NotSupportedError`` + * - ``22`` + - ``DataError`` + * - ``23`` + - ``IntegrityError`` + * - ``24``, ``25``, ``26``, ``2D``, ``I9``, ``XX`` + - ``InternalError`` + * - ``3F``, ``42`` + - ``ProgrammingError`` + Invalid cursor or connection use raises ``ProgrammingError``. A transport configuration or protocol mismatch raises ``InterfaceError``. A refused or lost connection raises ``OperationalError``. Unsupported result frames diff --git a/polypheny/connection.py b/polypheny/connection.py index 018e4fe7..091cfba6 100644 --- a/polypheny/connection.py +++ b/polypheny/connection.py @@ -138,8 +138,9 @@ def __next__(self): except StopIteration: if self.frame.is_last: raise - self.frame = self.con.con.fetch(self.statement_id, self.fetch_size) - self.rows = self._frame_items(self.frame) + frame = self.con.con.fetch(self.statement_id, self.fetch_size) + self.rows = self._frame_items(frame) + self.frame = frame class Cursor: @@ -283,6 +284,10 @@ def fetchone(self): n = next(self.result) except StopIteration: return None + except Error: + with suppress(Error): + self.reset() + raise if isinstance(n, relational_frame_pb2.Row): v = [] diff --git a/tests/test_error_mapping_unit.py b/tests/test_error_mapping_unit.py index 8f116af9..67c67022 100644 --- a/tests/test_error_mapping_unit.py +++ b/tests/test_error_mapping_unit.py @@ -99,6 +99,182 @@ def test_prism_error_without_vendor_code(): assert caught.value.errorcode is None +@pytest.fixture +def wire(monkeypatch): + transport = Mock() + monkeypatch.setattr(rpc, "PlainTransport", Mock(return_value=transport)) + return transport + + +def reply(request_id, field): + response = protointerface_pb2.Response(id=request_id, last=True) + getattr(response, field).SetInParent() + return response + + +def login_reply(): + response = reply(1, "connection_response") + response.connection_response.is_compatible = True + return response + + +def error_reply(request_id, message, sqlstate): + response = reply(request_id, "error_response") + response.error_response.message = message + if sqlstate is not None: + response.error_response.details.state = sqlstate + response.error_response.details.error_code = 0 + return response + + +def statement_replies(request_id, statement_id, *, last=False): + started = protointerface_pb2.Response(id=request_id) + started.statement_response.statement_id = statement_id + completed = reply(request_id, "statement_response") + completed.statement_response.statement_id = statement_id + frame = completed.statement_response.result.frame + frame.is_last = last + frame.relational_frame.SetInParent() + if last: + frame.relational_frame.rows.add().values.append(py2proto(1)) + return started, completed + + +def send_replies(wire, *responses): + wire.recv_msg.side_effect = [response.SerializeToString() for response in responses] + + +def requests_sent(wire): + return [ + protointerface_pb2.Request.FromString(call.args[0]) + for call in wire.send_msg.call_args_list + ] + + +@pytest.mark.parametrize(("sqlstate", "exception_type"), [ + ("28P01", polypheny.OperationalError), + (None, polypheny.DatabaseError), +]) +def test_login_preserves_prism_error(wire, sqlstate, exception_type): + message = "Login rejected.\n" + send_replies(wire, error_reply(1, message, sqlstate)) + + with pytest.raises(exception_type) as caught: + polypheny.connect(("localhost", 20590), username="guest", transport="plain") + + error = caught.value + assert type(error) is exception_type + assert error.args == (message,) + assert error.sqlstate == sqlstate + assert error.errorcode == (0 if sqlstate is not None else None) + assert [request.WhichOneof("type") for request in requests_sent(wire)] == ["connection_request"] + wire.close.assert_called_once_with() + + +@pytest.mark.parametrize(("query", "params", "mode"), [ + ("INSERT INTO t VALUES (?)", (1,), "indexed"), + ("INSERT INTO t VALUES (:id)", {"id": 1}, "named"), +]) +def test_prepared_error_survives_statement_cleanup(wire, query, params, mode): + signature = reply(2, "prepared_statement_signature") + signature.prepared_statement_signature.statement_id = 42 + message = "Primary key conflict.\n" + send_replies( + wire, + login_reply(), + signature, + error_reply(3, message, "23505"), + error_reply(4, "Cleanup failed", "XX000"), + reply(5, "rollback_response"), + reply(6, "disconnect_response"), + ) + + connection = polypheny.connect(("localhost", 20590), transport="plain") + try: + cursor = connection.cursor() + with pytest.raises(polypheny.IntegrityError) as caught: + cursor.execute(query, params) + assert caught.value.args == (message,) + assert caught.value.sqlstate == "23505" + assert caught.value.errorcode == 0 + with pytest.raises(polypheny.ProgrammingError, match="No statement was yet executed"): + cursor.fetchone() + finally: + connection.close() + + requests = requests_sent(wire) + assert [request.WhichOneof("type") for request in requests] == [ + "connection_request", + f"prepare_{mode}_statement_request", + f"execute_{mode}_statement_request", + "close_statement_request", + "rollback_request", + "disconnect_request", + ] + assert requests[3].close_statement_request.statement_id == 42 + + +@pytest.mark.parametrize("unsupported_frame", [False, True], ids=["server-error", "unsupported-frame"]) +def test_fetch_failure_releases_result_and_cursor_can_recover(wire, unsupported_frame): + message = "Division by zero.\n" + if unsupported_frame: + continuation = reply(3, "frame") + continuation.frame.is_last = True + exception_type = polypheny.NotSupportedError + else: + continuation = error_reply(3, message, "22012") + exception_type = polypheny.DataError + + send_replies( + wire, + login_reply(), + *statement_replies(2, 42), + continuation, + reply(4, "close_statement_response"), + reply(5, "rollback_response"), + *statement_replies(6, 43, last=True), + reply(7, "close_statement_response"), + reply(8, "rollback_response"), + reply(9, "disconnect_response"), + ) + + connection = polypheny.connect(("localhost", 20590), transport="plain") + try: + cursor = connection.cursor() + cursor.execute("SELECT 1") + with pytest.raises(exception_type) as caught: + cursor.fetchone() + if not unsupported_frame: + assert caught.value.args == (message,) + assert caught.value.sqlstate == "22012" + assert caught.value.errorcode == 0 + with pytest.raises(polypheny.ProgrammingError, match="No statement was yet executed"): + cursor.fetchone() + connection.rollback() + cursor.execute("SELECT 1") + assert cursor.fetchall() == [[1]] + finally: + connection.close() + + requests = requests_sent(wire) + assert requests[2].fetch_request.statement_id == 42 + assert requests[3].close_statement_request.statement_id == 42 + assert requests[6].close_statement_request.statement_id == 43 + + +def test_vendor_code_without_sqlstate(wire): + response = error_reply(1, "Login rejected.", None) + response.error_response.details.error_code = 0 + send_replies(wire, response) + + with pytest.raises(polypheny.DatabaseError) as caught: + polypheny.connect(("localhost", 20590), transport="plain") + + assert type(caught.value) is polypheny.DatabaseError + assert caught.value.sqlstate is None + assert caught.value.errorcode == 0 + + @pytest.fixture def connection(monkeypatch): prism = Mock() From 4319ecb64a7bc5d9c3da0c599ab9944c126a17eb Mon Sep 17 00:00:00 2001 From: Marco Vogt Date: Sun, 22 Nov 2026 23:09:11 +0100 Subject: [PATCH 3/7] Release paged results on decoding failure --- polypheny/connection.py | 23 +++++++++------------- tests/test_error_mapping_unit.py | 33 +++++++++++++++++++++----------- 2 files changed, 31 insertions(+), 25 deletions(-) diff --git a/polypheny/connection.py b/polypheny/connection.py index 091cfba6..0036ec38 100644 --- a/polypheny/connection.py +++ b/polypheny/connection.py @@ -282,6 +282,15 @@ def fetchone(self): self._require_result() try: n = next(self.result) + if isinstance(n, relational_frame_pb2.Row): + return [proto2py(value) for value in n.values] + if isinstance(n, value_pb2.ProtoDocument): + value = value_pb2.ProtoValue() + value.document.CopyFrom(n) + return proto2py(value) + if isinstance(n, graph_frame_pb2.GraphElement): + return proto_graph_element2py(n) + raise NotSupportedError(f"Unknown result of type {type(n)}") except StopIteration: return None except Error: @@ -289,20 +298,6 @@ def fetchone(self): self.reset() raise - if isinstance(n, relational_frame_pb2.Row): - v = [] - for value in n.values: - v.append(proto2py(value)) - return v - elif isinstance(n, value_pb2.ProtoDocument): - value = value_pb2.ProtoValue() - value.document.CopyFrom(n) - return proto2py(value) - elif isinstance(n, graph_frame_pb2.GraphElement): - return proto_graph_element2py(n) - else: - raise NotSupportedError(f"Unknown result of type {type(n)}") - def fetchmany(self, size=None): self._require_result() if size is None: diff --git a/tests/test_error_mapping_unit.py b/tests/test_error_mapping_unit.py index 67c67022..e41f33b9 100644 --- a/tests/test_error_mapping_unit.py +++ b/tests/test_error_mapping_unit.py @@ -214,16 +214,23 @@ def test_prepared_error_survives_statement_cleanup(wire, query, params, mode): assert requests[3].close_statement_request.statement_id == 42 -@pytest.mark.parametrize("unsupported_frame", [False, True], ids=["server-error", "unsupported-frame"]) -def test_fetch_failure_releases_result_and_cursor_can_recover(wire, unsupported_frame): - message = "Division by zero.\n" - if unsupported_frame: +@pytest.mark.parametrize("failure", ["server-error", "unsupported-frame", "unsupported-value"]) +def test_fetch_failure_releases_result_and_cursor_can_recover(wire, failure): + if failure == "server-error": + message = "Division by zero.\n" + continuation = error_reply(3, message, "22012") + exception_type = polypheny.DataError + else: continuation = reply(3, "frame") continuation.frame.is_last = True exception_type = polypheny.NotSupportedError - else: - continuation = error_reply(3, message, "22012") - exception_type = polypheny.DataError + if failure == "unsupported-value": + rows = continuation.frame.relational_frame.rows + rows.add().values.add(file=value_pb2.ProtoFile()) + rows.add().values.append(py2proto(7)) + message = "Unhandled value type" + else: + message = "Unsupported Prism result frame: None" send_replies( wire, @@ -244,13 +251,17 @@ def test_fetch_failure_releases_result_and_cursor_can_recover(wire, unsupported_ cursor.execute("SELECT 1") with pytest.raises(exception_type) as caught: cursor.fetchone() - if not unsupported_frame: - assert caught.value.args == (message,) + assert type(caught.value) is exception_type + assert caught.value.args == (message,) + if failure == "server-error": assert caught.value.sqlstate == "22012" assert caught.value.errorcode == 0 + cleanup = requests_sent(wire)[-1] + assert cleanup.WhichOneof("type") == "close_statement_request" + assert cleanup.close_statement_request.statement_id == 42 + connection.rollback() with pytest.raises(polypheny.ProgrammingError, match="No statement was yet executed"): cursor.fetchone() - connection.rollback() cursor.execute("SELECT 1") assert cursor.fetchall() == [[1]] finally: @@ -258,7 +269,7 @@ def test_fetch_failure_releases_result_and_cursor_can_recover(wire, unsupported_ requests = requests_sent(wire) assert requests[2].fetch_request.statement_id == 42 - assert requests[3].close_statement_request.statement_id == 42 + assert requests[4].WhichOneof("type") == "rollback_request" assert requests[6].close_statement_request.statement_id == 43 From 00bfa6297e6d8982654f86b8c746a986f6b713b3 Mon Sep 17 00:00:00 2001 From: Marco Vogt Date: Sun, 22 Nov 2026 23:17:25 +0100 Subject: [PATCH 4/7] Pin CI to Neo4j SQLSTATE backend --- .github/workflows/test.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml index e1a696ad..8fb8544c 100644 --- a/.github/workflows/test.yaml +++ b/.github/workflows/test.yaml @@ -12,7 +12,7 @@ jobs: - uses: actions/checkout@v4 with: repository: polypheny/Polypheny-DB - ref: ${{ vars.POLYPHENY_DB_REF || '01a2e438d761190e889f1a9f91426d3264b3e6d8' }} + ref: ${{ vars.POLYPHENY_DB_REF || '4cd0e54276be00a8e620ef848bf74012693ed268' }} - uses: actions/setup-java@v4 with: From aee97dbf1321dc670c01374bb820a3fecfc0f86d Mon Sep 17 00:00:00 2001 From: Marco Vogt Date: Mon, 23 Nov 2026 08:30:30 +0100 Subject: [PATCH 5/7] Address Prism error review and verify both store fixes --- .github/workflows/test.yaml | 2 +- README.md | 6 ++++- polypheny/connection.py | 14 ++++++++++- polypheny/rpc.py | 11 +++++++-- tests/test_error_mapping.py | 16 +++++++++++-- tests/test_error_mapping_unit.py | 40 ++++++++++++++++++++++++++++++++ 6 files changed, 82 insertions(+), 7 deletions(-) diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml index 8fb8544c..4d51fa3e 100644 --- a/.github/workflows/test.yaml +++ b/.github/workflows/test.yaml @@ -12,7 +12,7 @@ jobs: - uses: actions/checkout@v4 with: repository: polypheny/Polypheny-DB - ref: ${{ vars.POLYPHENY_DB_REF || '4cd0e54276be00a8e620ef848bf74012693ed268' }} + ref: ${{ vars.POLYPHENY_DB_REF || 'c548758eaa8aa55c936656eb6c09fdaefb537517' }} - uses: actions/setup-java@v4 with: diff --git a/README.md b/README.md index 05c81054..f89c78bc 100644 --- a/README.md +++ b/README.md @@ -85,11 +85,15 @@ con.close() An in-depth and more detailed documentation can be found [here](https://docs.polypheny.com/en/latest/drivers/python/overview). ## Tests -Run the tests with coverage report: +Run the tests with a coverage report against an isolated Polypheny instance. ``` coverage run --source polypheny -m pytest && coverage report -m ``` +The constraint tests read the test server's runtime settings through its Web UI +at `http://127.0.0.1:7659`. Set `POLYPHENY_TEST_WEBUI_URL` if the same test server +exposes its Web UI at a different address. + ## Roadmap See the [open issues](https://github.com/polypheny/Polypheny-DB/labels/A-python) for a list of proposed features (and known issues). diff --git a/polypheny/connection.py b/polypheny/connection.py index 0036ec38..cb9c4dd2 100644 --- a/polypheny/connection.py +++ b/polypheny/connection.py @@ -17,7 +17,19 @@ from org.polypheny.prism import graph_frame_pb2, relational_frame_pb2, value_pb2 from polypheny import rpc -from polypheny.exceptions import Error, InterfaceError, NotSupportedError, ProgrammingError +# Preserve the exception names exposed by this module in previous releases. +from polypheny.exceptions import ( + DataError as DataError, + DatabaseError as DatabaseError, + Error as Error, + IntegrityError as IntegrityError, + InterfaceError as InterfaceError, + InternalError as InternalError, + NotSupportedError as NotSupportedError, + OperationalError as OperationalError, + ProgrammingError as ProgrammingError, + Warning as Warning, +) from polypheny.serialize import proto2py, proto_graph_element2py diff --git a/polypheny/rpc.py b/polypheny/rpc.py index 19ba2bf8..87b08933 100644 --- a/polypheny/rpc.py +++ b/polypheny/rpc.py @@ -231,15 +231,22 @@ def execute_unparameterized_statement(self, language_name, statement, fetch_size self.send_msg(msg) started = self.recv_msg(msg.id) self._require_response(started, 'statement_response', last=False) + statement_id = started.statement_response.statement_id try: completed = self.recv_msg(msg.id) except Error: # Prism allocated a statement before evaluating the query. with suppress(Error): - self.close_statement(started.statement_response.statement_id) + self.close_statement(statement_id) raise self._require_response(completed, 'statement_response') - return completed.statement_response + result = completed.statement_response + if result.statement_id != statement_id: + self.abort() + raise InterfaceError( + f"Unexpected Prism statement ID {result.statement_id}, expected {statement_id}" + ) + return result def prepare_indexed_statement(self, language_name, statement, namespace): msg = self.new_request() diff --git a/tests/test_error_mapping.py b/tests/test_error_mapping.py index 01dd9905..04054193 100644 --- a/tests/test_error_mapping.py +++ b/tests/test_error_mapping.py @@ -13,8 +13,10 @@ # limitations under the License. +import json import os from contextlib import contextmanager +from urllib.request import Request, urlopen import pytest @@ -72,12 +74,22 @@ def test_sql_statement_error(con, errtest, statement, exception_type, sqlstates) @contextmanager def enable_constraint_enforcement(connection, cursor, key): - cursor.execute(f"ALTER CONFIG 'runtime/{key}' SET true") + key = f"runtime/{key}" + webui_url = os.environ.get("POLYPHENY_TEST_WEBUI_URL", "http://127.0.0.1:7659") + request = Request(f"{webui_url.rstrip('/')}/config/v1/getConfig", data=key.encode(), + headers={"Content-Type": "text/plain"}) + with urlopen(request, timeout=10) as response: + enabled = json.load(response)["value"] + assert isinstance(enabled, bool), f"Expected a boolean runtime setting for {key}" + + if not enabled: + cursor.execute(f"ALTER CONFIG '{key}' SET true") try: yield finally: connection.rollback() - cursor.execute(f"ALTER CONFIG 'runtime/{key}' SET false") + if not enabled: + cursor.execute(f"ALTER CONFIG '{key}' SET false") def test_s10_duplicate_primary_key_enforced(con, errtest): diff --git a/tests/test_error_mapping_unit.py b/tests/test_error_mapping_unit.py index e41f33b9..ed934a7c 100644 --- a/tests/test_error_mapping_unit.py +++ b/tests/test_error_mapping_unit.py @@ -86,6 +86,14 @@ def test_exception_constructible_with_message(): assert error.errorcode is None +def test_connection_module_preserves_exception_aliases(): + for name in ( + "DataError", "DatabaseError", "Error", "IntegrityError", "InterfaceError", + "InternalError", "NotSupportedError", "OperationalError", "ProgrammingError", "Warning", + ): + assert getattr(polypheny.connection, name) is getattr(polypheny, name) + + def test_prism_error_without_vendor_code(): response = protointerface_pb2.Response(id=1, last=True) response.error_response.details.state = "23502" @@ -151,6 +159,38 @@ def requests_sent(wire): ] +def test_mismatched_statement_id_aborts_connection(wire): + started, completed = statement_replies(2, 42, last=True) + completed.statement_response.statement_id = 43 + send_replies( + wire, + login_reply(), + started, + completed, + reply(3, "close_statement_response"), + reply(4, "rollback_response"), + reply(5, "disconnect_response"), + ) + + connection = polypheny.connect(("localhost", 20590), transport="plain") + try: + cursor = connection.cursor() + with pytest.raises(polypheny.InterfaceError, match="Unexpected Prism statement ID 43, expected 42"): + cursor.execute("SELECT 1") + with pytest.raises(polypheny.ProgrammingError, match="No statement was yet executed"): + cursor.fetchone() + with pytest.raises(polypheny.OperationalError): + connection.rollback() + finally: + connection.close() + + assert [request.WhichOneof("type") for request in requests_sent(wire)] == [ + "connection_request", + "execute_unparameterized_statement_request", + ] + wire.close.assert_called_once_with() + + @pytest.mark.parametrize(("sqlstate", "exception_type"), [ ("28P01", polypheny.OperationalError), (None, polypheny.DatabaseError), From 8a6c67eb46dee5def3067e2e2839dc43a32f1b34 Mon Sep 17 00:00:00 2001 From: Marco Vogt Date: Mon, 23 Nov 2026 08:48:56 +0100 Subject: [PATCH 6/7] Restore test constraints after Prism disconnects --- tests/test_constraint_fixture.py | 99 ++++++++++++++++++++++++++++++++ tests/test_error_mapping.py | 42 ++++++++++---- 2 files changed, 130 insertions(+), 11 deletions(-) create mode 100644 tests/test_constraint_fixture.py diff --git a/tests/test_constraint_fixture.py b/tests/test_constraint_fixture.py new file mode 100644 index 00000000..989e9b0e --- /dev/null +++ b/tests/test_constraint_fixture.py @@ -0,0 +1,99 @@ +# Copyright 2026 The Polypheny Project +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import json +from io import BytesIO +from unittest.mock import Mock + +import pytest + +import polypheny +import test_error_mapping +from test_error_mapping import enable_constraint_enforcement + + +WEBUI_URL = "http://polypheny.invalid:8765" +KEY = "uniqueConstraintEnforcement" +RUNTIME_KEY = f"runtime/{KEY}" + + +@pytest.fixture +def config_http(monkeypatch): + monkeypatch.setenv("POLYPHENY_TEST_WEBUI_URL", f"{WEBUI_URL}/") + urlopen = Mock(side_effect=[ + BytesIO(b'{"value": false}'), + BytesIO(b'{"successful": true, "message": "All values were saved."}'), + ]) + monkeypatch.setattr(test_error_mapping, "urlopen", urlopen) + return urlopen + + +def assert_http_restore(config_http): + assert config_http.call_count == 2 + lookup, restore = [call.args[0] for call in config_http.call_args_list] + assert lookup.full_url == f"{WEBUI_URL}/config/v1/getConfig" + assert lookup.data.decode() == RUNTIME_KEY + assert restore.full_url == f"{WEBUI_URL}/config/v1/updateConfigs" + assert restore.get_method() == "POST" + assert restore.get_header("Content-type") == "application/json" + assert json.loads(restore.data) == {RUNTIME_KEY: False} + + +def test_constraint_fixture_restores_after_lost_alter_reply(config_http): + connection, cursor = Mock(), Mock() + alter_error = polypheny.OperationalError("ALTER reply was lost") + cursor.execute.side_effect = alter_error + + with pytest.raises(polypheny.OperationalError) as caught: + with enable_constraint_enforcement(connection, cursor, KEY): + pytest.fail("The fixture body should not run after a failed ALTER") + + assert caught.value is alter_error + connection.rollback.assert_called_once_with() + cursor.execute.assert_called_once_with(f"ALTER CONFIG '{RUNTIME_KEY}' SET true") + assert_http_restore(config_http) + + +def test_constraint_fixture_restores_after_lost_rollback(config_http): + connection, cursor = Mock(), Mock() + rollback_error = polypheny.OperationalError("Prism transport lost during rollback") + connection.rollback.side_effect = rollback_error + + with pytest.raises(polypheny.OperationalError) as caught: + with enable_constraint_enforcement(connection, cursor, KEY): + pass + + assert caught.value is rollback_error + connection.rollback.assert_called_once_with() + cursor.execute.assert_called_once_with(f"ALTER CONFIG '{RUNTIME_KEY}' SET true") + assert_http_restore(config_http) + + +def test_constraint_fixture_preserves_test_failure_when_cleanup_fails(config_http, caplog): + connection, cursor = Mock(), Mock() + test_error = AssertionError("Original test failure") + connection.rollback.side_effect = polypheny.OperationalError("Prism transport lost during rollback") + config_http.side_effect = [ + BytesIO(b'{"value": false}'), + BytesIO(b'{"successful": false, "message": "Setting was rejected."}'), + ] + + with pytest.raises(AssertionError) as caught: + with enable_constraint_enforcement(connection, cursor, KEY): + raise test_error + + assert caught.value is test_error + connection.rollback.assert_called_once_with() + assert_http_restore(config_http) + assert "Setting was rejected." in caplog.text diff --git a/tests/test_error_mapping.py b/tests/test_error_mapping.py index 04054193..c329bb04 100644 --- a/tests/test_error_mapping.py +++ b/tests/test_error_mapping.py @@ -14,6 +14,7 @@ import json +import logging import os from contextlib import contextmanager from urllib.request import Request, urlopen @@ -72,24 +73,43 @@ def test_sql_statement_error(con, errtest, statement, exception_type, sqlstates) assert_recovered(con, errtest) +def _config_request(webui_url, endpoint, data, content_type): + request = Request(f"{webui_url}/config/v1/{endpoint}", data=data.encode(), + headers={"Content-Type": content_type}) + with urlopen(request, timeout=10) as response: + return json.load(response) + + @contextmanager def enable_constraint_enforcement(connection, cursor, key): key = f"runtime/{key}" - webui_url = os.environ.get("POLYPHENY_TEST_WEBUI_URL", "http://127.0.0.1:7659") - request = Request(f"{webui_url.rstrip('/')}/config/v1/getConfig", data=key.encode(), - headers={"Content-Type": "text/plain"}) - with urlopen(request, timeout=10) as response: - enabled = json.load(response)["value"] + webui_url = os.environ.get("POLYPHENY_TEST_WEBUI_URL", "http://127.0.0.1:7659").rstrip("/") + enabled = _config_request(webui_url, "getConfig", key, "text/plain")["value"] assert isinstance(enabled, bool), f"Expected a boolean runtime setting for {key}" - if not enabled: - cursor.execute(f"ALTER CONFIG '{key}' SET true") + def cleanup(): + try: + connection.rollback() + finally: + if not enabled: + # The config server can restore the setting even if Prism has disconnected. + feedback = _config_request(webui_url, "updateConfigs", json.dumps({key: enabled}), + "application/json") + if feedback.get("successful") is not True: + raise RuntimeError(f"Could not restore {key}: {feedback}") + try: - yield - finally: - connection.rollback() if not enabled: - cursor.execute(f"ALTER CONFIG '{key}' SET false") + cursor.execute(f"ALTER CONFIG '{key}' SET true") + yield + except BaseException: + try: + cleanup() + except Exception: + logging.getLogger(__name__).exception("Cleanup failed for %s", key) + raise + else: + cleanup() def test_s10_duplicate_primary_key_enforced(con, errtest): From 07671d8851482b67acfd50974074d19e8da8e3f7 Mon Sep 17 00:00:00 2001 From: Marco Vogt Date: Mon, 23 Nov 2026 09:54:33 +0100 Subject: [PATCH 7/7] Test against Polypheny-DB master after SQLSTATE merge --- .github/workflows/test.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml index 4d51fa3e..9f9d957e 100644 --- a/.github/workflows/test.yaml +++ b/.github/workflows/test.yaml @@ -12,7 +12,7 @@ jobs: - uses: actions/checkout@v4 with: repository: polypheny/Polypheny-DB - ref: ${{ vars.POLYPHENY_DB_REF || 'c548758eaa8aa55c936656eb6c09fdaefb537517' }} + ref: ${{ vars.POLYPHENY_DB_REF || 'master' }} - uses: actions/setup-java@v4 with: