Skip to content

feat(mssql): add useUnicodeStrings dialect option - #18548

Merged
SippieCup merged 2 commits into
sequelize:mainfrom
OMD-123:fix/mssql-varchar-unicode-option
Oct 20, 2026
Merged

SippieCup merged 2 commits into
sequelize:mainfrom
OMD-123:fix/mssql-varchar-unicode-option

Conversation

@OMD-123

@OMD-123 OMD-123 commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Description

The mssql dialect unconditionally escaped & bound every string value as a Unicode value:

  • MsSqlDialect#escapeString prefixed every string literal with N (packages/mssql/src/dialect.ts)
  • MsSqlQuery#getSQLTypeFromJsType defaulted every string bind parameter to TYPES.NVarChar (packages/mssql/src/query.js)

Both were hardcoded, with no way to opt out. For schemas that use non-Unicode VARCHAR columns, this causes a well-known SQL Server performance problem: when a VARCHAR column is compared against an NVARCHAR literal or parameter, SQL Server must implicitly convert the column (not just the parameter) to satisfy type precedence rules. That conversion is applied per-row, which prevents the query optimizer from using an index seek on the column — it falls back to a full index/table scan.

Many production schemas (codes, IDs, statuses; anything migrated from an older system or designed for ASCII-only data) use plain VARCHAR columns, so the slowdown is silent and hard to diagnose.

Solution

Add a new useUnicodeStrings dialect option (default true, so existing behavior is preserved):

import { MsSqlDialect, Sequelize } from 'sequelize';

const sequelize = new Sequelize({
  dialect: MsSqlDialect,
  useUnicodeStrings: false,
});

When disabled:

  • dialect.escapeString('ABC-123') returns 'ABC-123' instead of N'ABC-123'
  • MsSqlQuery#getSQLTypeFromJsType binds strings as TYPES.VarChar instead of TYPES.NVarChar

The issue also asks whether the type could be derived from the model attribute's column type rather than an option. That is a much larger change (it requires the escaping/binding layer to know the target column's SQL type, which is not currently threaded through), and it would still need an escape hatch for cases where the column type is unknown. This option delivers the fix in a small, reviewable, backward-compatible change; the per-attribute derivation can be built on top of it later.

Changes

File Change
packages/mssql/src/dialect.ts Add useUnicodeStrings to MsSqlDialectOptions, register it in DIALECT_OPTION_NAMES, expose a useUnicodeStrings getter (defaults to true), and make escapeString omit the N prefix when disabled
packages/mssql/src/query.js Bind string parameters as TYPES.VarChar when useUnicodeStrings is disabled
packages/core/test/unit/dialects/mssql/query-generator.test.js Tests for the option default, the option round-trip through new Sequelize(), and escapeString output in both modes
packages/core/test/unit/dialects/mssql/query.test.js Tests that strings bind as NVarChar by default and VarChar when disabled

Tests

Run locally on Windows 11 / Node v22.23.3:

DIALECT=mssql yarn _test-unit        # 2418 passing, 0 failing
node node_modules/typescript/bin/tsc --noEmit    # core: 0 errors
node node_modules/typescript/bin/tsc --noEmit --project tsconfig.json    # mssql: 0 errors
node node_modules/eslint/bin/eslint.js <4 changed files>    # clean

I verified the new tests fail without the implementation (5 failures — 3 option round-trips plus the 2 behavior assertions), so they do exercise the new code path:

  • can be disabled through the dialect options
  • can be enabled through the dialect options
  • defaults to true
  • escapes strings as non-Unicode literals when useUnicodeStrings is disabled
  • should bind strings as VarChar when the dialect is configured to not use unicode strings

I did not run the MSSQL integration suite (test-integration-mssql) — it requires a live SQL Server instance (Docker), which is not available in this environment. I'd appreciate it if a maintainer could confirm the integration suite in CI.

I also could not verify the actual execution-plan improvement (index seek vs. scan) against a real database for the same reason. The change is behaviorally straightforward — it stops emitting the N prefix and stops binding NVarChar — but an execution-plan confirmation would strengthen the report.

Notes

  • Default is true → no behavior change for existing users.
  • No new dependencies; no public API removed.
  • Documentation (the sequelize/website repo) would need a follow-up to document the new option.

