Skip to content

Introduce parameter length hints via defineParameterType and setObject - #2960

Merged
Muskan Gupta (muskan124947) merged 21 commits into
mainfrom
users/muskgupta/define-parameter-type
Jul 24, 2026
Merged

Muskan Gupta (muskan124947) merged 21 commits into
mainfrom
users/muskgupta/define-parameter-type

Conversation

@muskan124947

@muskan124947 Muskan Gupta (muskan124947) commented May 22, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Adds a new public API, defineParameterType(int parameterIndex, int sqlType, int maxLength), to ISQLServerPreparedStatement and SQLServerPreparedStatement, and also enables the existing setObject overloads that accept scaleOrLength to 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 of nvarchar(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, or setObject for 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 scaleOrLength on supported setObject paths.

API

// On ISQLServerPreparedStatement / SQLServerPreparedStatement
void defineParameterType(int parameterIndex, int sqlType, int maxLength) throws SQLServerException;

Supported Types

sqlType Wire type produced
Types.VARCHAR varchar(N)
Types.CHAR varchar(N) (CHAR routes through VARCHAR on wire)
Types.NVARCHAR nvarchar(N)
Types.NCHAR nvarchar(N) (NCHAR routes through NVARCHAR on wire)
Types.VARBINARY varbinary(N)
Types.BINARY varbinary(N) (BINARY routes through VARBINARY on wire)

Behavior

  • defineParameterType sets a maximum length hint for supported bounded short character and binary parameter types.
  • The existing setObject overloads that accept scaleOrLength now also use that value as a length hint for the same supported types.
  • If both are present, defineParameterType takes precedence over setObject(scaleOrLength).
  • Hints are applied when the driver computes the parameter type definition for execution.
  • Non-positive hints passed to defineParameterType are rejected eagerly at call time with R_invalidParameterLength. Non-positive hints passed via setObject(scaleOrLength) are rejected at execution time.
  • The sqlType argument to defineParameterType enforces type family compatibility at execution time. The setter must produce a type in the same family as the declared sqlType (character family: VARCHAR, CHAR, NVARCHAR, NCHAR; binary family: VARBINARY, BINARY). Cross-family usage fails with R_defineParameterTypeTypeMismatch.
  • When Always Encrypted is active for a parameter, hints are silently ignored — the driver uses the exact type info derived from the actual value.
  • Unsupported types passed to defineParameterType are rejected with R_unsupportedTypeForDefineParamType.
  • If the actual value length exceeds the active hint, execution fails with R_parameterTypeValueLengthExceedsHint.
  • Hints persist across clearParameters() and across batch rows for the statement parameter they were defined on.
  • Hints are scoped per parameter and do not leak across statements.
  • Existing behavior remains unchanged when no hint is provided.

Boundary Rules

Condition Wire type
VARCHAR or CHAR hint greater than 8000 varchar(max)
NVARCHAR or NCHAR hint greater than 4000 nvarchar(max)
VARBINARY or BINARY hint greater than 8000 varbinary(max)
Any supported hint less than or equal to 0 rejected with R_invalidParameterLength

Validation Model

  • Type family enforcement is performed at setter time in Parameter.setValue(). When defineParameterTypeCalled is true, validateSetterTypeFamily() ensures the setter's JDBC type family matches the declared family before any further processing.
  • Length hint resolution and value-length enforcement are centralized in Parameter.GetTypeDefinitionOp when the driver resolves the effective parameter type definition. The length hint is stored in a dedicated defineParameterTypeLengthHint field (separate from valueLength/userProvidesPrecision used by DECIMAL/NUMERIC precision logic).

This keeps defineParameterType and setObject hint handling aligned and ensures the same rules apply across prepared and callable statement execution paths.

Files Changed

File Description
src/main/java/com/microsoft/sqlserver/jdbc/ISQLServerPreparedStatement.java Adds the public defineParameterType API and Javadoc
src/main/java/com/microsoft/sqlserver/jdbc/SQLServerPreparedStatement.java Stores defineParameterType hints and wires setObject(scaleOrLength) into the hint flow
src/main/java/com/microsoft/sqlserver/jdbc/SQLServerCallableStatement.java Brings the same hint behavior to callable statement setObject paths
src/main/java/com/microsoft/sqlserver/jdbc/Parameter.java Resolves hint precedence, validates non-positive hints, and enforces value length against the active hint
src/main/java/com/microsoft/sqlserver/jdbc/SQLServerResource.java Adds error messages for validation (R_invalidParameterLength, R_unsupportedTypeForDefineParamType, R_parameterTypeValueLengthExceedsHint, R_defineParameterTypeTypeMismatch)
src/test/java/com/microsoft/sqlserver/jdbc/preparedStatement/ParameterLengthHintTest.java Comprehensive prepared statement coverage
src/test/java/com/microsoft/sqlserver/jdbc/callablestatement/CallableParameterLengthHintTest.java Callable statement coverage and parity checks
.github/instructions/parameter-hints/README.md Overview and behavior documentation for parameter hints
.github/instructions/parameter-hints/define-parameter-type.md API design and defineParameterType behavior details
.github/instructions/parameter-hints/setObject-scaleOrLength.md setObject(scaleOrLength) hint behavior and precedence documentation

Test Coverage

Prepared Statement Coverage

  • defineParameterType hint-to-wire-type mapping for VARCHAR, CHAR, NVARCHAR, NCHAR, VARBINARY, and BINARY
  • setObject(scaleOrLength) hint behavior for the same supported types
  • precedence of defineParameterType over setObject(scaleOrLength)
  • boundary promotion to varchar(max), nvarchar(max), and varbinary(max)
  • null values with and without active hints
  • empty string and empty binary payload behavior
  • per-parameter independence on multi-parameter statements
  • persistence across clearParameters()
  • persistence across batch rows
  • batch execution with mixed value sizes under the same hint

Callable Statement Coverage

  • callable statement parity for setObject(scaleOrLength) hint handling
  • wire-type selection for supported bounded string and binary types
  • precedence behavior where defineParameterType is also present
  • validation and execution behavior matching prepared statements

Validation and Error Coverage

  • non-positive hint rejection with R_invalidParameterLength
  • unsupported type rejection with R_unsupportedTypeForDefineParamType
  • value length exceeding the active hint with R_parameterTypeValueLengthExceedsHint
  • invalid parameter index handling
  • closed statement behavior
  • failure cases during batch execution when a row exceeds the active hint
  • type family mismatch rejection with R_defineParameterTypeTypeMismatch (e.g. VARCHAR declared + setBytes)
  • same-family compatibility validation (e.g. VARCHAR declared + setNString succeeds)

Regression Coverage

  • existing default behavior when no hint is provided
  • no hint leakage across separate statement instances
  • interaction with existing execution flows for prepared and callable statements
  • documentation updated to match final runtime behavior and error keys

Breaking Changes

setObject(..., scaleOrLength) now enforces length for string/binary types. The setObject(int, Object, int, int) method (and the callable statement setObject(String, Object, int, int) variants) now treats scaleOrLength as a maximum length constraint for character and binary target types (VARCHAR, CHAR, NVARCHAR, NCHAR, VARBINARY, BINARY). Previously, per the JDBC 4.3 specification, scaleOrLength was 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 with R_parameterTypeValueLengthExceedsHint. Applications that pass arbitrary or undersized scaleOrLength values to setObject for string/binary types must either:

  • Increase the value to accommodate their largest expected payload, or
  • Use a setObject overload that omits the length parameter

The defineParameterType API 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

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 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 to ISQLServerPreparedStatement and implements it in SQLServerPreparedStatement.
  • Extends Parameter.setTypeDefinition(...) to honor a per-parameter “hint active” flag when building varchar/nvarchar/varbinary type 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.
Comment thread docs/design/define-parameter-type.md Resolved
Comment thread docs/design/define-parameter-type.md Resolved
@muskan124947 Muskan Gupta (muskan124947) changed the title [WIP] Introduce define parameter type functionality May 26, 2026
@muskan124947
Muskan Gupta (muskan124947) force-pushed the users/muskgupta/define-parameter-type branch from 9cbddc3 to 93c0365 Compare May 26, 2026 07:08

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

Copilot reviewed 6 out of 6 changed files in this pull request and generated 14 comments.

Comment thread docs/design/define-parameter-type.md Resolved
Comment thread docs/design/define-parameter-type.md Resolved
@codecov

codecov Bot commented May 26, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 82.11382% with 22 lines in your changes missing coverage. Please review.
✅ Project coverage is 61.48%. Comparing base (40ad6d2) to head (4722b1f).
⚠️ Report is 4 commits behind head on main.

Files with missing lines Patch % Lines
...n/java/com/microsoft/sqlserver/jdbc/Parameter.java 84.61% 9 Missing and 5 partials ⚠️
...oft/sqlserver/jdbc/SQLServerPreparedStatement.java 77.77% 3 Missing and 3 partials ⚠️
...oft/sqlserver/jdbc/SQLServerCallableStatement.java 60.00% 0 Missing and 2 partials ⚠️
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.
📢 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.

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

Copilot reviewed 6 out of 6 changed files in this pull request and generated 5 comments.

Comment thread docs/design/define-parameter-type.md Resolved

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

Copilot reviewed 12 out of 12 changed files in this pull request and generated 7 comments.

@muskan124947
Muskan Gupta (muskan124947) force-pushed the users/muskgupta/define-parameter-type branch from 81bf4b6 to dce7c61 Compare July 14, 2026 06:37
@muskan124947 Muskan Gupta (muskan124947) added the Enhancement An enhancement to the driver. Lower priority than bugs. label Jul 14, 2026
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).
@muskan124947
Muskan Gupta (muskan124947) force-pushed the users/muskgupta/define-parameter-type branch from 300e44b to 4722b1f Compare July 23, 2026 10:12
@muskan124947
Muskan Gupta (muskan124947) merged commit 41a8a21 into main Jul 24, 2026
23 checks passed
@github-project-automation github-project-automation Bot moved this from In progress to Closed/Merged PRs in MSSQL JDBC Jul 24, 2026
Muskan Gupta (muskan124947) added a commit that referenced this pull request Jul 31, 2026
…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
Mahendra Chavan (machavan) pushed a commit that referenced this pull request Aug 26, 2026
…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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Enhancement An enhancement to the driver. Lower priority than bugs. Performance-related The desired fix involves increasing the performance of a process.

5 participants