Repository navigation
Introduce parameter length hints via defineParameterType and setObject - #2960
Conversation
There was a problem hiding this comment.
Pull request overview
This PR introduces a new driver extension, ISQLServerPreparedStatement#defineParameterType(...), to let callers provide a max-length hint for variable-length parameter types so the driver can send tighter TDS TypeInfo (e.g., varchar(50) instead of varchar(8000)), improving SQL Server memory grant accuracy—especially for large batches.
Changes:
- Adds the
defineParameterType(int parameterIndex, int sqlType, int maxLength)API toISQLServerPreparedStatementand implements it inSQLServerPreparedStatement. - Extends
Parameter.setTypeDefinition(...)to honor a per-parameter “hint active” flag when buildingvarchar/nvarchar/varbinarytype definitions, including batch cloning support. - Adds new error resources, a design doc, and a comprehensive new test suite for the feature.
Reviewed changes
Copilot reviewed 6 out of 6 changed files in this pull request and generated 8 comments.
Show a summary per file
| File | Description |
|---|---|
| src/test/java/com/microsoft/sqlserver/jdbc/preparedStatement/DefineParameterTypeTest.java | Adds integration tests covering hint behavior across types, boundaries, batches, and error cases. |
| src/main/java/com/microsoft/sqlserver/jdbc/SQLServerResource.java | Adds new error message keys for invalid maxLength and unsupported sqlType. |
| src/main/java/com/microsoft/sqlserver/jdbc/SQLServerPreparedStatement.java | Implements defineParameterType and wires it to Parameter state. |
| src/main/java/com/microsoft/sqlserver/jdbc/Parameter.java | Adds a new flag and uses the hinted length to build TDS type definitions for supported variable-length families. |
| src/main/java/com/microsoft/sqlserver/jdbc/ISQLServerPreparedStatement.java | Adds the public API and Javadoc for defineParameterType. |
| docs/design/define-parameter-type.md | Adds a design document explaining motivation, behavior, and intended scenarios. |
9cbddc3 to
93c0365
Compare
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## main #2960 +/- ##
============================================
+ Coverage 59.26% 61.48% +2.22%
- Complexity 5042 5230 +188
============================================
Files 153 153
Lines 36354 39149 +2795
Branches 6652 7559 +907
============================================
+ Hits 21544 24070 +2526
- Misses 11050 11255 +205
- Partials 3760 3824 +64 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
81bf4b6 to
dce7c61
Compare
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
…bject breaking change - Store defineParameterTypeSqlType on Parameter and enforce type family compatibility at execution time (character vs binary). Cross-family usage (e.g. VARCHAR declared + setBytes) throws R_defineParameterTypeTypeMismatch. - Add breaking behavioral change Javadoc to setObject(int,Object,int,int) in SQLServerPreparedStatement and setObject(String,Object,int,int) overloads in SQLServerCallableStatement documenting that scaleOrLength is now enforced as a max-length constraint for string/binary types. - Update ISQLServerPreparedStatement Javadoc: sqlType now identifies type family and is enforced, not just validated. - Add 6 type mismatch tests in ParameterLengthHintTest and 3 in CallableParameterLengthHintTest. - Update parameter-hints markdown docs (README, define-parameter-type, setObject-scaleOrLength) with type family enforcement, eager validation, and breaking change documentation.
When Always Encrypted is active for a parameter, the length hint from defineParameterType/setObject(scaleOrLength) should be completely ignored because AE requires exact type info derived from the actual value. Previously, getApplicationSpecifiedLengthHint() and validateApplicationSpecifiedLength() ran unconditionally before the per-type AE branches, meaning a hint could still throw R_parameterTypeValueLengthExceedsHint even under AE. Fix: compute aeActive once at the top of setTypeDefinition() using the same condition as the per-type AE branches, and skip hint resolution entirely when AE is active (applicationLengthHint = null).
…amily check - Store defineParameterType maxLength in dedicated defineParameterTypeLengthHint field, separate from valueLength/userProvidesPrecision (which are used by DECIMAL/NUMERIC precision logic). Prevents length hint misinterpretation. - Remove redundant validateDeclaredTypeFamily() from GetTypeDefinitionOp since validateSetterTypeFamily() in setValue() already enforces the same contract at setter time. - Fix batch over-length test: move over-length setter calls inside assertThrows lambda so exceptions are caught regardless of when validation triggers.
Move documentation files that are feature/reference docs (not Copilot instruction files) to the docs/ directory: - parameter-hints/ (overview, define-parameter-type, setObject-scaleOrLength) - performance-metrics.md - state-machine-testing.md - legacy-fx-tests.md .github/instructions/ now only contains Copilot instruction files (architecture, glossary, patterns).
…rameterTypeSqlType != 0
300e44b to
4722b1f
Compare
…mporal types and stream lengths (#2998) * Fix regression from #2960: restore scale/length pass-through for CallableStatement named-parameter setObject PR #2960 replaced the unconditional pass-through of `decimals` in SQLServerCallableStatement.setObject(String, Object, int, int) with an allow-list limited to NUMERIC, DECIMAL and the newly supported character/binary length-hint types. Temporal types, InputStream/Reader stream lengths and VECTOR were silently dropped as a result. Under Always Encrypted this is fatal. Parameter.setValue only sets userProvidesScale/outScale when a non-null scale is supplied, and the AE branch of Parameter.setTypeDefinition emits `time(outScale)` only when userProvidesScale is true, otherwise falling back to `time(valueLength)`. A call such as cstmt.setObject("@t", value, java.sql.Types.TIME, 0); against an encrypted `time(0)` column therefore now declares `time(7)` and the server rejects the statement with: Operand type clash: time(7) encrypted with (...) is incompatible with time(0) encrypted with (...) Without AE the same defect is silent but still wrong, since the requested scale is discarded. Restore TIMESTAMP, TIME, DATETIMEOFFSET, InputStream/Reader and VECTOR to the allow-list on both named-parameter overloads, matching the ordinal SQLServerPreparedStatement.setObject(int, Object, int, int) implementation, and derive the VECTOR dimension count for precision the same way. The character/binary length-hint behaviour introduced by #2960 is unchanged. Add an AE regression test that exercises the named-parameter setObject overload with a temporal scale. Existing coverage missed this: PrecisionScaleTest only drives setObject(..., Types.TIME, scale) through the ordinal path, and testMixedProcedureDateScaleWithParameterName only uses the typed setTime/setTimestamp/setDateTimeOffset setters. Also correct docs/parameter-hints/setObject-scaleOrLength.md, which stated that scaleOrLength is ignored for all non character/binary types. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 2c3fe246-a318-4314-86c6-8645dbdfe681 * Added test case * Align both CallableStatement named-parameter setObject overloads Make setObject(String, Object, int, int) and its forceEncrypt sibling byte-identical apart from the forceEncrypt argument itself. The forceEncrypt overload was still missing VECTOR from the scale/length allow-list and the accompanying dimension-count derivation for precision, leaving the two APIs inconsistent. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 2c3fe246-a318-4314-86c6-8645dbdfe681 * Update CallableStatementTest.java * Add 'alwaysEncrypted' tag to CallableStatementTest --------- Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 2c3fe246-a318-4314-86c6-8645dbdfe681
…limit (#3026) * Make setObject scaleOrLength an advisory hint instead of an enforced 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 * Potential fix for pull request finding Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> * Potential fix for pull request finding Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> * Potential fix for pull request finding Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> * Potential fix for pull request finding Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> * Ignore non-positive setObject length hints and revert CHANGELOG 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 * Fix NullPointerException from auto-unboxing in length hint resolution 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 * Update stale callable test for non-positive setObject length hints 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 * Remove unreachable length validation and cover the widening diagnostic 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 --------- Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> Copilot-Session: 5e77f20b-b1e3-4ced-adfa-36d94a6cdc94
Summary
Adds a new public API,
defineParameterType(int parameterIndex, int sqlType, int maxLength), toISQLServerPreparedStatementandSQLServerPreparedStatement, and also enables the existingsetObjectoverloads that acceptscaleOrLengthto act as length hints for bounded short character and binary types.This allows the driver to send tighter TDS type definitions on the wire, such as
nvarchar(50)instead ofnvarchar(4000), which gives SQL Server much more accurate width information for memory grant calculations.The change also brings the same behavior to callable statements, centralizes hint validation in
Parameter.java, and adds comprehensive prepared and callable statement coverage.Motivation
When applications use
setString,setNString,setBytes, orsetObjectfor short character and binary values, the driver has historically declared the maximum bounded width on the wire:varchar(8000)nvarchar(4000)varbinary(8000)SQL Server uses those declared widths when estimating row size and memory grants. For small actual values, this can lead to substantial over-allocation, especially for batches and concurrent workloads.
The JDBC API does not provide a dedicated standard method for declaring bounded short string and binary parameter widths, so this change adds an explicit driver API and also honors
scaleOrLengthon supportedsetObjectpaths.API
Supported Types
sqlTypeTypes.VARCHARvarchar(N)Types.CHARvarchar(N)(CHAR routes through VARCHAR on wire)Types.NVARCHARnvarchar(N)Types.NCHARnvarchar(N)(NCHAR routes through NVARCHAR on wire)Types.VARBINARYvarbinary(N)Types.BINARYvarbinary(N)(BINARY routes through VARBINARY on wire)Behavior
defineParameterTypesets a maximum length hint for supported bounded short character and binary parameter types.setObjectoverloads that acceptscaleOrLengthnow also use that value as a length hint for the same supported types.defineParameterTypetakes precedence oversetObject(scaleOrLength).defineParameterTypeare rejected eagerly at call time withR_invalidParameterLength. Non-positive hints passed viasetObject(scaleOrLength)are rejected at execution time.sqlTypeargument todefineParameterTypeenforces type family compatibility at execution time. The setter must produce a type in the same family as the declaredsqlType(character family: VARCHAR, CHAR, NVARCHAR, NCHAR; binary family: VARBINARY, BINARY). Cross-family usage fails withR_defineParameterTypeTypeMismatch.defineParameterTypeare rejected withR_unsupportedTypeForDefineParamType.R_parameterTypeValueLengthExceedsHint.clearParameters()and across batch rows for the statement parameter they were defined on.Boundary Rules
VARCHARorCHARhint greater than8000varchar(max)NVARCHARorNCHARhint greater than4000nvarchar(max)VARBINARYorBINARYhint greater than8000varbinary(max)0R_invalidParameterLengthValidation Model
This keeps defineParameterType and setObject hint handling aligned and ensures the same rules apply across prepared and callable statement execution paths.
Files Changed
src/main/java/com/microsoft/sqlserver/jdbc/ISQLServerPreparedStatement.javadefineParameterTypeAPI and Javadocsrc/main/java/com/microsoft/sqlserver/jdbc/SQLServerPreparedStatement.javadefineParameterTypehints and wiressetObject(scaleOrLength)into the hint flowsrc/main/java/com/microsoft/sqlserver/jdbc/SQLServerCallableStatement.javasetObjectpathssrc/main/java/com/microsoft/sqlserver/jdbc/Parameter.javasrc/main/java/com/microsoft/sqlserver/jdbc/SQLServerResource.javaR_invalidParameterLength,R_unsupportedTypeForDefineParamType,R_parameterTypeValueLengthExceedsHint,R_defineParameterTypeTypeMismatch)src/test/java/com/microsoft/sqlserver/jdbc/preparedStatement/ParameterLengthHintTest.javasrc/test/java/com/microsoft/sqlserver/jdbc/callablestatement/CallableParameterLengthHintTest.java.github/instructions/parameter-hints/README.md.github/instructions/parameter-hints/define-parameter-type.mddefineParameterTypebehavior details.github/instructions/parameter-hints/setObject-scaleOrLength.mdsetObject(scaleOrLength)hint behavior and precedence documentationTest Coverage
Prepared Statement Coverage
defineParameterTypehint-to-wire-type mapping forVARCHAR,CHAR,NVARCHAR,NCHAR,VARBINARY, andBINARYsetObject(scaleOrLength)hint behavior for the same supported typesdefineParameterTypeoversetObject(scaleOrLength)varchar(max),nvarchar(max), andvarbinary(max)clearParameters()Callable Statement Coverage
setObject(scaleOrLength)hint handlingdefineParameterTypeis also presentValidation and Error Coverage
R_invalidParameterLengthR_unsupportedTypeForDefineParamTypeR_parameterTypeValueLengthExceedsHintR_defineParameterTypeTypeMismatch(e.g. VARCHAR declared + setBytes)Regression Coverage
Breaking Changes
setObject(..., scaleOrLength)now enforces length for string/binary types. ThesetObject(int, Object, int, int)method (and the callable statementsetObject(String, Object, int, int)variants) now treatsscaleOrLengthas a maximum length constraint for character and binary target types (VARCHAR, CHAR, NVARCHAR, NCHAR, VARBINARY, BINARY). Previously, per the JDBC 4.3 specification,scaleOrLengthwas only defined for DECIMAL/NUMERIC (as scale) and InputStream/Reader (as stream length) — it was ignored for string and binary types.With this change, if the actual value length exceeds the specified
scaleOrLength, execution will fail withR_parameterTypeValueLengthExceedsHint. Applications that pass arbitrary or undersizedscaleOrLengthvalues tosetObjectfor string/binary types must either:setObjectoverload that omits the length parameterThe
defineParameterTypeAPI itself is purely additive — existing behavior is unchanged when it is not called.Additionally, type family mismatches (e.g. defineParameterType(1, Types.VARCHAR, 50) followed by setBytes(1, ...)) now throw at setter time rather than at execution time. Code that catches these errors around executeUpdate() / executeBatch() must move the catch to the setter call.
Closes Why does String paramater being passed to query go as nvarchar(4000) or varchar(8000) #2913