Skip to content

FEAT: Expose SQLSTATE on DB-API exceptions - #909

Merged
Jahnvi Thakkar (jahnvi480) merged 3 commits into
mainfrom
jahnvi/sqlstate-exception-attributes
Nov 24, 2026
Merged

Jahnvi Thakkar (jahnvi480) merged 3 commits into
mainfrom
jahnvi/sqlstate-exception-attributes

Conversation

@jahnvi480

Copy link
Copy Markdown
Contributor

Work Item / Issue Reference

N/A

GitHub Issue: #581


Summary

Expose optional sqlstate metadata on DB-API exceptions so callers can classify errors without matching English messages.

  • Preserve existing two-argument construction, exception classes, messages, and args; add an optional keyword-only sqlstate argument.
  • Retain SQLSTATE for mapped and unmapped synchronous ODBC errors, including connection failures. Use None when unavailable; async Rust/TDS errors retain that default.
  • Preserve metadata through pickle/copy operations and continue loading legacy pickle payloads.
  • Update public stubs, README guidance, and focused compatibility tests.

Native SQL Server error numbers remain explicitly deferred; this PR does not complete that portion of the linked issue or change retry behavior.

Validation (project Python 3.13 development environment; native extension built successfully):

  • python -m pytest tests\test_006_exceptions.py tests\test_027_retry_policy.py tests\AsyncTest\test_003_async_exceptions.py -q --tb=short — 210 passed, 1 xfailed.
  • 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 — 6932 passed, 188 skipped, 49 deselected, 1 xfailed, 2 failed. Both failures also reproduce with baseline production modules: the password-masking logging assertion and Windows long-path test.
  • Live SQL Server before/after comparison: missing-table SQLSTATE changes from unavailable to 42S02, with identical exception class, message, and args.
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>
Copilot AI balanced review requested due to automatic review settings November 20, 2026 04:11
@github-actions github-actions Bot added the pr-size: medium Moderate update size label Nov 20, 2026
@github-actions

github-actions Bot commented Nov 20, 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.586 ms 11.112 ms +5.2% no signal
SELECT queries 1.034 ms 1.006 ms -2.1% no signal
Row insertion 30.712 ms 30.544 ms -0.5% no signal
Executemany inserts 156.756 ms 157.795 ms +0.7% no signal
Fetch-all queries 120.205 ms 122.811 ms +0.7% no signal
Row-by-row fetching 4.911 ms 4.825 ms -1.6% no signal
Batched row fetching 116.697 ms 117.923 ms +0.5% no signal
Transaction commit and rollback 106.964 ms 105.293 ms -0.9% no signal
Arrow row fetching 90.535 ms 89.699 ms +1.8% no signal
100,000-row insertion 370.711 ms 384.129 ms +6.6% no signal
Row fetching in batches of 100 120.319 ms 120.450 ms -0.2% no signal
Row fetching in batches of 10,000 143.589 ms 144.600 ms +3.9% no signal
Repeated positional queries 32.053 ms 32.620 ms +1.8% no signal
Repeated named-parameter queries 32.404 ms 32.144 ms -1.6% no signal
Legacy 100,000-row insertion 291.682 ms 285.995 ms -1.9% no signal
Insertion with explicit input sizes 415.703 ms 433.690 ms +4.8% no signal
Joined aggregation queries 181.516 ms 186.162 ms +2.6% no signal
Large joined-result fetching 196.173 ms 196.015 ms -1.2% no signal
1.2-million-row fetching 3467.013 ms 3477.285 ms +0.5% no signal
Common table expression queries 5.420 ms 5.625 ms +0.8% no signal
256 KiB VARCHAR(MAX) / fetchall() 1.690 ms 1.183 ms +2.8% no signal
10,000 scalar values / fetchval() (debug disabled) 16.749 ms 16.478 ms -0.6% no signal
10,000 output-converted rows / fetchall() 19.107 ms 19.277 ms +0.9% no signal
10,000 output-converted rows / fetchmany(1000) 23.986 ms 24.070 ms -0.5% no signal
10,000 INT/NVARCHAR rows / fetchmany(1) 24.350 ms 24.112 ms -1.0% no signal
10,000 rows x 32 columns / dict(row._mapping) (warm) 32.482 ms 36.913 ms +8.2% no signal

Unix / SQL Server 2025

Database task Before After Paired change Result
Connection opening 82.020 ms 83.195 ms +1.4% no signal
SELECT queries 1.023 ms 0.983 ms -3.9% no signal
Row insertion 31.038 ms 31.004 ms -0.6% no signal
Executemany inserts 152.124 ms 152.007 ms -0.7% no signal
Fetch-all queries 123.842 ms 123.238 ms -0.4% no signal
Row-by-row fetching 4.973 ms 5.000 ms +0.4% no signal
Batched row fetching 118.530 ms 119.102 ms +0.4% no signal
Transaction commit and rollback 107.093 ms 108.357 ms +1.4% no signal
Arrow row fetching 89.841 ms 90.316 ms +0.3% no signal
100,000-row insertion 374.935 ms 378.050 ms +0.4% no signal
Row fetching in batches of 100 123.943 ms 122.320 ms +0.6% no signal
Row fetching in batches of 10,000 131.175 ms 136.379 ms +4.7% no signal
Repeated positional queries 32.534 ms 32.087 ms -2.6% no signal
Repeated named-parameter queries 32.761 ms 32.711 ms +1.1% no signal
Legacy 100,000-row insertion 273.299 ms 270.415 ms -0.3% no signal
Insertion with explicit input sizes 428.402 ms 433.609 ms +1.5% no signal
Joined aggregation queries 166.023 ms 167.931 ms +1.0% no signal
Large joined-result fetching 192.123 ms 192.372 ms +0.7% no signal
1.2-million-row fetching 3502.373 ms 3510.195 ms +0.5% no signal
Common table expression queries 5.195 ms 5.184 ms +0.8% no signal
256 KiB VARCHAR(MAX) / fetchall() 2.058 ms 1.294 ms -23.9% no signal
10,000 scalar values / fetchval() (debug disabled) 17.083 ms 16.858 ms -2.2% no signal
10,000 output-converted rows / fetchall() 20.071 ms 19.630 ms -1.8% no signal
10,000 output-converted rows / fetchmany(1000) 24.225 ms 24.450 ms +0.7% no signal
10,000 INT/NVARCHAR rows / fetchmany(1) 24.620 ms 24.794 ms -0.8% no signal
10,000 rows x 32 columns / dict(row._mapping) (warm) 31.953 ms 32.807 ms +2.4% no signal
Build and measurement details

ADO build 194625

PR head: c4049180c36b67947a7d30c8e65067548fceaad6
Base: 9b4cd667838d3ac4ba09e18c8241ee91b0d96940
Measured merge: 390283f7ca2dafba3135ba476a918ec807b64373

  • 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.

🟢 Approval recommended

No active review issues remain for the optional SQLSTATE metadata changes.

No open issues 🎉

What changed in this PR

Adds optional SQLSTATE metadata to the driver’s DB-API exceptions, addressing the SQLSTATE portion of #581 so callers can classify errors without parsing English messages. Native SQL Server error numbers remain deferred.

Changes:

  • Preserve SQLSTATE for mapped and unmapped synchronous ODBC errors, including connection failures, without changing existing messages or args.
  • Preserve metadata through pickle and copy operations while supporting legacy pickle payloads.
  • Update public type stubs, usage guidance, and compatibility tests; async errors continue to default to None.
File Description
tests/​test_typing.py Checks legacy and SQLSTATE-aware exception call shapes across public imports.
tests/​test_006_exceptions.py Covers SQLSTATE propagation, constructor compatibility, serialization, and copying.
tests/​AsyncTest/​test_003_async_exceptions.py Verifies translated async errors default to no SQLSTATE.
README.md Documents SQLSTATE-based classification and its limitations.
mssql_python/​mssql_python.pyi Adds SQLSTATE constructor parameters and attribute types.
mssql_python/​exceptions.py Stores, propagates, and serializes optional SQLSTATE metadata.
mssql_python/​connection.py Retains SQLSTATE in the unmapped connection-error fallback.

Review effort: Balanced

@github-actions

github-actions Bot commented Nov 20, 2026 •

Copy link
Copy Markdown

📊 Code Coverage Report

🔥 Diff Coverage

100%


🎯 Overall Coverage

86%


📈 Total Lines Covered: 12188 out of 14141
📁 Project: mssql-python


Diff Coverage

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

  • mssql_python/exceptions.py (100%)

Summary

  • Total: 27 lines
  • Missing: 0 lines
  • Coverage: 100%

📋 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.ddbc_bindings.h: 64.8%
mssql_python.pybind.logger_bridge.hpp: 70.8%
mssql_python._native_fetch.py: 77.7%
mssql_python.pybind.ddbc_bindings.cpp: 81.1%
mssql_python.__init__.py: 81.2%
mssql_python.pybind.row_mapping_cache.hpp: 81.5%
mssql_python.pybind.connection.connection_pool.cpp: 82.5%
mssql_python.pybind.connection.connection.cpp: 82.9%

🔗 Quick Links

⚙️ Build Summary 📋 Coverage Details

View Azure DevOps Build

Browse Full Coverage Report

@jahnvi480
Jahnvi Thakkar (jahnvi480) marked this pull request as ready for review November 20, 2026 08:15
Copilot AI balanced review requested due to automatic review settings November 23, 2026 13: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.

🟢 Approval recommended

No active review issues are recorded for the optional SQLSTATE metadata change.

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

Copilot AI balanced review requested due to automatic review settings November 24, 2026 04:48

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.

🟢 Approval recommended

No active review issues block the change adding optional SQLSTATE metadata to DB-API exceptions.

No open issues 🎉

Review effort: Balanced

@jahnvi480
Jahnvi Thakkar (jahnvi480) merged commit ae1a6bb into main Nov 24, 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: medium Moderate update size

3 participants