Repository navigation
Add opt-in best-fit encoding for non-Unicode SQL writes - #5158
cheenamalhotra wants to merge 9 commits into
Conversation
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>
There was a problem hiding this comment.
🟡 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>
There was a problem hiding this comment.
🟡 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>
There was a problem hiding this comment.
🔵 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>
Codecov Report❌ Patch coverage is 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
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
David-Engel
left a comment
There was a problem hiding this comment.
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
0x00keeps 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.GetCharsSqlSequentialTextReader, 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:
- 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.
- 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.
- 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>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
There was a problem hiding this comment.
🟡 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>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
There was a problem hiding this comment.
🔵 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


Description
Adds an opt-in AppContext switch,
Switch.Microsoft.Data.SqlClient.UseSqlServerCodePageConversion, for newer Windows best-fit mappings onchar,varchar, andtextwrites. For example, CP1252 writes U+2012 as-instead of?. The switch defaults tofalsebecause 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 -nologopassed: 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 -nologopassed. Live SQL Server and .NET Framework 4.6.2 were not validated locally for this revision.Validation
Guidelines
Please review the contribution guidelines before submitting a pull request: