Skip to content

Make setObject scaleOrLength an advisory hint instead of an enforced limit - #3026

Merged
Mahendra Chavan (machavan) merged 9 commits into
mainfrom
users/muskgupta/setObject_parameterHint
Aug 26, 2026
Merged

Mahendra Chavan (machavan) merged 9 commits into
mainfrom
users/muskgupta/setObject_parameterHint

Conversation

@muskan124947

@muskan124947 Muskan Gupta (muskan124947) commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

Problem

#2960 introduced parameter length hints via defineParameterType() and setObject(..., scaleOrLength). As part of that change, setObject(int, Object, int, int) (and the SQLServerCallableStatement.setObject(String, Object, int, int) variants) began treating scaleOrLength as an enforced maximum length for character and binary target types, throwing R_parameterTypeValueLengthExceedsHint when the value was longer.

Per the JDBC 4.3 specification, scaleOrLength is only defined for DECIMAL/NUMERIC (as scale) and InputStream/Reader (as stream length) — it was previously ignored for string and binary types. Applications that had been passing an inaccurate or placeholder length were silently fine before, and started failing at execution time after the change.

Fix

setObject length hints are now advisory. A positive hint is used to size the parameter when it fits and quietly widened when it does not, so nothing truncates and nothing throws. A non-positive hint is not a usable declaration and is ignored outright.

scaleOrLength Behavior
<= 0 Ignored — driver default sizing (nvarchar(4000) / varchar(8000) / varbinary(8000)), same as calling setObject without a length
> 0, value fits Hint honored exactly
> 0, value longer than the hint Declared length widened to the actual value length, logged at FINER
> 0, value not String/byte[] or collation unavailable Ignored — driver default sizing

Widening happens while the type definition string is built, before prepare. SQLServerPreparedStatement.buildPreparedStrings() only re-prepares when the type definition actually changed, so the cost is at most one re-prepare and no extra round trip.

Because widening is only reachable when the actual length already exceeds a positive hint, a zero-length declaration such as varchar(0) is unreachable by construction.

defineParameterType() is unchanged and remains enforced — it is an explicit declaration by the application, not a hint, so violating it is still an error.

Also fixed: length validation units

While isolating the two paths, we found that length validation compared the value against String.length() — a character count — regardless of the declared type.

varchar(n) and char(n) are byte-counted on the server. With sendStringParametersAsUnicode=false, a multi-byte value such as "café" (4 chars, 5+ bytes) would pass validation against defineParameterType(1, VARCHAR, 4) and then be silently truncated by the server.

Values are now measured in the units the server uses for the declared type:

Declared type Unit
varchar / char bytes, via the database collation's charset
nvarchar / nchar characters
binary / varbinary bytes

This is well-defined because Parameter.setValue() re-tags character parameters as NVARCHAR when sendStringParametersAsUnicode=true. A parameter that still carries JDBCType.VARCHAR/CHAR by the time it reaches length resolution is therefore genuinely sent as varchar on the wire, so the measurement unit always matches the type being declared.

Note that this makes the enforced defineParameterType path stricter in one narrow case: a multi-byte value that previously passed validation and was then truncated by the server is now correctly rejected up front. This only affects sendStringParametersAsUnicode=false with non-ASCII data, and the previous behavior was silent data loss.

Changes

Driver

  • Parameter.java — split hint resolution into an enforced defineParameterType path and an advisory setObject path (resolveSetObjectLengthHint); added getActualValueLength for unit-correct measurement, now shared by both paths; added a FINER logger.
  • SQLServerPreparedStatement.java — rewrote the setObject(int, Object, int, int) javadoc; removed the "Breaking Behavioral Change" note.
  • SQLServerCallableStatement.java — same for setObject(String, Object, int, int) and the forceEncrypt overload.

Docs

  • docs/parameter-hints/setObject-scaleOrLength.md, parameter-hints-overview.md, define-parameter-type.md — documented advisory vs. enforced semantics, the widening rule, non-positive handling, and the measurement units.

Tests

  • ParameterLengthHintTest.java — converted 8 setObject "throws" tests to "widens"; added a SetObjectAdvisoryHintTests class covering hint-honored-when-it-fits, exact fit, widening past the short-type boundary into nvarchar(max)/varbinary(max), multi-byte VARCHAR byte measurement under SSPAU=false, non-positive hints falling back to default sizing, empty and null values, successive widening across executions, unmeasurable values, and a guard that defineParameterType still enforces. Added two tests pinning the byte-vs-character validation units.
  • CallableParameterLengthHintTest.java — converted the named-parameter setObject enforcement test to widening; added coverage for the forceEncrypt overload and non-positive hints.

