Skip to content

FIX: bind executemany money-range Decimals as SQL_NUMERIC - #752

Merged
Jahnvi Thakkar (jahnvi480) merged 27 commits into
microsoft:mainfrom
vyrnsynx:fix-745-executemany-decimal-sql-numeric
Nov 26, 2026
Merged

Jahnvi Thakkar (jahnvi480) merged 27 commits into
microsoft:mainfrom
vyrnsynx:fix-745-executemany-decimal-sql-numeric

Conversation

@vyrnsynx

Copy link
Copy Markdown
Contributor

Work Item / Issue Reference

GitHub Issue: #745


Summary

executemany auto-detect still used the MONEY/SMALLMONEY-range VARCHAR shortcut after #742 fixed execute(). A money-range Decimal compared against a smaller numeric column could still overflow on that path.

This change binds auto-detected Decimal columns as SQL_NUMERIC with a batch-wide precision/scale (values still go through the existing SQL_C_CHAR string conversion). The setinputsizes DECIMAL/NUMERIC string path (GH-503) and mixed-sign VARCHAR sizing (GH-557) are left alone.

Fixes #745

executemany auto-detect skipped the money-range VARCHAR shortcut by
deriving a batch-wide NUMERIC precision/scale, matching execute() so
comparisons against smaller numeric columns no longer overflow.

setinputsizes DECIMAL/NUMERIC string binding is unchanged.

Fixes microsoft#745
Copilot AI lite review requested due to automatic review settings September 4, 2026 04:43
@azure-pipelines

Copy link
Copy Markdown
Contributor
Azure Pipelines:
There may be pipelines that require an authorized user to comment /azp run to run.

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.

🟡 Changes recommended

The new batch precision/scale path needs stricter validation and the current executemany numeric override still conflates numeric precision with string buffer sizing in a way that can produce invalid SQL Server precision (>38) for some Decimal shapes.

Once you've addressed the issues Copilot identified, you can request another Copilot review.

Pull request overview

This PR fixes the remaining executemany() auto-detection path where MONEY/SMALLMONEY-range Decimal values could still be bound as SQL_VARCHAR, causing SQL Server to overflow when comparing against smaller numeric/decimal columns. The change aligns executemany() with the already-fixed execute() behavior by binding auto-detected Decimal columns as SQL_NUMERIC using a batch-wide precision/scale, while still sending values as SQL_C_CHAR strings.

Changes:

  • Update executemany() auto-detect to bind Decimal columns as SQL_NUMERIC (skipping the MONEY-range VARCHAR shortcut) and compute a batch-wide (precision, scale).
  • Add unit/integration tests covering the GH-745 overflow regression and mixed-sign batch behavior.
  • Document the behavior change in the changelog and update explanatory test/module docs.
File summaries
File Description
mssql_python/cursor.py Adds batch-wide Decimal precision/scale derivation and applies it to executemany() auto-detect numeric binding.
tests/test_020_money_smallmoney.py Adds DB integration coverage for GH-745 (no overflow on executemany comparisons; mixed-sign batch still works).
tests/test_004_cursor.py Adds unit tests for batch precision/scale derivation and verifies executemany binds money-range Decimals as SQL_NUMERIC.
CHANGELOG.md Records GH-745 fix and clarifies setinputsizes behavior remains unchanged.
Review details

Suppressed comments (1)

mssql_python/cursor.py:2729

  • executemany’s SQL_NUMERIC/SQL_DECIMAL override reuses ParamInfo.columnSize both as the numeric precision (passed as cbColDef to SQLBindParameter) and as the max SQL_C_CHAR buffer length. Setting columnSize to max_decimal_len (which includes sign and decimal point) can push the declared numeric precision above SQL Server’s max 38 (e.g., scale-38 values format to 40 chars), causing bind failures unrelated to the actual numeric precision/scale. Consider decoupling numeric precision from string buffer sizing (e.g., compute buffer sizes from actual encoded string lengths in BindParameterArray when SQLType is NUMERIC/DECIMAL but keep cbColDef=precision<=38).
                    # Ensure columnSize also accommodates the longest string form
                    # (mixed-sign batches, GH-557).
                    if max_decimal_len > paraminfo.columnSize:
                        paraminfo.columnSize = max_decimal_len
  • Files reviewed: 4/4 changed files
  • Comments generated: 1
  • Review effort level: Lite

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread mssql_python/cursor.py Resolved

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 change that routes executemany auto-detected Decimal columns to SQL_NUMERIC (GH-745). The core approach is sound and the new _decimal_sql_precision_scale / _batch_decimal_precision_scale helpers correctly derive a batch-wide precision/scale (and fix a latent sample-only sizing gap). Verified the precision/scale math matches _get_numeric_data, and black --check passes.

One blocking issue: the retained max_decimal_len override inside the NUMERIC block sets the NUMERIC precision from a formatted string length, which can push precision past 38 and break near-max-precision money-range Decimals that previously worked. Two smaller reliability points below.

Recommendation: Request changes.

Comment thread mssql_python/cursor.py Resolved
Comment thread mssql_python/cursor.py Resolved
Comment thread mssql_python/cursor.py Resolved
…inding

Address review feedback on the executemany SQL_NUMERIC path: keep columnSize as
numeric precision (not string length), raise when batch precision exceeds 38,
force NUMERIC only when every non-NULL value is Decimal, and cover the cases
with unit tests.
@vyrnsynx

Copy link
Copy Markdown
Contributor Author

Sumit Sarabhai (@sumitmsft) Thanks for the review — addressed in the latest commit:

  1. Dropped the max_decimal_len override inside the NUMERIC branch so columnSize stays as numeric precision (not string length).
  2. Raise ValueError when batch precision exceeds 38 (no clamp).
  3. Force decimal_as_numeric only when every non-NULL value in the column is a Decimal.

Also added unit coverage for near-max precision (1E-38), batch precision >38, heterogeneous columns, and non-finite Decimals.

@vyrnsynx

Copy link
Copy Markdown
Contributor Author

@microsoft-github-policy-service agree

VyrnSynx (vyrnsynx) and others added 2 commits September 5, 2026 15:27
Resolve conflict in execute(): keep upstream native DDBCSQLExecute /
DDBCSQLExecDirect path from microsoft#736/microsoft#758; retain microsoftGH-745 executemany
SQL_NUMERIC batch precision/scale changes.
Copilot AI review requested due to automatic review settings September 8, 2026 10:14

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

It changes core executemany() parameter binding semantics in a DB driver, so a final human review is needed to confirm no subtle regressions across ODBC/SQL Server edge cases.

Review details
  • Files reviewed: 4/4 changed files
  • Comments generated: 2
  • Review effort level: Lite

Comment thread CHANGELOG.md Resolved
Comment thread mssql_python/cursor.py Resolved
@bewithgaurav

Copy link
Copy Markdown
Collaborator

/azp run

@azure-pipelines

Copy link
Copy Markdown
Contributor
Azure Pipelines:
Successfully started running 1 pipeline(s).

@bewithgaurav

Copy link
Copy Markdown
Collaborator

VyrnSynx (@vyrnsynx) - requesting you to please look into the failing tests, let us know if you need any help

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

requesting changes. the issue comparison still errors, while normal decimal batches that work on the merge base now fail before reaching sql server. I reproduced this locally, and the same regression appears in the linux and windows CI jobs.

Comment thread mssql_python/cursor.py Resolved
Keep SQLBindParameter columnSize as digit precision/scale, and size the
executemany CHAR array stride from the longest fixed-point encoding
(bufferSize) so values like Decimal("1E-38") and mixed-sign short
batches are not rejected by the array buffer.
Copilot AI review requested due to automatic review settings September 8, 2026 17:52
@vyrnsynx

Copy link
Copy Markdown
Contributor Author

Gaurav Sharma (@bewithgaurav) thanks for catching this — you were right that we were treating SQL numeric precision as the CHAR array width.

Pushed a follow-up that keeps columnSize / decimalDigits as SQL precision/scale for SQLBindParameter, and sizes the SQL_C_CHAR array stride separately (bufferSize) from the longest fixed-point encoding in the batch (with a precision+3 fallback in the binder). That covers Decimal("1E-38") and the mixed-sign short-precision case like [-12.34, 56.78].

Added/updated unit coverage for those, plus an executemany numeric(38,38) round-trip test.

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

It changes core executemany type inference and native array-binding buffer sizing in C++, which is regression-prone and warrants final human review despite strong new test coverage.

Review details

Suppressed comments (2)

mssql_python/cursor.py:2632

  • executemany() builds a full non_null_values list just to decide whether all non-NULL values are Decimal. For large batches this doubles per-column memory and does extra work; a single-pass check avoids allocating another list.
                non_null_values = [v for v in column if v is not None]
                decimal_as_numeric = bool(non_null_values) and all(
                    isinstance(v, decimal.Decimal) for v in non_null_values
                )

mssql_python/pybind/ddbc_bindings.cpp:2418

  • This bounds check is against dataWidth (array buffer stride), but the thrown message still refers to "column size". Since columnSize can represent NUMERIC precision rather than string length, the message should reference buffer width to match the check.
                            if (encodedStr.size() > dataWidth) {
                                LOG("BindParameterArray: String/binary too "
                                    "long - param_index=%d, row=%zu, size=%zu, "
                                    "max=%zu",
                                    paramIndex, i, encodedStr.size(), dataWidth);
                                ThrowStdException("Input exceeds column size at index " +
                                                  std::to_string(i));
  • Files reviewed: 6/6 changed files
  • Comments generated: 2
  • Review effort level: Lite

Comment thread mssql_python/cursor.py Resolved
Comment thread mssql_python/pybind/ddbc_bindings.cpp Resolved
@bewithgaurav

Copy link
Copy Markdown
Collaborator

/azp run

@azure-pipelines

Copy link
Copy Markdown
Contributor
Azure Pipelines:
Successfully started running 1 pipeline(s).

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

the original decimal buffer issue is fixed. requesting changes for a new regression in how conversion errors are handled, detailed inline.

Comment thread mssql_python/cursor.py Resolved
Provisional CHAR buffer sizing for setinputsizes DECIMAL/NUMERIC now
only measures already-Decimal values. Non-Decimal conversion stays in
the protected loop so MemoryError/RuntimeError become sanitized
ValueError with row/column details; bufferSize is then widened from
that converted fixed-point text.
Copilot AI review requested due to automatic review settings September 8, 2026 18:43

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.

🟡 Changes recommended

Batch precision/scale derivation currently ignores non-Decimal values even though executemany later converts non-Decimal inputs for DECIMAL/NUMERIC columns, which can yield under-sized NUMERIC metadata and runtime errors for mixed-type batches.

Once you've addressed the issues Copilot identified, you can request another Copilot review.

Review details

Suppressed comments (1)

mssql_python/cursor.py:2627

  • In executemany() auto-detect, non_null_values = [v for v in column if v is not None] allocates an extra list the size of the batch just to decide whether all non-NULLs are Decimals. For large batches this adds avoidable memory/time overhead; a single-pass scan can compute the same result without an intermediate list.
                non_null_values = [v for v in column if v is not None]
                decimal_as_numeric = bool(non_null_values) and all(
                    isinstance(v, decimal.Decimal) for v in non_null_values
                )
  • Files reviewed: 6/6 changed files
  • Comments generated: 1
  • Review effort level: Lite

Comment thread mssql_python/cursor.py Resolved
@jahnvi480

Copy link
Copy Markdown
Contributor

/azp run

@azure-pipelines

Copy link
Copy Markdown
Contributor
Azure Pipelines:
Successfully started running 1 pipeline(s).

Copilot AI lite review requested due to automatic review settings November 26, 2026 12:07
@jahnvi480

Copy link
Copy Markdown
Contributor

/azp run

@azure-pipelines

Copy link
Copy Markdown
Contributor
Azure Pipelines:
Successfully started running 1 pipeline(s).

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

Live SQL Server testing across the supported platforms is still needed to verify type coercion, precision/scale boundaries, and native buffer ownership beyond the available source and unit evidence.

No open issues 🎉

Review effort: Lite

Set the default JSON-output mode in the shared mocked cursor setup after the main branch introduced execution-time JSON state.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@jahnvi480
Jahnvi Thakkar (jahnvi480) dismissed stale reviews from Subrata (subrata-ms) and themself via 9cab68b November 26, 2026 12:36
Copilot AI lite review requested due to automatic review settings November 26, 2026 12:36
@jahnvi480

Copy link
Copy Markdown
Contributor

/azp run

@azure-pipelines

Copy link
Copy Markdown
Contributor
Azure Pipelines:
Successfully started running 1 pipeline(s).

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

Human assessment is needed because the changelog’s broad claim about preventing raw MemoryError/RuntimeError leakage is not guaranteed for Decimal subclasses, whose formatting can still raise those errors outside the protected conversion loop.

No open issues 🎉

Review effort: Lite

Copilot AI lite review requested due to automatic review settings November 26, 2026 13:37
@jahnvi480

Copy link
Copy Markdown
Contributor

/azp run

@azure-pipelines

Copy link
Copy Markdown
Contributor
Azure Pipelines:
Successfully started running 1 pipeline(s).

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 changelog claims GH-745 is fixed, but the modified-file set contains no production binder or native binding changes to provide that behavior.

No open issues 🎉

Review effort: Lite

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 complete diff and directly affected binding code, fixtures, tests, and repository contracts. No actionable issues were identified. The regression coverage is consistent with the implementation already present in the base branch.

Recommendation: Approve, with required CI checks passing before merge.

@jahnvi480
Jahnvi Thakkar (jahnvi480) merged commit f3e19e9 into microsoft:main Nov 26, 2026
34 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

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Decimal in money range still string-binds on the executemany path

6 participants