Fixes #18260

Summary by CodeRabbit

  • New Features
    • Added an MSSQL option to choose whether strings use Unicode encoding. Unicode remains enabled by default; disabling it uses non-Unicode string types and omits the Unicode prefix from escaped string literals.

The mssql dialect unconditionally escaped & bound every string value as a
Unicode value: string literals were prefixed with `N`, and bound parameters
used the `NVarChar` type. This was hardcoded, with no way to opt out.

For schemas that use non-Unicode `VARCHAR` columns this causes a well-known
SQL Server performance problem: when a `VARCHAR` column is compared against
an `NVARCHAR` literal or parameter, SQL Server must implicitly convert the
column (not just the parameter) to satisfy type precedence rules. That
conversion is applied per-row, which prevents the query optimizer from using
an index seek on the column - it falls back to a full index/table scan.

Add a new `useUnicodeStrings` dialect option (default `true`, preserving the
current behavior) so applications can generate non-Unicode string literals and
bind string parameters as `VarChar` instead:

```ts
new Sequelize({
  dialect: MsSqlDialect,
  useUnicodeStrings: false,
});
```

When disabled, `dialect.escapeString('ABC-123')` returns `'ABC-123'` instead of
`N'ABC-123'`, and `MsSqlQuery#getSQLTypeFromJsType` binds strings as
`TYPES.VarChar` instead of `TYPES.NVarChar`.

Fixes sequelize#18260
@OMD-123
OMD-123 requested a review from a team as a code owner October 9, 2026 14:01
@OMD-123
OMD-123 requested review from SippieCup and sdepold October 9, 2026 14:01
@coderabbitai

coderabbitai Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Important

Review skipped

Review was skipped as selected files did not have any reviewable changes.

⚙️ Run configuration
  • Configuration used: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: fd698312-f920-4a06-b822-a26c5d0fa0b5
📥 Commits

Reviewing files that changed from the base of the PR and between c188339 and d850036.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 34f54cd7-17ae-42c0-8b4f-a881ac53c0be
📥 Commits

Reviewing files that changed from the base of the PR and between d191d5b and c188339.

📒 Files selected for processing (4)
  • packages/core/test/unit/dialects/mssql/query-generator.test.js
  • packages/core/test/unit/dialects/mssql/query.test.js
  • packages/mssql/src/dialect.ts
  • packages/mssql/src/query.js

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.

📝 Walkthrough

The MSSQL dialect adds the useUnicodeStrings option, which defaults to true. The setting controls whether escaped strings use an N prefix and whether bound string parameters use NVarChar or VarChar.

Changes: MSSQL Unicode string configuration

Layer / File(s) Summary
Configure Unicode string literals
packages/mssql/src/dialect.ts, packages/core/test/unit/dialects/mssql/query-generator.test.js
The dialect adds the useUnicodeStrings option with a true default. When set to false, escaped string literals omit the N prefix. Tests cover the default and configured behavior.
Select bound string parameter types
packages/mssql/src/query.js, packages/core/test/unit/dialects/mssql/query.test.js
String parameters use NVarChar by default and VarChar when useUnicodeStrings is false. Tests cover both settings.

Priority: ➖ Normal

Estimated code review effort: 2 (Simple) | ~12 minutes

Change: Feature · Severity of issue fixed: Medium

Merge Risk: ⚪ Minimal · up to c1883

This adds an opt-in MSSQL setting that controls Unicode string literals and parameter types. Default behavior is unchanged, so the merge risk is minimal. Integration tests against a live database were not run.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title clearly and concisely identifies the main change: adding the MSSQL useUnicodeStrings dialect option.
Linked Issues check Passed Issue #18260 requires a supported way to avoid unconditional Unicode MSSQL strings. The PR adds the useUnicodeStrings dialect option, defaults it to true, omits the N literal prefix when false…
Out of Scope Changes check Passed The changes are limited to the MSSQL dialect option, MSSQL string escaping and binding, and tests for those behaviors. The added comments and tests support issue #18260. No unrelated product behavior …
Docstring Coverage Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check. Docstring coverage is scoped to functions touched by this diff. Analyzed 0 functions across 4…
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@SippieCup SippieCup 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.