No CHANGELOG.md change — the existing #2960 entry already describes the length-hint feature, and this PR restores the setObject behavior that entry originally implied.

Validation

  • mvn -P jre11 -DskipTests test-compile passes.
  • defineParameterType enforcement tests were intentionally left untouched and still assert R_parameterTypeValueLengthExceedsHint.

The parameter-hint test classes require a live SQL Server instance and have not been executed in this environment — they need a run against a configured test server before merge.

…limit

PR #2960 made the scaleOrLength argument of setObject(int, Object, int, int)
an enforced maximum length for character and binary target types, raising
R_parameterTypeValueLengthExceedsHint when the value was longer. Previously
this argument was ignored for those types, so the change broke applications
that had been passing an inaccurate length.

setObject length hints are now advisory. When the value does not fit, the
driver widens the declared parameter length to the actual value length
rather than failing, and logs the widening at FINER. A non-positive hint is
dropped instead of rejected, and a hint that cannot be measured safely falls
back to the driver's default sizing. Widening happens while the type
definition is built, before prepare, so it costs at most one re-prepare.

defineParameterType() is unchanged and remains enforced, since it is an
explicit declaration rather than a hint.

Also fixes the units used for length validation. varchar/char lengths are
byte counts on the server, but the value was compared against its Java
character count. With sendStringParametersAsUnicode=false a multi-byte value
could therefore pass validation and then be silently truncated by the
server. Character values are now measured with the database collation's
charset for varchar/char and by character count for nvarchar/nchar.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 5e77f20b-b1e3-4ced-adfa-36d94a6cdc94

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.

Pull request overview

This PR updates the Microsoft JDBC Driver for SQL Server to treat setObject(..., scaleOrLength) as an advisory length hint (widened when too small) rather than an enforced maximum, while keeping defineParameterType() as an enforced declaration. It also corrects length validation to use the server’s units (bytes vs. characters) to avoid silent truncation in VARCHAR/CHAR scenarios when sendStringParametersAsUnicode=false.

Changes:

  • Split parameter-length handling into enforced (defineParameterType) vs advisory/widening (setObject) paths, with unit-correct measurement for varchar/char (bytes via collation charset).
  • Updated Javadocs and parameter-hints documentation to describe advisory widening semantics and validation units.
  • Updated and expanded prepared/callable statement tests to assert widening behavior and byte-vs-char validation semantics.

Reviewed changes

Copilot reviewed 9 out of 9 changed files in this pull request and generated 4 comments.

Show a summary per file
File Description
src/main/java/com/microsoft/sqlserver/jdbc/Parameter.java Implements advisory widening for setObject hints and unit-correct length measurement shared with enforced validation.
src/main/java/com/microsoft/sqlserver/jdbc/SQLServerPreparedStatement.java Updates setObject(..., scaleOrLength) Javadoc to describe advisory hint/widening behavior.
src/main/java/com/microsoft/sqlserver/jdbc/SQLServerCallableStatement.java Updates callable setObject(..., decimals) Javadocs to describe advisory hint/widening behavior (incl. overload).
src/test/java/com/microsoft/sqlserver/jdbc/preparedStatement/ParameterLengthHintTest.java Converts former “throws” cases to “widens” and adds new coverage for advisory widening and byte/char validation units.
src/test/java/com/microsoft/sqlserver/jdbc/callablestatement/CallableParameterLengthHintTest.java Updates callable tests from enforced failure to widening; adds coverage for forceEncrypt overload and non-positive hints.
docs/parameter-hints/setObject-scaleOrLength.md Documents advisory widening, FINER logging, and non-positive behavior for setObject length hints.
docs/parameter-hints/parameter-hints-overview.md Clarifies enforced vs advisory semantics and the operational implications (widening and re-prepare).
docs/parameter-hints/define-parameter-type.md Documents that defineParameterType remains enforced and describes corrected measurement units.
CHANGELOG.md Updates #2960 notes to reflect advisory setObject semantics and corrected length-measurement behavior.

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

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
@muskan124947 Muskan Gupta (muskan124947) added this to the 13.6.0 milestone Aug 25, 2026
A zero or negative scaleOrLength is not a usable declared length, so it is
now ignored outright and the driver falls back to its default parameter
sizing - the same result as calling setObject() without a length. Only a
positive hint participates in sizing, where it is honored when the value
fits and widened to the actual value length when it does not.

