SQL Server: OPENJSON WITH ... AS JSON columns carry a json type mapping even when the server returns nvarchar(max)
Maintainers usually reply within 2 days
Nobody has claimed this yet.
Assessment
- Difficulty
- 5/5
- Estimated time
- Over a week
- Newbie friendliness
- 35/100
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
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:
TransformJsonQueryToTableassignselement.StoreTypeMapping(primitive collections) andjsonQueryExpression.JsonColumn.TypeMapping(nested owned/complex navigations) to theAS JSONcolumn infos.- The column expressions that refer to them, created via the relational
CreateSelectfrom the model's mappings, inherit the samejsonmapping.
Everything downstream that decides based on the store type is therefore misled.
Known consequences
JSON_CONTAINSover nested collections fails with error 8116 (#39626). TheContainstranslation gate (Json: { TypeMapping: SqlServerJsonTypeMapping }) accepts the column, andEF.Functions.JsonContainspasses it through as is.
#39715 works around this inSqlServerJsonPostprocessor. It works out where the document came from (OPENJSON columns, subqueries, set operations, CASE/COALESCE, etc.) and addsCAST(... AS json)unless the document is provably nativejson.JSON_VALUE ... RETURNINGis likely affected too (needs confirmation). The generator usesRETURNINGwhenjsonScalarExpression.Json.TypeMapping?.StoreType is "json". According to the generator's own comment,RETURNINGis only supported overjson, notnvarchar(max). A scalar property navigated through a nestedAS JSONcolumn on Azure SQL at compat 170 (e.g.e.Details.Tags.Any(t => t.Child.SomeInt > 0)) probably producesJSON_VALUE([t].[Child], '$.SomeInt' RETURNING int)overnvarchar(max).- The rule in
SqlServerJsonPostprocessorthat casts json comparisons tonvarchar(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_CONTAINSgate stops matching on these platforms and falls back toIN (SELECT value FROM OPENJSON(...)), as at compat 160. EF.Functions.JsonContainsonly needs a local rule at translation time: cast the document tojsonwhen its mapping isn'tjson.- Type mappings for CASE/COALESCE, subquery projections and set operations are inferred correctly, so no provenance analysis is needed.
- The generator stops using
RETURNINGover text. - The engine/compat special case in
GenerateColumnInfobecomes 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 useSqlServerStructuralJsonTypeMapping.NvarcharMaxDefault. - Where the mapping is set: the column expressions come from the relational
CreateSelect, not fromColumnInfo, so this probably needs a provider hook there. - Mixed CASE/COALESCE: if one branch is native
jsonand another is text, the inferred mapping may still bejson. 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
Starts the project's dev container in your browser, under your own GitHub account.
- No Dockerfile or Docker Compose file
- Has a pull request template
- Read the contributing guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
More from dotnet/efcore
-
customer-reported
Difficulty 2/5 1-3 hours Newbie friendliness 72/100
Maintainers usually reply within 2 days
-
GroupBy element `OrderBy(...).First()`/`MaxBy` over an owned type mapped to its own table fails to translatePossibly taken @cincuranet claimed this today. Openarea-groupby area-query
Difficulty 4/5 3-5 days Newbie friendliness 25/100
dotnet/efcore#39833 · 1 assignee ·
Maintainers usually reply within 2 days
-
SQLite: Polygon.Length translates to GLength, which returns 0Possibly taken @cincuranet claimed this today. Openarea-query area-sqlite
Difficulty 3/5 1-2 days Newbie friendliness 45/100
dotnet/efcore#39826 · 1 assignee ·
Maintainers usually reply within 2 days
-
Migration lock with LockReleaseBehavior.Transaction doesn't prevent concurrent migrations since per-migration transactionsPossibly taken @AndriySvyryd claimed this 1 day ago. Openarea-migrations
dotnet/efcore#39824 · 1 assignee ·
Maintainers usually reply within 2 days
-
Querying a TPC base type with a JSON complex property throwsPossibly taken @cincuranet claimed this 1 day ago. Openarea-query
Difficulty 4/5 3-5 days Newbie friendliness 22/100
dotnet/efcore#39814 · 1 assignee ·
Maintainers usually reply within 2 days
Similar issues
-
Difficulty 2/5 1-3 hours Newbie friendliness 77/100
Maintainers usually reply within 1 day
-
Difficulty 2/5 1-3 hours Newbie friendliness 68/100
SubtitleEdit/subtitleedit#17247 ·
Maintainers usually reply within 1 day
-
Restore test cleanup fails on Windows when restored files are read-onlyPossibly taken @JamBalaya56562 claimed this today. Open
Difficulty 2/5 1-3 hours Newbie friendliness 68/100
duplicati/duplicati#8046 · 1 comment ·
Maintainers usually reply within 1 day
-
Difficulty 2/5 1-3 hours Newbie friendliness 70/100
Maintainers usually reply within 1 day
-
Bundles Documentation
Difficulty 2/5 1-3 hours Newbie friendliness 78/100
pyrevitlabs/pyRevit#4285 ·
Maintainers usually reply within 1 day