LGTM

@SippieCup
SippieCup enabled auto-merge (squash) October 20, 2026 02:33
@SippieCup
SippieCup merged commit b1679df into sequelize:main Oct 20, 2026
papandreou added a commit to papandreou/sequelize that referenced this pull request Oct 23, 2026
* origin/main: (54 commits)
  fix: use bind parameters in the Oracle catalog queries (sequelize#18498)
  meta: update mysql docker tag to v8.4.13 (sequelize#18577)
  meta: update dependency eslint-plugin-jsdoc to v65.4.0 (sequelize#18575)
  meta: update dependency node to v24.22.1 (sequelize#18574)
  meta: update dependency @oclif/core to ^5.1.9 (sequelize#18573)
  fix(core): skip removing foreign keys in dropAllTables when dropping with cascade (sequelize#18497)
  fix(core): drop each model only once in Sequelize#drop (sequelize#18572)
  fix(postgres): drop the enum types of a model when its table is dropped (sequelize#18554)
  fix(core): avoid lodash omit in the Model constructor (sequelize#18556)
  meta(core): support async functions in expectPerDialect (sequelize#18569)
  meta: update dependency ibm_db to ^4.1.0 (sequelize#18571)
  fix(core): make rejectInvalidOptions iterate supportable options and accept undefined (sequelize#18557)
  fix(core): respect the omitNull option of calls and models, fix query generator typings (sequelize#18565)
  meta(core): convert unit/model tests to TypeScript (sequelize#18564)
  meta(core): convert unit/instance tests to TypeScript (sequelize#18563)
  meta: update sequelize AUTHORS (sequelize#18549)
  feat(mssql): add useUnicodeStrings dialect option (sequelize#18548)
  meta: retry image pulls in the database start scripts (sequelize#18340)
  meta(core): follow-ups to the isModelStatic cache from sequelize#18234 (sequelize#18559)
  meta: update dependency uuid to v14 (sequelize#18544)
  ...

# Conflicts:
#	packages/postgres/src/query-interface.js
papandreou added a commit to papandreou/sequelize that referenced this pull request Oct 23, 2026
* origin/main: (26 commits)
  fix: use bind parameters in the Oracle catalog queries (sequelize#18498)
  meta: update mysql docker tag to v8.4.13 (sequelize#18577)
  meta: update dependency eslint-plugin-jsdoc to v65.4.0 (sequelize#18575)
  meta: update dependency node to v24.22.1 (sequelize#18574)
  meta: update dependency @oclif/core to ^5.1.9 (sequelize#18573)
  fix(core): skip removing foreign keys in dropAllTables when dropping with cascade (sequelize#18497)
  fix(core): drop each model only once in Sequelize#drop (sequelize#18572)
  fix(postgres): drop the enum types of a model when its table is dropped (sequelize#18554)
  fix(core): avoid lodash omit in the Model constructor (sequelize#18556)
  meta(core): support async functions in expectPerDialect (sequelize#18569)
  meta: update dependency ibm_db to ^4.1.0 (sequelize#18571)
  fix(core): make rejectInvalidOptions iterate supportable options and accept undefined (sequelize#18557)
  fix(core): respect the omitNull option of calls and models, fix query generator typings (sequelize#18565)
  meta(core): convert unit/model tests to TypeScript (sequelize#18564)
  meta(core): convert unit/instance tests to TypeScript (sequelize#18563)
  meta: update sequelize AUTHORS (sequelize#18549)
  feat(mssql): add useUnicodeStrings dialect option (sequelize#18548)
  meta: retry image pulls in the database start scripts (sequelize#18340)
  meta(core): follow-ups to the isModelStatic cache from sequelize#18234 (sequelize#18559)
  meta: update dependency uuid to v14 (sequelize#18544)
  ...

# Conflicts:
#	packages/core/src/abstract-dialect/query-generator.js
#	packages/core/src/abstract-dialect/query-interface-typescript.ts
#	packages/core/test/unit/model/bulk-create.test.js
#	packages/core/test/unit/sql/insert.test.js
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

mssql dialect always sends string params/literals as NVARCHAR, causing implicit-conversion index scans on VARCHAR columns

2 participants