From ab8212706235f565c0961e32fa1d01695f915dce Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Thu, 22 Oct 2026 14:47:57 +0200 Subject: [PATCH] [8.0] Fix byte-array projections from JSON collections Backport #4067 using EF8 table identities and owning selects to decode base64 recordset fields without wrapper subqueries. Add owned-JSON regression coverage, including correlated references. Fixes #3566 Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: c8a1b67d-06d1-4128-b3e6-3679f8634267 --- .../Query/Internal/NpgsqlJsonPostprocessor.cs | 87 +++++++++++++++ .../NpgsqlQueryTranslationPostprocessor.cs | 2 + .../Query/JsonQueryNpgsqlTest.cs | 104 ++++++++++++++++++ 3 files changed, 193 insertions(+) create mode 100644 src/EFCore.PG/Query/Internal/NpgsqlJsonPostprocessor.cs diff --git a/src/EFCore.PG/Query/Internal/NpgsqlJsonPostprocessor.cs b/src/EFCore.PG/Query/Internal/NpgsqlJsonPostprocessor.cs new file mode 100644 index 0000000000..f1e8adc723 --- /dev/null +++ b/src/EFCore.PG/Query/Internal/NpgsqlJsonPostprocessor.cs @@ -0,0 +1,87 @@ +using Npgsql.EntityFrameworkCore.PostgreSQL.Query.Expressions.Internal; +using Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.Mapping; + +namespace Npgsql.EntityFrameworkCore.PostgreSQL.Query.Internal; + +/// +/// Applies JSON-related post-processing transformations. +/// +/// +/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to +/// the same compatibility standards as public APIs. It may be changed or removed without notice in +/// any release. You should only use it directly in your code with extreme caution and knowing that +/// doing so can result in application failures when updating to a new Entity Framework Core release. +/// +public class NpgsqlJsonPostprocessor(ISqlExpressionFactory sqlExpressionFactory) : ExpressionVisitor +{ + private readonly Dictionary _jsonRecordsets = new(ReferenceEqualityComparer.Instance); + + /// + protected override Expression VisitExtension(Expression node) + { + switch (node) + { + case ShapedQueryExpression shapedQueryExpression: + return shapedQueryExpression.Update( + Visit(shapedQueryExpression.QueryExpression), + Visit(shapedQueryExpression.ShaperExpression)); + + case SelectExpression selectExpression: + // Binary values are stored as base64 strings in JSON, but json_to_recordset/jsonb_to_recordset do not decode + // them when extracting bytea columns. Find recordsets before visiting their column references. + RegisterRecordsets(selectExpression); + var visitedSelect = (SelectExpression)base.VisitExtension(node); + // Visiting a select can replace its tables; register those too for references in the shaper. + RegisterRecordsets(visitedSelect); + return visitedSelect; + + case ColumnExpression { TypeMapping: NpgsqlByteArrayTypeMapping } column + when _jsonRecordsets.TryGetValue(column.Table, out var select): + // Extract the base64 string as text and decode it, preserving the original binary result mapping. + // Rewrite every reference, not just projections, so predicates and other server-side operations use decoded bytes. + return sqlExpressionFactory.Function( + "decode", + [ + select.CreateColumnExpression( + column.Table, column.Name, typeof(string), NpgsqlStringTypeMapping.Default, column.IsNullable), + sqlExpressionFactory.Constant("base64") + ], + nullable: true, + argumentsPropagateNullability: [true, false], + column.Type, + column.TypeMapping); + + case PgTableValuedFunctionExpression + { + Name: "json_to_recordset" or "jsonb_to_recordset", + ColumnInfos: { } columnInfos + } tvf when columnInfos.Any(c => c.TypeMapping is NpgsqlByteArrayTypeMapping): + // Change the recordset's column declarations to match the text inputs used by decode above. + return new PgTableValuedFunctionExpression( + tvf.Alias, + tvf.Name, + this.VisitAndConvert(tvf.Arguments), + columnInfos.Select( + c => c.TypeMapping is NpgsqlByteArrayTypeMapping + ? c with { TypeMapping = NpgsqlStringTypeMapping.Default } + : c).ToArray(), + tvf.WithOrdinality); + + default: + return base.VisitExtension(node); + } + } + + private void RegisterRecordsets(SelectExpression selectExpression) + { + foreach (var table in selectExpression.Tables) + { + if (table.UnwrapJoin() is PgTableValuedFunctionExpression { Name: "json_to_recordset" or "jsonb_to_recordset" }) + { + // Use table identity to distinguish query scopes and retain the owning select to create EF8 text columns, + // including correlated references. + _jsonRecordsets[table] = selectExpression; + } + } + } +} diff --git a/src/EFCore.PG/Query/Internal/NpgsqlQueryTranslationPostprocessor.cs b/src/EFCore.PG/Query/Internal/NpgsqlQueryTranslationPostprocessor.cs index 7b9a9828df..5d7b0b8d01 100644 --- a/src/EFCore.PG/Query/Internal/NpgsqlQueryTranslationPostprocessor.cs +++ b/src/EFCore.PG/Query/Internal/NpgsqlQueryTranslationPostprocessor.cs @@ -32,6 +32,8 @@ public override Expression Process(Expression query) { var result = base.Process(query); + // Structural projections require column expressions, so apply decoding after projection application. + result = new NpgsqlJsonPostprocessor(RelationalDependencies.SqlExpressionFactory).Visit(result); result = new NpgsqlUnnestPostprocessor().Visit(result); result = new NpgsqlSetOperationTypeResolutionCompensatingExpressionVisitor().Visit(result); diff --git a/test/EFCore.PG.FunctionalTests/Query/JsonQueryNpgsqlTest.cs b/test/EFCore.PG.FunctionalTests/Query/JsonQueryNpgsqlTest.cs index 8928c1fce8..0aa2a966da 100644 --- a/test/EFCore.PG.FunctionalTests/Query/JsonQueryNpgsqlTest.cs +++ b/test/EFCore.PG.FunctionalTests/Query/JsonQueryNpgsqlTest.cs @@ -3023,6 +3023,104 @@ await AssertQuery( """); } + [ConditionalTheory, MemberData(nameof(IsAsyncData))] + public virtual async Task Byte_array_in_json_collection(bool async) + { + await using var context = Fixture.CreateContext(); + await context.Database.CreateExecutionStrategy().ExecuteAsync( + async () => + { + await using var transaction = await context.Database.BeginTransactionAsync(); + + List elements = + [ + new() { Name = "A", Content = [0, 1, 127, 128, 255] }, + new() { Name = "B", Content = [] }, + new() { Name = "C", Content = null } + ]; + context.Add( + new JsonByteArrayEntity + { + Id = 1, + Json = elements + }); + await context.SaveChangesAsync(); + context.ChangeTracker.Clear(); + + var entity = async + ? await context.Set().AsNoTracking().SingleAsync() + : context.Set().AsNoTracking().Single(); + Assert.Equal(elements.Select(e => e.Content), entity.Json.Select(e => e.Content)); + + Fixture.TestSqlLoggerFactory.Clear(); + + var collectionQuery = context.Set() + .SelectMany(e => e.Json); + var projectionQuery = collectionQuery.OrderBy(e => e.Name).Select(e => e.Content); + var projected = async ? await projectionQuery.ToListAsync() : projectionQuery.ToList(); + Assert.Equal(elements.Select(e => e.Content), projected); + + var predicateQuery = collectionQuery.Where(e => e.Content == new byte[] { 0, 1, 127, 128, 255 }).Select(e => e.Name); + var matchingName = async ? await predicateQuery.SingleAsync() : predicateQuery.Single(); + Assert.Equal("A", matchingName); + + var correlatedQuery = collectionQuery + .Where(e => context.Set() + .Any(owner => owner.Id == 1 && e.Content == new byte[] { 0, 1, 127, 128, 255 })) + .Select(e => e.Name); + var correlatedName = async ? await correlatedQuery.SingleAsync() : correlatedQuery.Single(); + Assert.Equal("A", correlatedName); + + AssertSql( + """ +SELECT decode(j0."Content", 'base64') AS "Content" +FROM "JsonByteArrayEntity" AS j +JOIN LATERAL ROWS FROM (jsonb_to_recordset(j."Json") AS ( + "Content" text, + "Name" text +)) WITH ORDINALITY AS j0 ON TRUE +ORDER BY j0."Name" NULLS FIRST +""", + // + """ +SELECT j0."Name" +FROM "JsonByteArrayEntity" AS j +JOIN LATERAL ROWS FROM (jsonb_to_recordset(j."Json") AS ( + "Content" text, + "Name" text +)) WITH ORDINALITY AS j0 ON TRUE +WHERE decode(j0."Content", 'base64') = BYTEA E'\\x00017F80FF' +LIMIT 2 +""", + // + """ +SELECT j0."Name" +FROM "JsonByteArrayEntity" AS j +JOIN LATERAL ROWS FROM (jsonb_to_recordset(j."Json") AS ( + "Content" text, + "Name" text +)) WITH ORDINALITY AS j0 ON TRUE +WHERE EXISTS ( + SELECT 1 + FROM "JsonByteArrayEntity" AS j1 + WHERE j1."Id" = 1 AND decode(j0."Content", 'base64') = BYTEA E'\\x00017F80FF') +LIMIT 2 +"""); + }); + } + + public class JsonByteArrayEntity + { + public int Id { get; set; } + public List Json { get; set; } = []; + } + + public class ByteArrayJsonElement + { + public string Name { get; set; } + public byte[] Content { get; set; } + } + [ConditionalFact] public virtual void Check_all_tests_overridden() => TestHelpers.AssertAllMethodsOverridden(GetType()); @@ -3051,6 +3149,12 @@ protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext con { base.OnModelCreating(modelBuilder, context); + modelBuilder.Entity(b => + { + b.Property(e => e.Id).ValueGeneratedNever(); + b.OwnsMany(e => e.Json).ToJson(); + }); + // The following are ignored since we do not support mapping IList (as opposed to array/List) on regular properties // (since that's not supported at the ADO.NET layer). However, we do support IList inside JSON documents, since that doesn't // rely on ADO.NET support.