Repository navigation
FEAT: Expose native error numbers on DB-API exceptions - #913
Conversation
Preserve paired SQLSTATE/native diagnostics through synchronous ODBC errors using structured connection transport. Retain constructor, message, retry, and serialization compatibility. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
PR Performance Report✅ No regression detectedNo consistent slowdowns detected across all 2 environments. 0 IMPROVEMENTS 0 SLOWDOWNS 2/2 ENVIRONMENTS Coverage: 2 of 2 environments completed. Advisory result; does not block merging. Performance diagnosticsPhase times are inclusive diagnostics and must not be added together. They identify where measured time changed, not why it changed. No affected phases or call-count changes were recorded. All database tasks and timingsUnix / SQL Server 2022
Unix / SQL Server 2025
Build and measurement detailsPR head:
A consistent change requires more than 20% median paired movement, at least 1 ms between the median runtimes, and at least 80% of pairs exceeding the relative threshold in the same direction. A slowdown without enough pair agreement is reported as inconsistent. The displayed change is the median of paired before-and-after ratios. It is not recalculated from the two displayed median runtimes. Both revisions use profiling-enabled builds on the same agent and database, with alternating order and discarded warmups. Results are diagnostic and do not represent production-wheel latency. Raw samples and logs are attached to the ADO run as |
There was a problem hiding this comment.
🔵 Needs a closer look
Native exception translation and pooled-cleanup diagnostics have only Windows x64 runtime coverage, while Linux/macOS validation remains pending CI.
No open issues 🎉
What changed in this PR
Extends mssql-python’s synchronous ODBC error reporting with optional native_error metadata alongside SQLSTATE, connecting native diagnostics to the public DB-API exceptions.
Changes:
- Captures paired diagnostic fields and preserves them through connection, cursor, parameter, and Arrow error paths.
- Maintains legacy exception behavior and serialization compatibility; retains genuine zero values and uses
Nonefor unavailable metadata. - Updates documentation, type stubs, and regression tests, including retry and async compatibility.
No blockers were established. Reported Windows validation was not rerun here; cross-platform validation remains for CI.
| File | Description |
|---|---|
tests/test_typing.py |
Checks public and native diagnostic types. |
tests/test_fetch_settings_cache.py |
Updates mocked fetch diagnostics. |
tests/test_027_retry_policy.py |
Checks retry counts and final diagnostic metadata. |
tests/test_006_exceptions.py |
Covers native numbers, cleanup, diagnostic pairing, and serialization. |
tests/test_004_cursor_arrow.py |
Verifies metadata on injected Arrow failures. |
tests/AsyncTest/test_003_async_exceptions.py |
Confirms async native-error metadata defaults to None. |
README.md |
Documents metadata semantics and compatibility. |
mssql_python/pybind/ddbc_bindings.h |
Defines optional native numbers and structured native errors. |
mssql_python/pybind/ddbc_bindings.cpp |
Captures, translates, and forwards native diagnostics. |
mssql_python/pybind/connection/connection.cpp |
Preserves diagnostics through connection and pool failures. |
mssql_python/mssql_python.pyi |
Adds metadata to public exception stubs. |
mssql_python/helpers.py |
Forwards native numbers from diagnostic checks. |
mssql_python/exceptions.py |
Supports metadata in construction, mapping, and serialization. |
mssql_python/connection.py |
Consumes structured errors while retaining legacy mapping and retries. |
mssql_python/_ddbc_types.pyi |
Types native diagnostic fields and the error transport. |
Review effort: Balanced
There was a problem hiding this comment.
🔵 Needs a closer look
Native exception translation and diagnostic snapshots affect connection initialization and pooled cleanup, but unavailable live native/SQL Server verification and Windows-only validation leave cross-platform coverage requiring human review.
No open issues 🎉
Review effort: Balanced
📊 Code Coverage Report
Diff CoverageDiff: main...HEAD, staged and unstaged changes
Summary
mssql_python/connection.pyLines 1755-1763 1755 # Determine appropriate exception type based on error content
1756 error_str = str(e).lower()
1757 if "invalid" in error_str or "unsupported" in error_str or "cast" in error_str:
1758 logger.error(error_msg)
! 1759 raise InterfaceError(
1760 error_msg, str(e), sqlstate=sqlstate, native_error=native_error
1761 ) from e
1762 logger.error(error_msg)
1763 raise ProgrammingError(mssql_python/pybind/connection/connection.cppLines 814-822 814 u"IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION";
815 ret = SQLExecDirect_ptr(statement,
816 reinterpretU16stringAsSqlWChar(rollbackQuery), SQL_NTS);
817 if (!SQL_SUCCEEDED(ret)) {
! 818 statementError = SQLReadError(SQL_HANDLE_STMT, statement, ret);
819 }
820 SQLRETURN freeRet = SQLFreeHandle_ptr(SQL_HANDLE_STMT, statement);
821 if (SQL_SUCCEEDED(ret) && !SQL_SUCCEEDED(freeRet)) {
822 statementError = SQLReadError(SQL_HANDLE_STMT, statement, freeRet);Lines 1150-1159 1150 const std::string errorMsg =
1151 "Failed to set connection attribute " + std::to_string(attribute);
1152 ErrorInfo errorInfo;
1153 try {
! 1154 if (odbcCalled) {
! 1155 errorInfo = SQLCheckError_Wrap(SQL_HANDLE_DBC, _conn->getDbcHandle(), ret);
1156 }
1157 } catch (const std::runtime_error& error) {
1158 LOG("Connection setAttribute diagnostics failed: %s", error.what());
1159 ThrowStdException(errorMsg);mssql_python/pybind/ddbc_bindings.cppLines 7066-7075 7066 py::register_local_exception_translator([](std::exception_ptr p) {
7067 try {
7068 if (p) std::rethrow_exception(p);
7069 } catch (const NativeDatabaseError& error) {
! 7070 // Resolve per interpreter rather than retaining a static Python handle.
! 7071 auto type = py::module_::import("ddbc_bindings").attr("NativeDatabaseError");
7072 auto instance = type(error.what());
7073 instance.attr("sqlstate") = error.diagnostic.sqlState.empty()
7074 ? py::object(py::none()) : py::object(py::str(error.diagnostic.sqlState));
7075 instance.attr("native_error") = py::cast(error.diagnostic.nativeError);📋 Files Needing Attention📉 Files with overall lowest coverage (click to expand)mssql_python.pybind.performance_counter.hpp: 0.7%
mssql_python.pybind.logger_bridge.cpp: 57.9%
mssql_python.pybind.vector_support.hpp: 59.5%
mssql_python.pybind.ddbc_bindings.h: 65.7%
mssql_python.pybind.logger_bridge.hpp: 70.8%
mssql_python._native_fetch.py: 78.1%
mssql_python.pybind.ddbc_bindings.cpp: 79.5%
mssql_python.__init__.py: 81.4%
mssql_python.pybind.row_mapping_cache.hpp: 81.5%
mssql_python.pybind.connection.connection_pool.cpp: 82.5%🔗 Quick Links
|
There was a problem hiding this comment.
🔵 Needs a closer look
Native exception translation and diagnostic preservation across initialization, pooled cleanup, and cancellation require cross-platform live-SQL validation beyond the reported Windows-only coverage, which this review environment cannot independently perform.
No open issues 🎉
Review effort: Balanced
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
There was a problem hiding this comment.
🔵 Needs a closer look
Native exception translation and diagnostic preservation affect connection and pooled cleanup paths, but supplied runtime evidence covers only Windows x64, leaving Linux/macOS behavior unvalidated.
No open issues 🎉
Review effort: Balanced
Track whether SQLSetConnectAttr ran before reading connection diagnostics. Cover a missing-catalog error followed by a lone-surrogate conversion failure on the same connection, plus preconnect conversion failures. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
There was a problem hiding this comment.
🔵 Needs a closer look
Native exception and diagnostic-lifetime changes require human confirmation of cross-platform validation because reported testing covers only Windows and this review environment cannot run SQL Server integration checks.
No open issues 🎉
Review effort: Balanced
Preserve both native-error metadata and vector-support changelog entries. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
There was a problem hiding this comment.
🔵 Needs a closer look
Native exception translation and pooled-cleanup diagnostics require cross-platform native/live-SQL validation beyond the reported Windows x64 testing, which this review could not independently perform.
No open issues 🎉
Review effort: Balanced
Sumit Sarabhai (sumitmsft)
left a comment
There was a problem hiding this comment.
Reviewed the PR for correctness, security, reliability, performance, test coverage, repository conventions, and applicable architecture and design specifications. No actionable issues were identified. The implementation is consistent with repository standards and the applicable approved design requirements.
Recommendation: Approve
### Work Item / Issue Reference <!-- IMPORTANT: Please follow the PR template guidelines below. For mssql-python maintainers: Insert your ADO Work Item ID below For external contributors: Insert Github Issue number below Only one reference is required - either GitHub issue OR ADO Work Item. --> <!-- mssql-python maintainers: ADO Work Item --> > [AB#50319](https://sqlclientdrivers.visualstudio.com/c6d89619-62de-46a0-8b46-70b92a84d85e/_workitems/edit/50319) <!-- External contributors: GitHub Issue --> ------------------------------------------------------------------- ### Summary <!-- Insert your summary of changes below. Minimum 10 characters required. --> Prepare mssql-python 1.19.0. Bump the package version in `mssql_python/__init__.py` and `setup.py`, and replace the previous release highlights in `PyPI_Description.md`. #### Enhancements - Optional connection retry policy for transient failures during connection initialization (#751). - Table-valued parameter definitions and synchronous execution through the default ODBC provider (#789). - Optional SQLSTATE and native error number attributes on DB-API exceptions (#909, #913). - Best-effort synchronous cursor cancellation with operation-scoped requests and checked recovery (#911, #915). - POSIX native binary hardening (#810). #### Bug Fixes - Lossless `executemany` inference for Unicode, Decimal, mixed-type batches, and embedded/trailing NULs (#907). - Numeric binding for auto-detected money-range Decimal batches (#752). - Restore Korean VARCHAR conversion fidelity in manylinux packages (#910). #### Release status and gates - ADO-GitHub synchronization completed into ADO `main` via [ADO PR !9120](https://sqlclientdrivers.visualstudio.com/mssql-python/_git/mssql-python/pullrequest/9120). - Ready for reviewer approval. The equivalent ADO release PR follows approval of this GitHub PR. - Do not merge this release PR until the required PyPI and Conda publication and verification gates are complete. - Release builds, publication, and release qualification remain outstanding; marking this PR ready for review does not authorize publication or merging. #### Validation - `.\.venv\Scripts\python.exe -m pre_commit run black-check --all-files --hook-stage pre-push` - passed. - `git diff --check` - passed. - Source-only checks verified matching `1.19.0` version declarations, one current "What's new" section, and the agreed description scope. - Native build and runtime pytest were not run for this version/description-only change; release qualification remains required. <!-- ### PR Title Guide > For feature requests FEAT: (short-description) > For non-feature requests like test case updates, config updates , dependency updates etc CHORE: (short-description) > For Fix requests FIX: (short-description) > For doc update requests DOC: (short-description) > For Formatting, indentation, or styling update STYLE: (short-description) > For Refactor, without any feature changes REFACTOR: (short-description) > For performance improvements PERF: (short-description) > For AI tooling, agents, skills, prompts, or AI-assisted development workflows AI: (short-description) > For release related changes, without any feature changes RELEASE: #<RELEASE_VERSION> (short-description) ### Contribution Guidelines External contributors: - Create a GitHub issue first: https://github.com/microsoft/mssql-python/issues/new - Link the GitHub issue in the "GitHub Issue" section above - Follow the PR title format and provide a meaningful summary mssql-python maintainers: - Create an ADO Work Item following internal processes - Link the ADO Work Item in the "ADO Work Item" section above - Follow the PR title format and provide a meaningful summary --> Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Work Item / Issue Reference
Summary
Expose optional
native_error: int | Nonealongside SQLSTATE on DB-API exceptions for synchronous ODBC errors.SQLGetDiagRec, paired with SQLSTATE from the same selected diagnostic record. Preserve genuine zero; useNonewhen diagnostics are unavailable.args, and retry behavior. Snapshot diagnostic metadata before cleanup, including pooled statement failures.None); this does not redesign the native exception hierarchy or add retry rules.This follow-up targets
main, incorporating the actual merged SQLSTATE implementation.Validation: Windows x64, project Python 3.13 development environment, authorized live SQL Server.
python -m pytest tests\test_006_exceptions.py tests\test_027_retry_policy.py tests\AsyncTest\test_003_async_exceptions.py tests\test_004_cursor_arrow.py tests\test_fetch_settings_cache.py -q --tb=short- 664 passed, 6 skipped, 1 deselected, with native diagnostic test controls enabled.python -m pytest tests\test_006_exceptions.py tests\test_027_retry_policy.py tests\AsyncTest\test_003_async_exceptions.py -q --tb=short- 325 passed, 3 skipped with native diagnostic test controls disabled; the skips require those controls.python -m pytest tests\test_typing.py -m typing -q --tb=short- 7 passed.python -m pre_commit run black-check --all-files --hook-stage pre-push- passed.python -m pytest -q --tb=short- 7367 passed, 178 skipped, 50 deselected, 1 xfailed, 2 failed. The failures are the existing password-masking log assertion and Windows long-path test.python -m pytest tests\test_008_logging_integration.py::TestConnectionLogging::test_connection_logs_sanitized_connection_string tests\test_015_utf8_path_handling.py::TestPathEncodingEdgeCases::test_very_long_path_component -q --tb=shortagainst rebuilt actual-main production code - both failures reproduced.args. Focused cases also cover 8134, 50001, unavailable diagnostics, unmapped SQLSTATE, selected-record pairing, legacy serialization, and retry/async compatibility.Cross-platform validation remains for CI.