Skip to content

FEAT: Expose native error numbers on DB-API exceptions - #913

Merged
Jahnvi Thakkar (jahnvi480) merged 7 commits into
mainfrom
jahnvi/native-error-attributes
Nov 25, 2026
Merged

Jahnvi Thakkar (jahnvi480) merged 7 commits into
mainfrom
jahnvi/native-error-attributes

Conversation

@jahnvi480

@jahnvi480 Jahnvi Thakkar (jahnvi480) commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Work Item / Issue Reference

AB#50711

N/A


Summary

Expose optional native_error: int | None alongside SQLSTATE on DB-API exceptions for synchronous ODBC errors.

  • Capture native numbers directly from SQLGetDiagRec, paired with SQLSTATE from the same selected diagnostic record. Preserve genuine zero; use None when diagnostics are unavailable.
  • Add a small structured native connection-error transport, retaining the legacy RuntimeError fallback, exception selection, messages, args, and retry behavior. Snapshot diagnostic metadata before cleanup, including pooled statement failures.
  • Carry metadata through cursor, parameter, Arrow, and connection diagnostic paths; update public/native stubs and README guidance.
  • Preserve two-argument construction and old pickle payload loading; support keyword-only metadata and pickle/copy round trips.
  • Async Rust/TDS metadata remains unavailable (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.

  • Native Release builds with diagnostic test controls enabled and disabled: passed. Session-local build output avoids Windows MAX_PATH limitations; no binaries or virtual environments are committed.
  • 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=short against rebuilt actual-main production code - both failures reproduced.
  • Live before/after comparisons against rebuilt main: native numbers 208, 18456, 911 and 0 retained, with identical exception classes, messages and 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.

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>
Copilot AI balanced review requested due to automatic review settings November 24, 2026 06:40
@github-actions github-actions Bot added the pr-size: large Substantial code update label Nov 24, 2026
@github-actions

github-actions Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

PR Performance Report

✅ No regression detected

No 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 diagnostics

Phase 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 timings

Unix / SQL Server 2022

Database task Before After Paired change Result
Connection opening 10.411 ms 10.229 ms -1.7% no signal
SELECT queries 1.003 ms 0.997 ms -0.6% no signal
Row insertion 31.067 ms 30.779 ms -0.4% no signal
Executemany inserts 158.972 ms 158.728 ms -0.2% no signal
Fetch-all queries 120.866 ms 119.567 ms -1.1% no signal
Row-by-row fetching 5.012 ms 5.006 ms -0.1% no signal
Batched row fetching 116.634 ms 117.031 ms +0.2% no signal
Transaction commit and rollback 106.146 ms 104.768 ms -1.1% no signal
Arrow row fetching 88.661 ms 88.725 ms +0.1% no signal
100,000-row insertion 361.188 ms 383.084 ms +3.5% no signal
Row fetching in batches of 100 122.328 ms 119.558 ms -3.6% no signal
Row fetching in batches of 10,000 130.142 ms 134.772 ms +2.2% no signal
Repeated positional queries 31.865 ms 32.031 ms +0.7% no signal
Repeated named-parameter queries 32.306 ms 32.191 ms -0.7% no signal
Legacy 100,000-row insertion 274.639 ms 273.437 ms +0.6% no signal
Insertion with explicit input sizes 412.656 ms 415.216 ms +0.6% no signal
Joined aggregation queries 182.050 ms 182.673 ms +0.3% no signal
Large joined-result fetching 197.616 ms 193.826 ms -0.7% no signal
1.2-million-row fetching 3485.498 ms 3451.671 ms -1.1% no signal
Common table expression queries 5.326 ms 5.173 ms -1.1% no signal
256 KiB VARCHAR(MAX) / fetchall() 1.766 ms 1.219 ms -31.3% no signal
10,000 scalar values / fetchval() (debug disabled) 17.244 ms 16.906 ms -1.9% no signal
10,000 output-converted rows / fetchall() 19.994 ms 19.615 ms +0.3% no signal
10,000 output-converted rows / fetchmany(1000) 24.238 ms 23.232 ms -4.2% no signal
10,000 INT/NVARCHAR rows / fetchmany(1) 24.759 ms 24.740 ms -0.2% no signal
10,000 rows x 32 columns / dict(row._mapping) (warm) 31.925 ms 31.626 ms +0.6% no signal

Unix / SQL Server 2025

Database task Before After Paired change Result
Connection opening 85.077 ms 81.568 ms -4.1% no signal
SELECT queries 1.001 ms 1.002 ms +1.4% no signal
Row insertion 30.793 ms 30.830 ms +0.4% no signal
Executemany inserts 150.235 ms 148.725 ms -0.6% no signal
Fetch-all queries 118.079 ms 119.943 ms +1.6% no signal
Row-by-row fetching 4.934 ms 4.932 ms -0.1% no signal
Batched row fetching 117.193 ms 116.409 ms -0.5% no signal
Transaction commit and rollback 106.823 ms 106.140 ms -0.7% no signal
Arrow row fetching 87.150 ms 87.492 ms +0.9% no signal
100,000-row insertion 360.732 ms 352.063 ms -2.4% no signal
Row fetching in batches of 100 120.448 ms 118.973 ms -1.4% no signal
Row fetching in batches of 10,000 120.129 ms 120.794 ms +1.6% no signal
Repeated positional queries 31.725 ms 31.812 ms +0.5% no signal
Repeated named-parameter queries 32.094 ms 31.989 ms -0.4% no signal
Legacy 100,000-row insertion 271.299 ms 284.255 ms -0.5% no signal
Insertion with explicit input sizes 410.002 ms 409.468 ms -0.1% no signal
Joined aggregation queries 169.109 ms 169.671 ms -0.3% no signal
Large joined-result fetching 187.325 ms 194.508 ms +3.8% no signal
1.2-million-row fetching 3464.713 ms 3528.927 ms +1.9% no signal
Common table expression queries 5.083 ms 5.176 ms +4.0% no signal
256 KiB VARCHAR(MAX) / fetchall() 1.716 ms 2.051 ms +43.5% no signal
10,000 scalar values / fetchval() (debug disabled) 16.905 ms 16.700 ms -1.9% no signal
10,000 output-converted rows / fetchall() 19.107 ms 19.336 ms +0.9% no signal
10,000 output-converted rows / fetchmany(1000) 23.790 ms 24.272 ms +2.9% no signal
10,000 INT/NVARCHAR rows / fetchmany(1) 24.404 ms 24.410 ms +0.4% no signal
10,000 rows x 32 columns / dict(row._mapping) (warm) 30.749 ms 30.352 ms -0.9% no signal
Build and measurement details

ADO build 194866

PR head: 02f5225d889757143964287662894e6e36cdcced
Base: 599e4836d4673e95756690f6c28dbbcb48240424
Measured merge: 60f0545253f8d4947721723f5cce29c0debc6120

  • Unix / SQL Server 2022: Python 3.12.3, x86_64, SQL 16.0.4325.4; 5 paired comparisons and 1 warmup.
  • Unix / SQL Server 2025: Python 3.12.3, x86_64, SQL 17.0.5065.9; 5 paired comparisons and 1 warmup.

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 profiler-* artifacts.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 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 None for 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

Copilot AI balanced review requested due to automatic review settings November 24, 2026 07:09

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 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

@github-actions

github-actions Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

📊 Code Coverage Report

🔥 Diff Coverage

92%


🎯 Overall Coverage

85%


📈 Total Lines Covered: 12696 out of 14784
📁 Project: mssql-python


Diff Coverage

Diff: main...HEAD, staged and unstaged changes

  • mssql_python/connection.py (95.5%): Missing lines 1759
  • mssql_python/exceptions.py (100%)
  • mssql_python/helpers.py (100%)
  • mssql_python/pybind/connection/connection.cpp (88.0%): Missing lines 818,1154-1155
  • mssql_python/pybind/ddbc_bindings.cpp (81.8%): Missing lines 7070-7071
  • mssql_python/pybind/ddbc_bindings.h (100%)

Summary

  • Total: 80 lines
  • Missing: 6 lines
  • Coverage: 92%

mssql_python/connection.py

Lines 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.cpp

Lines 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.cpp

Lines 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

⚙️ Build Summary 📋 Coverage Details

View Azure DevOps Build

Browse Full Coverage Report

Copilot AI balanced review requested due to automatic review settings November 24, 2026 09:00

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 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

Comment thread README.md Resolved
Copilot AI balanced review requested due to automatic review settings November 24, 2026 12:35

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

The native exception translator and cleanup-time diagnostic transport require cross-platform validation beyond the reported Windows x64 coverage before a human approval decision.

No open issues 🎉

Review effort: Balanced

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings November 24, 2026 12:39

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 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>
Copilot AI balanced review requested due to automatic review settings November 24, 2026 17:13

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 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>
Copilot AI balanced review requested due to automatic review settings November 24, 2026 22:41

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

@jahnvi480
Jahnvi Thakkar (jahnvi480) merged commit 2cd63ac into main Nov 25, 2026
38 checks passed
Jahnvi Thakkar (jahnvi480) added a commit that referenced this pull request Nov 27, 2026
### 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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-size: large Substantial code update

3 participants