Skip to content

Add opt-in best-fit encoding for non-Unicode SQL writes - #5158

Open
cheenamalhotra wants to merge 9 commits into
mainfrom
dev/cheena/sql-server-codepage-conversion
Open

cheenamalhotra wants to merge 9 commits into
mainfrom
dev/cheena/sql-server-codepage-conversion

Conversation

@cheenamalhotra

@cheenamalhotra cheenamalhotra commented Nov 30, 2026 •

Copy link
Copy Markdown
Member

Description

Adds an opt-in AppContext switch, Switch.Microsoft.Data.SqlClient.UseSqlServerCodePageConversion, for newer Windows best-fit mappings on char, varchar, and text writes. For example, CP1252 writes U+2012 as - instead of ?. The switch defaults to false because server-side mappings vary by host. There are no public API changes.

Following review, this PR is limited to writes. It does not change read behavior or UTF-8 writes, and it adds no sequential reader buffering.

Issues

Related: tediousjs/tedious#1859. No linked SqlClient issue.

Testing

  • dotnet test src/Microsoft.Data.SqlClient/tests/UnitTests/Microsoft.Data.SqlClient.UnitTests.csproj -f net10.0 --filter 'FullyQualifiedName~SqlServerEncodingTests|FullyQualifiedName~LocalAppContextSwitchesTest' -v q -nologo passed: 55 tests, none skipped. Includes representative exact mappings and checks across all non-surrogate BMP characters for 16 code pages. The exhaustive comparisons use .NET as the baseline, not a live SQL Server.
  • dotnet build src/Microsoft.Data.SqlClient/tests/ManualTests/Microsoft.Data.SqlClient.ManualTests.csproj -f net10.0 -v q -nologo passed. Live SQL Server and .NET Framework 4.6.2 were not validated locally for this revision.

Validation

  • Tests added or updated
  • Public API changes documented (N/A; no public API changes)
  • Ensure no breaking changes introduced

Guidelines

Please review the contribution guidelines before submitting a pull request:

cheenamalhotra and others added 2 commits November 30, 2026 11:08
Adds Switch.Microsoft.Data.SqlClient.UseSqlServerCodePageConversion (default off).
When on, char/varchar/text data is converted as SQL Server does: newer Windows
best-fit mappings on write, NUL kept after a DBCS lead byte, and SQL Server
UTF-8 replacement grouping for invalid restricted pairs.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Cover every BMP character per code page, every DBCS byte pair, and every
UTF-8 lead/trail pair, including byte-at-a-time decoding.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

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

Active issues can cause premature text-reader EOF, exceptions or out-of-slice writes during sequential decoding, and authentication failures that prevent conversion tests from running on supported Azure SQL configurations.

3 open issues
What changed in this PR

Adds opt-in SQL Server-compatible conversion for char, varchar, and text values without changing public APIs. The switch defaults to false, preserving existing behavior.

Changes:

  • Adds best-fit encoding mappings and stateful decoding for DBCS NUL preservation and UTF-8 replacement grouping.
  • Routes parser encoding selection through the switch-aware helper.
  • Adds unit and manual integration tests, switch-state support, and documentation.
File Description
src/​Microsoft.Data.SqlClient/​tests/​UnitTests/​Microsoft/​Data/​SqlClient/​SqlServerEncodingTests.cs Tests mappings, byte pairs, chunked decoding, and switch behavior.
src/​Microsoft.Data.SqlClient/​tests/​UnitTests/​Microsoft/​Data/​SqlClient/​LocalAppContextSwitchesTest.cs Verifies the switch defaults to false.
src/​Microsoft.Data.SqlClient/​tests/​ManualTests/​SQL/​GlobalizationTest/​SqlServerCodePageConversionTests.cs Adds synchronous and asynchronous database conversion tests.
src/​Microsoft.Data.SqlClient/​tests/​Common/​LocalAppContextSwitchesHelper.cs Saves, sets, and restores the switch in tests.
src/​Microsoft.Data.SqlClient/​src/​Microsoft/​Data/​SqlClient/​SqlServerEncoding.cs Implements compatible encodings and stateful decoders.
src/​Microsoft.Data.SqlClient/​src/​Microsoft/​Data/​SqlClient/​Parser/​TdsParser.cs Uses switch-aware encodings for database text conversion.
src/​Microsoft.Data.SqlClient/​src/​Microsoft/​Data/​SqlClient/​LocalAppContextSwitches.cs Defines and caches the opt-in switch.
.github/​instructions/​features.instructions.md Documents conversion behavior and compatibility constraints.

Review effort: Balanced

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings November 30, 2026 18:47

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

Unresolved sequential GetChars defects can consume subsequent column or result bytes when skipping past EOF and overwrite undecoded payload at packet boundaries, corrupting reader state or returned text.

2 open issues
3 resolved since last review

Review effort: Balanced

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings November 30, 2026 18:54

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

Stateful PLP/text decoding and buffer-ownership changes require human review because validation covers only net10.0 unit tests, leaving live SQL Server streaming and net462 behavior unverified.

No open issues 🎉

2 resolved since last review

Review effort: Balanced

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings November 30, 2026 19:50

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

Stateful decoding and PLP/sequential-reader changes still require live SQL Server validation of packet/chunk boundaries and sync/async reads, plus .NET Framework 4.6.2 coverage.

No open issues 🎉

Review effort: Balanced

@codecov

codecov Bot commented Nov 30, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 79.73568% with 46 lines in your changes missing coverage. Please review.
✅ Project coverage is 73.61%. Comparing base (b3eefc2) to head (723fbb0).
⚠️ Report is 9 commits behind head on main.

Files with missing lines Patch % Lines
.../src/Microsoft/Data/SqlClient/SqlServerEncoding.cs 83.06% 21 Missing ⚠️
...lient/src/Microsoft/Data/SqlClient/SqlParameter.cs 75.00% 9 Missing ⚠️
.../Microsoft/Data/SqlClient/Parser/TdsValueSetter.cs 20.00% 8 Missing ⚠️
...t/src/Microsoft/Data/SqlClient/Parser/TdsParser.cs 77.77% 6 Missing ⚠️
.../src/Microsoft/Data/SqlClient/SqlCommand.Reader.cs 89.47% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #5158      +/-   ##
==========================================
+ Coverage   71.17%   73.61%   +2.43%     
==========================================
  Files         315      317       +2     
  Lines       46140    71824   +25684     
==========================================
+ Hits        32841    52871   +20030     
- Misses      13299    18953    +5654     
Flag Coverage Δ
CI-SqlClient ?
sqlclient-pr 73.61% <79.73%> (?)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ 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.

@David-Engel David-Engel 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.

I like the idea of making SqlClient "more faithful" in matching SQL Server's codepage conversion behavior. But I have concerns about this PR.

It combines three fixes that have very different costs. One is cheap and self-contained. The other two only affect invalid data, but they cause most of the complexity and all of the open bugs.

What the PR does

It adds an opt-in switch that's off by default. When it's on, the driver changes three behaviors:

  • Writes: characters with a newer Windows best-fit mapping, such as U+2012 to - in CP1252, are sent as their best fit instead of ?.
  • Reads from the CJK code pages (932/936/949/950): a lead byte followed by 0x00 keeps the NUL character.
  • UTF-8 reads: invalid restricted pairs, such as E0 80, produce one U+FFFD per pair.

The PR is +2,016/−32 across 10 files. About 900 lines are the new encoding class, and most of the rest is tests. The description says there's no linked SqlClient issue; the only related link is tedious#1859.

How each part weighs up

Part Benefit Cost and risk
Best-fit mappings on write Real but small: common punctuation like figure dashes and narrow spaces is stored as a close match instead of ? Low. It's a self-contained encoder fallback with no changes to the read paths.
Keeping the NUL after a CJK lead byte Only affects malformed data, like CONVERT(varchar, 0x8100) High. Needs new character buffering in the decoders.
UTF-8 replacement grouping Only affects invalid UTF-8 stored in a _UTF8 column, and only changes how many U+FFFD characters appear Same as above

The best-fit part fixes one mismatch but creates another. The PR's own docs say: "The best-fit mappings match newer SQL Server hosts; older Windows hosts emit ?, which is why the switch is opt-in." So with the switch on, the driver matches some servers and not others. It's also unclear what Linux and Azure SQL hosts do. On maintenance, Windows code pages are effectively frozen, so the mapping tables won't need updating. The risk is that server behavior differs by host, not that the tables go stale.

The two read changes are where the cost is. They need the new decoders to hold onto decoded characters that don't fit in the caller's buffer and hand them out on later reads. That buffered state lives in the most fragile code in the driver:

  • the PLP read path in TdsParser
  • SqlDataReader.GetChars
  • SqlSequentialTextReader, both sync and async

The Copilot review still lists two open issues, both in exactly this area:

  • "Chunk-length reads overwrite buffered bytes during sequential GetChars"
  • "GetChars reads past EOF when skipping beyond buffered PLP data"

Its summary says these can consume the next column's bytes or corrupt the returned text. Three earlier issues were already fixed in later commits, which suggests the design keeps producing edge-case bugs. Test coverage is also lowest in these files: about 68% of the new lines in TdsParser.cs and 77% in SqlDataReader.cs are covered.

Issues worth raising:

  1. The default path isn't completely untouched. Most changes only apply when the switch is on, but ReadPlpAnsiChars now clears the PLP decoder when the value's total length is 0, even with the switch off. Before, it just returned 0. That's probably harmless, but it's a behavior change outside the switch. A debug assert in DecodeBytesToChars was also loosened for both paths.
  2. The exhaustive tests only check consistency with the PR's own rules, not against SQL Server. For example, the every-byte-pair test computes its expected value as "lead byte and second == 0 ? defaultChar + "\0" : dotNet.GetString(bytes)". That's the PR's rule applied on top of .NET's output. Only about 11 tests run against a real server, using a few hand-picked values. Expected results captured from SQL Server itself (for example, converting every byte pair under each collation) and checked in would actually prove the "matches SQL Server" claim.
  3. The new buffered state needs a lifecycle check. Does it survive async snapshot replay? Is it cleared on NextResult, Close and moving to the next column? This is the class of bug the open issues point to.

Alternative

  • Split the PR. Take the best-fit write change on its own (switch-gated, small, low risk) if there's actual customer demand.
  • Hold the two read changes until there's a customer issue that needs them. The benefit is limited to malformed data, and the cost is new state in the read path that already has open corruption bugs.
  • If the read changes do go ahead, the open review issues need to be fixed and test expectations generated from SQL Server.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings December 4, 2026 20:57
@cheenamalhotra cheenamalhotra changed the title Add opt-in SQL Server code page conversion Add opt-in best-fit encoding for non-Unicode SQL writes Dec 4, 2026

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

With the switch enabled, encrypted CP932 bulk copy can throw due to byte/character count confusion, and CP1252 table-valued parameters still use inconsistent character fallback.

2 open issues

Review effort: Balanced

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings December 4, 2026 21:06

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

Parameter promotion still uses character counts rather than encoded byte counts, allowing CP932 values to exceed the 8,000-byte varchar limit and produce commands SQL Server rejects.

1 open issue
2 resolved since last review

Review effort: Balanced

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings December 4, 2026 21:15

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

Changing a prepared VarChar parameter’s value can promote its payload to MAX without re-preparing its varchar(8000) declaration, causing truncation.

1 open issue
1 resolved since last review

Review effort: Balanced

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings December 4, 2026 21:24

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 CP932 byte expansion can exceed prepared varchar declarations and table-valued field limits, risking truncation or invalid payloads.

No open issues 🎉

1 resolved since last review

Review effort: Balanced

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: To triage

Development

Successfully merging this pull request may close these issues.

5 participants