From 5e42bb6a24807c2e9642f311d25ed7aff7a49b43 Mon Sep 17 00:00:00 2001 From: Jahnvi Thakkar Date: Fri, 20 Nov 2026 09:39:57 +0530 Subject: [PATCH] FEAT: Expose SQLSTATE on DB-API exceptions Preserve SQLSTATE metadata without changing existing exception messages, args, or legacy pickle reconstruction. Add public typing, documentation, and regression coverage. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- README.md | 25 +++ mssql_python/connection.py | 1 + mssql_python/exceptions.py | 76 ++++++--- mssql_python/mssql_python.pyi | 42 +++-- tests/AsyncTest/test_003_async_exceptions.py | 1 + tests/test_006_exceptions.py | 155 +++++++++++++++---- tests/test_typing.py | 29 ++++ 7 files changed, 271 insertions(+), 58 deletions(-) diff --git a/README.md b/README.md index 620cc63e9..1ef790995 100644 --- a/README.md +++ b/README.md @@ -151,6 +151,31 @@ The Microsoft **mssql-python** module is designed to be fully compliant with the By adhering to the DB API 2.0 specification, the mssql-python module ensures compatibility with a wide range of Python applications and frameworks, making it a versatile choice for developers working with Microsoft SQL Server, Azure SQL Database, and Azure SQL Managed Instance. +### Error classification with SQLSTATE + +DB-API exceptions expose `sqlstate: str | None`. Synchronous ODBC errors retain +their diagnostic SQLSTATE, including codes not recognized by the driver's +exception mapping. When no SQLSTATE is available, the attribute is `None`. +Python-created errors and async Rust/TDS errors default to `None`. + +```python +from mssql_python import Error + +try: + cursor.execute("SELECT * FROM missing_table") +except Error as exc: + # getattr also supports driver versions without the sqlstate attribute. + if getattr(exc, "sqlstate", None) == "42S02": + print("The requested table was not found.") + raise +``` + +Existing exception types, two-argument constructors, messages, and `args` are +unchanged. Constructors also accept the optional keyword-only `sqlstate` argument, +and SQLSTATE metadata survives pickling and copying. A SQLSTATE alone does not +guarantee that retrying an operation is safe. Native SQL Server error numbers are +not exposed by this attribute. + ### Enhanced Pythonic Features The driver offers a suite of Pythonic enhancements that streamline database interactions, making it easier for developers to execute queries, manage connections, and handle data more efficiently. diff --git a/mssql_python/connection.py b/mssql_python/connection.py index 8247c2701..44fc61f49 100644 --- a/mssql_python/connection.py +++ b/mssql_python/connection.py @@ -242,6 +242,7 @@ def _raise_connection_error(e: RuntimeError) -> NoReturn: raise DatabaseError( driver_error=f"An error occurred with SQLSTATE code: {sqlstate}", ddbc_error=ddbc_error, + sqlstate=sqlstate, ) from None logger.error("Connection error (SQLSTATE %s): %s", sqlstate, ddbc_error) raise exc from None diff --git a/mssql_python/exceptions.py b/mssql_python/exceptions.py index 602d7c1bd..45acbe01f 100644 --- a/mssql_python/exceptions.py +++ b/mssql_python/exceptions.py @@ -37,11 +37,16 @@ def __reduce__(self) -> tuple[type["ConnectionStringParseError"], tuple[list[str class Exception(builtins.Exception): """ Base class for all DB API 2.0 exceptions. + + sqlstate is the diagnostic SQLSTATE when available, otherwise None. """ - def __init__(self, driver_error: str, ddbc_error: str) -> None: + def __init__( + self, driver_error: str, ddbc_error: str, *, sqlstate: Optional[str] = None + ) -> None: self.driver_error = driver_error self.ddbc_error = truncate_error_message(ddbc_error) + self.sqlstate = sqlstate or None if self.ddbc_error: # Both driver and DDBC errors are present self.message = f"Driver Error: {self.driver_error}; DDBC Error: {self.ddbc_error}" @@ -55,12 +60,14 @@ def __reduce__( ) -> tuple[ Callable[[type["Exception"], str, str, str], "Exception"], tuple[type["Exception"], str, str, str], + dict[str, Optional[str]], ]: # Reconstruct without re-running __init__/truncate_error_message() to avoid # emitting warnings for already-truncated "[Microsoft]..." messages. return ( Exception._unpickle, (self.__class__, self.driver_error, self.ddbc_error, self.message), + {"sqlstate": self.sqlstate}, ) @staticmethod @@ -71,6 +78,7 @@ def _unpickle( obj.driver_error = driver_error obj.ddbc_error = ddbc_error obj.message = message + obj.sqlstate = None builtins.Exception.__init__(obj, message) return obj @@ -80,8 +88,10 @@ class Warning(Exception): Exception raised for important warnings like data truncations while inserting, etc. """ - def __init__(self, driver_error: str, ddbc_error: str) -> None: - super().__init__(driver_error, ddbc_error) + def __init__( + self, driver_error: str, ddbc_error: str, *, sqlstate: Optional[str] = None + ) -> None: + super().__init__(driver_error, ddbc_error, sqlstate=sqlstate) class Error(Exception): @@ -89,8 +99,10 @@ class Error(Exception): Base class for errors. """ - def __init__(self, driver_error: str, ddbc_error: str) -> None: - super().__init__(driver_error, ddbc_error) + def __init__( + self, driver_error: str, ddbc_error: str, *, sqlstate: Optional[str] = None + ) -> None: + super().__init__(driver_error, ddbc_error, sqlstate=sqlstate) class InterfaceError(Error): @@ -99,8 +111,10 @@ class InterfaceError(Error): interface rather than the database itself. """ - def __init__(self, driver_error: str, ddbc_error: str) -> None: - super().__init__(driver_error, ddbc_error) + def __init__( + self, driver_error: str, ddbc_error: str, *, sqlstate: Optional[str] = None + ) -> None: + super().__init__(driver_error, ddbc_error, sqlstate=sqlstate) class DatabaseError(Error): @@ -108,8 +122,10 @@ class DatabaseError(Error): Exception raised for errors that are related to the database. """ - def __init__(self, driver_error: str, ddbc_error: str) -> None: - super().__init__(driver_error, ddbc_error) + def __init__( + self, driver_error: str, ddbc_error: str, *, sqlstate: Optional[str] = None + ) -> None: + super().__init__(driver_error, ddbc_error, sqlstate=sqlstate) class DataError(DatabaseError): @@ -118,8 +134,10 @@ class DataError(DatabaseError): processed data like division by zero, numeric value out of range, etc. """ - def __init__(self, driver_error: str, ddbc_error: str) -> None: - super().__init__(driver_error, ddbc_error) + def __init__( + self, driver_error: str, ddbc_error: str, *, sqlstate: Optional[str] = None + ) -> None: + super().__init__(driver_error, ddbc_error, sqlstate=sqlstate) class OperationalError(DatabaseError): @@ -128,8 +146,10 @@ class OperationalError(DatabaseError): and not necessarily under the control of the programmer. """ - def __init__(self, driver_error: str, ddbc_error: str) -> None: - super().__init__(driver_error, ddbc_error) + def __init__( + self, driver_error: str, ddbc_error: str, *, sqlstate: Optional[str] = None + ) -> None: + super().__init__(driver_error, ddbc_error, sqlstate=sqlstate) class IntegrityError(DatabaseError): @@ -138,8 +158,10 @@ class IntegrityError(DatabaseError): e.g., a foreign key check fails. """ - def __init__(self, driver_error: str, ddbc_error: str) -> None: - super().__init__(driver_error, ddbc_error) + def __init__( + self, driver_error: str, ddbc_error: str, *, sqlstate: Optional[str] = None + ) -> None: + super().__init__(driver_error, ddbc_error, sqlstate=sqlstate) class InternalError(DatabaseError): @@ -148,8 +170,10 @@ class InternalError(DatabaseError): e.g., the cursor is not valid anymore, the transaction is out of sync, etc. """ - def __init__(self, driver_error: str, ddbc_error: str) -> None: - super().__init__(driver_error, ddbc_error) + def __init__( + self, driver_error: str, ddbc_error: str, *, sqlstate: Optional[str] = None + ) -> None: + super().__init__(driver_error, ddbc_error, sqlstate=sqlstate) class ProgrammingError(DatabaseError): @@ -159,8 +183,10 @@ class ProgrammingError(DatabaseError): wrong number of parameters specified, etc. """ - def __init__(self, driver_error: str, ddbc_error: str) -> None: - super().__init__(driver_error, ddbc_error) + def __init__( + self, driver_error: str, ddbc_error: str, *, sqlstate: Optional[str] = None + ) -> None: + super().__init__(driver_error, ddbc_error, sqlstate=sqlstate) class NotSupportedError(DatabaseError): @@ -170,8 +196,10 @@ class NotSupportedError(DatabaseError): on a connection that does not support transaction or has transactions turned off. """ - def __init__(self, driver_error: str, ddbc_error: str) -> None: - super().__init__(driver_error, ddbc_error) + def __init__( + self, driver_error: str, ddbc_error: str, *, sqlstate: Optional[str] = None + ) -> None: + super().__init__(driver_error, ddbc_error, sqlstate=sqlstate) # Mapping SQLSTATE codes to custom exception classes @@ -550,7 +578,10 @@ def sqlstate_to_exception(sqlstate: str, ddbc_error: str) -> Optional[Exception] driver_error="Corrupt file data source", ddbc_error=ddbc_error ), # Corrupt file data source } - return mapping.get(sqlstate, None) + exception = mapping.get(sqlstate) + if exception is not None: + exception.sqlstate = sqlstate or None + return exception def truncate_error_message(error_message: str) -> str: @@ -592,4 +623,5 @@ def raise_exception(sqlstate: str, ddbc_error: str) -> None: raise DatabaseError( driver_error=f"An error occurred with SQLSTATE code: {sqlstate}", ddbc_error=f"{ddbc_error}" if ddbc_error else "Unknown DDBC error", + sqlstate=sqlstate, ) diff --git a/mssql_python/mssql_python.pyi b/mssql_python/mssql_python.pyi index 123292cbd..cc30eb143 100644 --- a/mssql_python/mssql_python.pyi +++ b/mssql_python/mssql_python.pyi @@ -103,40 +103,62 @@ def Binary(value: Union[str, bytes, bytearray, memoryview]) -> bytes: ... # DB-API 2.0 Exception Hierarchy # https://www.python.org/dev/peps/pep-0249/#exceptions class Warning(Exception): - def __init__(self, driver_error: str, ddbc_error: str) -> None: ... + def __init__( + self, driver_error: str, ddbc_error: str, *, sqlstate: Optional[str] = None + ) -> None: ... driver_error: str ddbc_error: str message: str + sqlstate: Optional[str] class Error(Exception): - def __init__(self, driver_error: str, ddbc_error: str) -> None: ... + def __init__( + self, driver_error: str, ddbc_error: str, *, sqlstate: Optional[str] = None + ) -> None: ... driver_error: str ddbc_error: str message: str + sqlstate: Optional[str] class InterfaceError(Error): - def __init__(self, driver_error: str, ddbc_error: str) -> None: ... + def __init__( + self, driver_error: str, ddbc_error: str, *, sqlstate: Optional[str] = None + ) -> None: ... class DatabaseError(Error): - def __init__(self, driver_error: str, ddbc_error: str) -> None: ... + def __init__( + self, driver_error: str, ddbc_error: str, *, sqlstate: Optional[str] = None + ) -> None: ... class DataError(DatabaseError): - def __init__(self, driver_error: str, ddbc_error: str) -> None: ... + def __init__( + self, driver_error: str, ddbc_error: str, *, sqlstate: Optional[str] = None + ) -> None: ... class OperationalError(DatabaseError): - def __init__(self, driver_error: str, ddbc_error: str) -> None: ... + def __init__( + self, driver_error: str, ddbc_error: str, *, sqlstate: Optional[str] = None + ) -> None: ... class IntegrityError(DatabaseError): - def __init__(self, driver_error: str, ddbc_error: str) -> None: ... + def __init__( + self, driver_error: str, ddbc_error: str, *, sqlstate: Optional[str] = None + ) -> None: ... class InternalError(DatabaseError): - def __init__(self, driver_error: str, ddbc_error: str) -> None: ... + def __init__( + self, driver_error: str, ddbc_error: str, *, sqlstate: Optional[str] = None + ) -> None: ... class ProgrammingError(DatabaseError): - def __init__(self, driver_error: str, ddbc_error: str) -> None: ... + def __init__( + self, driver_error: str, ddbc_error: str, *, sqlstate: Optional[str] = None + ) -> None: ... class NotSupportedError(DatabaseError): - def __init__(self, driver_error: str, ddbc_error: str) -> None: ... + def __init__( + self, driver_error: str, ddbc_error: str, *, sqlstate: Optional[str] = None + ) -> None: ... # Row Object class Row: diff --git a/tests/AsyncTest/test_003_async_exceptions.py b/tests/AsyncTest/test_003_async_exceptions.py index e8987d759..f733bad3c 100644 --- a/tests/AsyncTest/test_003_async_exceptions.py +++ b/tests/AsyncTest/test_003_async_exceptions.py @@ -36,6 +36,7 @@ def test_translates_each_native_dbapi_exception(name): assert isinstance(translated, getattr(public_exceptions, name)) assert translated.driver_error == "Async operation failed" assert translated.ddbc_error == "native failure" + assert translated.sqlstate is None def test_translation_normalizes_native_detail_as_backend_error(): diff --git a/tests/test_006_exceptions.py b/tests/test_006_exceptions.py index 16569a172..09442b355 100644 --- a/tests/test_006_exceptions.py +++ b/tests/test_006_exceptions.py @@ -17,6 +17,38 @@ ) from mssql_python import ConnectionStringParseError +EXCEPTION_CLASSES = ( + Exception, + Warning, + Error, + InterfaceError, + DatabaseError, + DataError, + OperationalError, + IntegrityError, + InternalError, + ProgrammingError, + NotSupportedError, +) + + +@pytest.mark.parametrize("cls", EXCEPTION_CLASSES) +@pytest.mark.parametrize("ddbc_error", ["ddbc msg", ""]) +def test_exception_sqlstate_constructor_compatibility(cls, ddbc_error): + original = cls("driver msg", ddbc_error) + keyword = cls(driver_error="driver msg", ddbc_error=ddbc_error) + diagnostic = cls("driver msg", ddbc_error, sqlstate="42000") + + assert original.sqlstate is None + assert keyword.sqlstate is None + assert diagnostic.sqlstate == "42000" + for error in (keyword, diagnostic): + assert error.driver_error == original.driver_error + assert error.ddbc_error == original.ddbc_error + assert error.message == original.message + assert str(error) == str(original) + assert error.args == original.args == (original.message,) + def drop_table_if_exists(cursor, table_name): """Drop the table if it exists""" @@ -42,12 +74,14 @@ def test_raise_exception(): str(excinfo.value) == "Driver Error: Syntax error or access violation; DDBC Error: Syntax error or access violation" ) + assert excinfo.value.sqlstate == "42000" def test_warning_exception(): with pytest.raises(Warning) as excinfo: raise_exception("01000", "General warning") assert str(excinfo.value) == "Driver Error: General warning; DDBC Error: General warning" + assert excinfo.value.sqlstate == "01000" def test_data_error_exception(): @@ -57,6 +91,7 @@ def test_data_error_exception(): str(excinfo.value) == "Driver Error: Numeric value out of range; DDBC Error: Numeric value out of range" ) + assert excinfo.value.sqlstate == "22003" def test_operational_error_exception(): @@ -66,6 +101,7 @@ def test_operational_error_exception(): str(excinfo.value) == "Driver Error: Client unable to establish connection; DDBC Error: Client unable to establish connection" ) + assert excinfo.value.sqlstate == "08001" def test_integrity_error_exception(): @@ -75,6 +111,7 @@ def test_integrity_error_exception(): str(excinfo.value) == "Driver Error: Integrity constraint violation; DDBC Error: Integrity constraint violation" ) + assert excinfo.value.sqlstate == "23000" def test_internal_error_exception(): @@ -84,6 +121,7 @@ def test_internal_error_exception(): str(excinfo.value) == "Driver Error: Integrity constraint violation; DDBC Error: Integrity constraint violation" ) + assert excinfo.value.sqlstate == "40002" def test_programming_error_exception(): @@ -93,6 +131,7 @@ def test_programming_error_exception(): str(excinfo.value) == "Driver Error: Base table or view not found; DDBC Error: Base table or view not found" ) + assert excinfo.value.sqlstate == "42S02" def test_not_supported_error_exception(): @@ -102,6 +141,7 @@ def test_not_supported_error_exception(): str(excinfo.value) == "Driver Error: Driver does not support this function; DDBC Error: Driver does not support this function" ) + assert excinfo.value.sqlstate == "IM001" def test_unknown_error_exception(): @@ -111,18 +151,44 @@ def test_unknown_error_exception(): str(excinfo.value) == "Driver Error: An error occurred with SQLSTATE code: 99999; DDBC Error: Unknown error" ) + assert excinfo.value.sqlstate == "99999" + + +@pytest.mark.parametrize( + "sqlstate, expected_type", + [("42000", ProgrammingError), ("99999", DatabaseError), ("", DatabaseError)], +) +def test_check_error_preserves_diagnostic_sqlstate(monkeypatch, sqlstate, expected_type): + from types import SimpleNamespace + from unittest.mock import Mock + from mssql_python import helpers + + diagnostic = SimpleNamespace(sqlState=sqlstate, ddbcErrorMsg="diagnostic message") + read_error = Mock(return_value=diagnostic) + monkeypatch.setattr(helpers.ddbc_bindings, "DDBCSQLCheckError", read_error) + handle = object() + + with pytest.raises(expected_type) as caught: + helpers.check_error(3, handle, -1) + + assert type(caught.value) is expected_type + assert caught.value.sqlstate == (sqlstate or None) + assert caught.value.ddbc_error == "diagnostic message" + read_error.assert_called_once_with(3, handle, -1) def test_syntax_error(cursor): with pytest.raises(ProgrammingError) as excinfo: cursor.execute("SELEC * FROM non_existent_table") assert "Syntax error or access violation" in str(excinfo.value) + assert excinfo.value.sqlstate == "42000" def test_table_not_found_error(cursor): with pytest.raises(ProgrammingError) as excinfo: cursor.execute("SELECT * FROM non_existent_table") assert "Base table or view not found" in str(excinfo.value) + assert excinfo.value.sqlstate == "42S02" def test_data_truncation_error(cursor, db_connection): @@ -150,6 +216,7 @@ def test_unique_constraint_error(cursor, db_connection): with pytest.raises(IntegrityError) as excinfo: cursor.execute("INSERT INTO #pytest_test_unique (id, name) VALUES (?, ?)", [1, "Name2"]) assert "Integrity constraint violation" in str(excinfo.value) + assert excinfo.value.sqlstate == "23000" except Exception as e: pytest.fail(f"Test failed: {e}") finally: @@ -208,6 +275,7 @@ def test_connect_runtime_error_mapped_to_correct_dbapi_exception(): with pytest.raises(OperationalError) as exc_info: connect("Server=testserver;Database=mydb;Trusted_Connection=yes;") assert "Login failed for user" in exc_info.value.ddbc_error + assert exc_info.value.sqlstate == "28000" assert not isinstance(exc_info.value, RuntimeError) # SQLSTATE IM002 = driver not found -> OperationalError (per SQLSTATE mapping) @@ -220,6 +288,7 @@ def test_connect_runtime_error_mapped_to_correct_dbapi_exception(): with pytest.raises(OperationalError) as exc_info: connect("Server=testserver;Database=mydb;Trusted_Connection=yes;") assert "no default driver" in exc_info.value.ddbc_error + assert exc_info.value.sqlstate == "IM002" assert not isinstance(exc_info.value, RuntimeError) # No SQLSTATE prefix -> fallback OperationalError @@ -230,6 +299,7 @@ def test_connect_runtime_error_mapped_to_correct_dbapi_exception(): with pytest.raises(OperationalError) as exc_info: connect("Server=testserver;Database=mydb;Trusted_Connection=yes;") assert "Connection handle not allocated" in exc_info.value.ddbc_error + assert exc_info.value.sqlstate is None assert not isinstance(exc_info.value, RuntimeError) # Unmapped SQLSTATE (sqlstate_to_exception returns None) -> DatabaseError @@ -241,6 +311,7 @@ def test_connect_runtime_error_mapped_to_correct_dbapi_exception(): connect("Server=testserver;Database=mydb;Trusted_Connection=yes;") assert "Unknown error with unmapped code" in exc_info.value.ddbc_error assert "SQLSTATE code: 99999" in exc_info.value.driver_error + assert exc_info.value.sqlstate == "99999" assert not isinstance(exc_info.value, RuntimeError) # Malformed SQLSTATE (empty code) -> OperationalError @@ -251,6 +322,7 @@ def test_connect_runtime_error_mapped_to_correct_dbapi_exception(): with pytest.raises(OperationalError) as exc_info: connect("Server=testserver;Database=mydb;Trusted_Connection=yes;") assert "Invalid handle!" in exc_info.value.ddbc_error + assert exc_info.value.sqlstate is None assert not isinstance(exc_info.value, RuntimeError) # commit() failure -> OperationalError via same _raise_connection_error path @@ -262,6 +334,7 @@ def test_connect_runtime_error_mapped_to_correct_dbapi_exception(): with pytest.raises(OperationalError) as exc_info: conn.commit() assert "Communication link failure" in exc_info.value.ddbc_error + assert exc_info.value.sqlstate == "08S01" assert not isinstance(exc_info.value, RuntimeError) # rollback() failure -> OperationalError via same _raise_connection_error path @@ -273,6 +346,7 @@ def test_connect_runtime_error_mapped_to_correct_dbapi_exception(): with pytest.raises(OperationalError) as exc_info: conn2.rollback() assert "Communication link failure" in exc_info.value.ddbc_error + assert exc_info.value.sqlstate == "08S01" assert not isinstance(exc_info.value, RuntimeError) @@ -287,9 +361,10 @@ def test_close_cleans_up_after_rollback_failure(): with patch("mssql_python.connection.ddbc_bindings.Connection", return_value=mock_conn): conn = connect("Server=testserver;Database=mydb;Trusted_Connection=yes;") - with pytest.raises(OperationalError, match="Communication link failure"): + with pytest.raises(OperationalError, match="Communication link failure") as caught: conn.close() + assert caught.value.sqlstate == "08S01" mock_conn.rollback.assert_not_called() mock_conn.close.assert_called_once_with(rollback_before_disconnect=True) assert conn._conn is None @@ -587,39 +662,66 @@ def test_truncate_error_message_return_paths(): # --------------------------------------------------------------------------- -def test_exception_pickle_roundtrip(): +@pytest.mark.parametrize("cls", EXCEPTION_CLASSES) +@pytest.mark.parametrize("sqlstate", [None, "42000"]) +def test_exception_pickle_roundtrip(cls, sqlstate): """All DB-API exception subclasses must survive a pickle round-trip.""" import pickle import copy - exception_classes = [ - Warning, - Error, - InterfaceError, - DatabaseError, - DataError, - OperationalError, - IntegrityError, - InternalError, - ProgrammingError, - NotSupportedError, - ] + original = cls("driver msg", "ddbc msg", sqlstate=sqlstate) + + restored = pickle.loads(pickle.dumps(original)) + for result in (restored, copy.copy(original), copy.deepcopy(original)): + assert type(result) is cls + assert result.driver_error == original.driver_error + assert result.ddbc_error == original.ddbc_error + assert result.message == original.message + assert result.sqlstate == sqlstate + assert str(result) == str(original) + assert result.args == original.args + + +def test_exception_legacy_pickle_defaults_to_no_sqlstate(): + import pickle + + class LegacyPayload: + def __reduce__(self): + return ( + Exception._unpickle, + (ProgrammingError, "driver msg", "ddbc msg", "original message"), + ) - for cls in exception_classes: - original = cls("driver msg", "ddbc msg") + restored = pickle.loads(pickle.dumps(LegacyPayload())) + + assert type(restored) is ProgrammingError + assert restored.sqlstate is None + assert restored.driver_error == "driver msg" + assert restored.ddbc_error == "ddbc msg" + assert restored.message == "original message" + assert restored.args == ("original message",) - # pickle round-trip - restored = pickle.loads(pickle.dumps(original)) - assert type(restored) is cls, f"{cls.__name__}: type mismatch after unpickle" - assert restored.driver_error == "driver msg", f"{cls.__name__}: driver_error mismatch" - assert restored.ddbc_error == "ddbc msg", f"{cls.__name__}: ddbc_error mismatch" - assert str(restored) == str(original), f"{cls.__name__}: str() mismatch" +def test_exception_pickle_does_not_retruncate_diagnostics(monkeypatch): + import copy + import pickle + from unittest.mock import Mock + from mssql_python import exceptions + + original = ProgrammingError( + "driver msg", + "[Microsoft][ODBC Driver 18 for SQL Server][SQL Server]query failed", + sqlstate="42000", + ) + payload = pickle.dumps(original) + truncate = Mock(side_effect=AssertionError("Diagnostics must not be truncated again")) + monkeypatch.setattr(exceptions, "truncate_error_message", truncate) - # copy.deepcopy also uses __reduce__ - deep = copy.deepcopy(original) - assert type(deep) is cls - assert deep.driver_error == "driver msg" + for result in (pickle.loads(payload), copy.deepcopy(original)): + assert result.sqlstate == "42000" + assert result.ddbc_error == original.ddbc_error + assert result.args == original.args + truncate.assert_not_called() def test_exception_pickle_empty_ddbc_error(): @@ -632,6 +734,7 @@ def test_exception_pickle_empty_ddbc_error(): assert type(restored) is ProgrammingError assert restored.driver_error == "cursor is closed" assert restored.ddbc_error == "" + assert restored.sqlstate is None assert str(restored) == str(original) diff --git a/tests/test_typing.py b/tests/test_typing.py index d492f73a6..6cab40d19 100644 --- a/tests/test_typing.py +++ b/tests/test_typing.py @@ -65,6 +65,35 @@ def supported_calls(cursor: Cursor) -> None: _check_typing(tmp_path, str(usage)) +@pytest.mark.parametrize( + "module", ["mssql_python", "mssql_python.mssql_python", "mssql_python.exceptions"] +) +def test_exception_consumer_call_shapes(tmp_path: Path, module: str) -> None: + usage = tmp_path / "exception_consumer.py" + usage.write_text( + f"""\ +from {module} import ( + Warning, Error, InterfaceError, DatabaseError, DataError, OperationalError, + IntegrityError, InternalError, ProgrammingError, NotSupportedError, +) + +def supported_calls() -> None: + for exception_type in ( + Warning, Error, InterfaceError, DatabaseError, DataError, OperationalError, + IntegrityError, InternalError, ProgrammingError, NotSupportedError, + ): + legacy = exception_type("driver msg", "ddbc msg") + diagnostic = exception_type( + driver_error="driver msg", ddbc_error="ddbc msg", sqlstate="42000" + ) + state: str | None = diagnostic.sqlstate + legacy_state: str | None = legacy.sqlstate +""", + encoding="utf-8", + ) + _check_typing(tmp_path, str(usage)) + + def test_native_api_call_shapes(tmp_path: Path) -> None: usage = tmp_path / "native_api_usage.py" usage.write_text(