SQL Server: OPENJSON WITH ... AS JSON columns carry a json type mapping even when the server returns nvarchar(max)

Open
#39,719 1 comment 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 2 days

Nobody has claimed this yet.

Assessment

Difficulty
5/5
Estimated time
Over a week
Newbie friendliness
35/100
Issue type
Bug
Clarity
Mostly clear
Activity status
Active
Tech stack
csharp, sql
Domain
backend, database

Research direction

Start by tracing TransformJsonQueryToTable, the relational CreateSelect path that creates column expressions, and SqlServerQuerySqlGenerator.GenerateColumnInfo. Compare the mappings for primitive collections and nested JSON navigations with the SQL emitted on Azure SQL and below compatibility level 170; then review the JSON_CONTAINS and JSON_VALUE ... RETURNING paths and their tests. Done means AS JSON columns carry mappings matching their returned SQL type, affected query baselines are updated, and the workaround in #39715 is no longer needed.

Written by the indexing model from the issue text.

Description

area-query area-sqlserver

Problem

On platforms where OPENJSON ... WITH cannot use json (Azure SQL, and SQL Server below compatibility level 170), AS JSON columns are returned as nvarchar(max). SqlServerQuerySqlGenerator.GenerateColumnInfo already accounts for this and emits nvarchar(max) in the WITH clause. However, the query tree still describes these columns with a json store type:

  • TransformJsonQueryToTable assigns element.StoreTypeMapping (primitive collections) and jsonQueryExpression.JsonColumn.TypeMapping (nested owned/complex navigations) to the AS JSON column infos.
  • The column expressions that refer to them, created via the relational CreateSelect from the model's mappings, inherit the same json mapping.

Everything downstream that decides based on the store type is therefore misled.

Known consequences

  1. JSON_CONTAINS over nested collections fails with error 8116 (#39626). The Contains translation gate (Json: { TypeMapping: SqlServerJsonTypeMapping }) accepts the column, and EF.Functions.JsonContains passes it through as is.
    #39715 works around this in SqlServerJsonPostprocessor. It works out where the document came from (OPENJSON columns, subqueries, set operations, CASE/COALESCE, etc.) and adds CAST(... AS json) unless the document is provably native json.
  2. JSON_VALUE ... RETURNING is likely affected too (needs confirmation). The generator uses RETURNING when jsonScalarExpression.Json.TypeMapping?.StoreType is "json". According to the generator's own comment, RETURNING is only supported over json, not nvarchar(max). A scalar property navigated through a nested AS JSON column on Azure SQL at compat 170 (e.g. e.Details.Tags.Any(t => t.Child.SomeInt > 0)) probably produces JSON_VALUE([t].[Child], '$.SomeInt' RETURNING int) over nvarchar(max).
  3. The rule in SqlServerJsonPostprocessor that casts json comparisons to nvarchar(max) also applies to these columns, which is unnecessary because they're already text.

Proposal

Give AS JSON columns a mapping that matches what the server actually returns: nvarchar(max) wherever the generator emits nvarchar(max). The correct store type then flows through the rest of the pipeline:

  • The Contains → JSON_CONTAINS gate stops matching on these platforms and falls back to IN (SELECT value FROM OPENJSON(...)), as at compat 160.
  • EF.Functions.JsonContains only needs a local rule at translation time: cast the document to json when its mapping isn't json.
  • Type mappings for CASE/COALESCE, subquery projections and set operations are inferred correctly, so no provenance analysis is needed.
  • The generator stops using RETURNING over text.
  • The engine/compat special case in GenerateColumnInfo becomes unnecessary. It is currently duplicated in #39715.

Once this lands, the JSON_CONTAINS handling added to SqlServerJsonPostprocessor in #39715 (including the _tables tracking and the ISqlServerSingletonOptions dependency) can be removed.

Open points

  • Primitive collections: we need an nvarchar(max) variant of the json primitive-collection mapping that keeps the element mapping, comparer and JSON reader/writer. Nested navigations can use SqlServerStructuralJsonTypeMapping.NvarcharMaxDefault.
  • Where the mapping is set: the column expressions come from the relational CreateSelect, not from ColumnInfo, so this probably needs a provider hook there.
  • Mixed CASE/COALESCE: if one branch is native json and another is text, the inferred mapping may still be json. Decide whether to normalize, or keep a cast for this case.
  • Baselines: Azure SQL and compat < 170 baselines for nested JSON queries will change. The changes are expected corrections.

Related

  • #39625 / #39706: JSON_CONTAINS search value type handling
  • #39626 / #39715: JSON_CONTAINS over nested JSON documents (current workaround)
Dominant language
C#
Stars
14.8k
Forks
3.5k
Avg merge
3d 7h
Merged PRs (30d)
182

Getting set up

Open in Codespaces

Starts the project's dev container in your browser, under your own GitHub account.

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from dotnet/efcore

All issues in dotnet/efcore

Similar issues

More C# issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.