This also removes the possibility of deriving a zero-length declaration from
an empty value, since widening is now only reachable when the actual length
already exceeds a positive hint.

Reverts the CHANGELOG entry.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 5e77f20b-b1e3-4ced-adfa-36d94a6cdc94
The length hint source was selected with a conditional expression whose
branches were the primitive int defineParameterTypeLengthHint and the
Integer returned by DTV.getScale(). Mixing a primitive and a boxed operand
makes the conditional expression itself of type int, so the Integer branch
is auto-unboxed. DTV.getScale() is null for ordinary parameters, which made
every parameterized statement throw NullPointerException.

Select the hint in separate branches so the value is assigned to an Integer
without numeric promotion, and document why a ternary must not be used here.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 5e77f20b-b1e3-4ced-adfa-36d94a6cdc94
testCallableSetObjectNonPositiveHintRejected still asserted the previous
behavior, where a zero or negative setObject length raised
R_invalidParameterLength. A non-positive length is now ignored in favour of
the driver default sizing, so the test asserts that the parameter is
declared as nvarchar(4000) or varbinary(8000) and that the value is stored
untruncated.

Removes the narrower non-positive test added earlier in this branch, since
this case source already covers both zero and negative lengths across all
six supported types.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 5e77f20b-b1e3-4ced-adfa-36d94a6cdc94
@codecov

codecov Bot commented Aug 25, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 71.05263% with 11 lines in your changes missing coverage. Please review.
✅ Project coverage is 60.45%. Comparing base (d1bdc44) to head (90ad756).
⚠️ Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
...n/java/com/microsoft/sqlserver/jdbc/Parameter.java 71.05% 7 Missing and 4 partials ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##               main    #3026      +/-   ##
============================================
+ Coverage     60.35%   60.45%   +0.10%     
- Complexity     5199     5246      +47     
============================================
  Files           153      153              
  Lines         36679    36783     +104     
  Branches       6735     6763      +28     
============================================
+ Hits          22136    22238     +102     
- Misses        10749    10753       +4     
+ Partials       3794     3792       -2     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
getApplicationSpecifiedLengthHint re-checked for a non-positive
defineParameterType length, but defineParameterType() already rejects a
non-positive maxLength before the hint is stored, so the branch and its
throwInvalidParameterLength helper could never run. Removing them drops the
duplicate validation and the dead error path.

Adds a test asserting the FINER diagnostic emitted when a setObject length
hint is widened. The message is the only signal an application gets that its
hint was too small, and it was previously documented but never verified.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 5e77f20b-b1e3-4ced-adfa-36d94a6cdc94
@machavan
Mahendra Chavan (machavan) merged commit f441986 into main Aug 26, 2026
23 checks passed
@github-project-automation github-project-automation Bot moved this from In progress to Closed/Merged PRs in MSSQL JDBC Aug 26, 2026
Mahendra Chavan (machavan) added a commit that referenced this pull request Sep 1, 2026
* Updates for 13.6.0 general availability release

- Update version from 13.5.1 to 13.6.0 in pom.xml and build.gradle
- Update license file header to reflect 13.6.0
- Remove '-preview' suffix from all sample pom.xml files (GA release)
- Update README.md with new 13.6.0.jre11 version references (no preview suffix)
- Add comprehensive CHANGELOG.md entries for 13.6.0 GA release including:
  * New features from 13.5.1 preview
  * Cross-driver connection aliases (#3011)
  * Performance callback enhancements (#3018, #3025, #3026)
  * Managed identity fixes (#3003)
  * Generated keys fix (#3002)
  * Additional bug fixes and improvements from PR #2994-#3026
  * Input validation enhancements (#3020)
  * XA DLL removal (#3017)
  * License and CI/CD improvements (#3010, #3022)

* Fix: Remove preview suffix and clean up Behavior Changes section for GA release

* Consolidate Deprecated and Testing & Quality sections into Changed and Fixed

* Correct 13.6.0 changelog to match milestone

* Update SQLJdbcVersion for 13.6.0

* Document DateTimeOffset compatibility revert

* Remove reverted Java SE Javadoc link changelog entry
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

5 participants