Repository navigation
Make setObject scaleOrLength an advisory hint instead of an enforced limit - #3026
Conversation
…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
There was a problem hiding this comment.
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 forvarchar/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>
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
9874c04
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 Report❌ Patch coverage is
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. 🚀 New features to boost your workflow:
|
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
* 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
Problem
#2960 introduced parameter length hints via
defineParameterType()andsetObject(..., scaleOrLength). As part of that change,setObject(int, Object, int, int)(and theSQLServerCallableStatement.setObject(String, Object, int, int)variants) began treatingscaleOrLengthas an enforced maximum length for character and binary target types, throwingR_parameterTypeValueLengthExceedsHintwhen the value was longer.Per the JDBC 4.3 specification,
scaleOrLengthis only defined forDECIMAL/NUMERIC(as scale) andInputStream/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
setObjectlength 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<= 0nvarchar(4000)/varchar(8000)/varbinary(8000)), same as callingsetObjectwithout a length> 0, value fits> 0, value longer than the hintFINER> 0, value notString/byte[]or collation unavailableWidening 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)andchar(n)are byte-counted on the server. WithsendStringParametersAsUnicode=false, a multi-byte value such as"café"(4 chars, 5+ bytes) would pass validation againstdefineParameterType(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:
varchar/charnvarchar/ncharbinary/varbinaryThis is well-defined because
Parameter.setValue()re-tags character parameters asNVARCHARwhensendStringParametersAsUnicode=true. A parameter that still carriesJDBCType.VARCHAR/CHARby the time it reaches length resolution is therefore genuinely sent asvarcharon the wire, so the measurement unit always matches the type being declared.Note that this makes the enforced
defineParameterTypepath 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 affectssendStringParametersAsUnicode=falsewith non-ASCII data, and the previous behavior was silent data loss.Changes
Driver
Parameter.java— split hint resolution into an enforceddefineParameterTypepath and an advisorysetObjectpath (resolveSetObjectLengthHint); addedgetActualValueLengthfor unit-correct measurement, now shared by both paths; added aFINERlogger.SQLServerPreparedStatement.java— rewrote thesetObject(int, Object, int, int)javadoc; removed the "Breaking Behavioral Change" note.SQLServerCallableStatement.java— same forsetObject(String, Object, int, int)and theforceEncryptoverload.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 8setObject"throws" tests to "widens"; added aSetObjectAdvisoryHintTestsclass covering hint-honored-when-it-fits, exact fit, widening past the short-type boundary intonvarchar(max)/varbinary(max), multi-byte VARCHAR byte measurement underSSPAU=false, non-positive hints falling back to default sizing, empty and null values, successive widening across executions, unmeasurable values, and a guard thatdefineParameterTypestill enforces. Added two tests pinning the byte-vs-character validation units.CallableParameterLengthHintTest.java— converted the named-parametersetObjectenforcement test to widening; added coverage for theforceEncryptoverload and non-positive hints.No
CHANGELOG.mdchange — the existing #2960 entry already describes the length-hint feature, and this PR restores thesetObjectbehavior that entry originally implied.Validation
mvn -P jre11 -DskipTests test-compilepasses.defineParameterTypeenforcement tests were intentionally left untouched and still assertR_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.