Skip to content

Commit e6908ad

Browse files
committed
Fix null checks and primitive collections of JSON members over single-result subqueries
Comparing a JSON owned navigation of an entity returned by a single-result subquery to null checked the values in the document, so a document whose values are all null was treated as absent. Check the document itself over the subquery instead. Querying a primitive collection of a JSON complex type on such an entity threw while generating the table alias, since the scalar subquery's projection has no alias. Derive the alias from the projected JSON property instead.
1 parent 2083989 commit e6908ad

9 files changed

Lines changed: 259 additions & 30 deletions

File tree

‎src/EFCore.Relational/Query/RelationalQueryableMethodTranslatingExpressionVisitor.cs‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -370,7 +370,9 @@ static string GenerateTableAlias(SqlExpression sqlExpression)
370370
JsonScalarExpression jsonScalar
371371
=> jsonScalar.Path.Select(s => s.PropertyName).LastOrDefault()
372372
?? GenerateTableAlias(jsonScalar.Json),
373-
ScalarSubqueryExpression scalarSubquery => scalarSubquery.Subquery.Projection[0].Alias,
373+
// The projection of a scalar subquery binding a member of a single-result subquery (e.g. a JSON value) has no alias
374+
ScalarSubqueryExpression { Subquery.Projection: [var projection] }
375+
=> projection.Alias is { Length: > 0 } alias ? alias : GenerateTableAlias(projection.Expression),
374376

375377
_ => "collection"
376378
};

‎src/EFCore.Relational/Query/RelationalSqlTranslatingExpressionVisitor.StructuralEquality.cs‎

Lines changed: 26 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -127,18 +127,27 @@ bool TryRewriteEntityEquality([NotNullWhen(true)] out SqlExpression? result)
127127
var nonNullEntityReference = (left is SqlConstantExpression { Value: null } ? rightReference : leftReference)!;
128128
var nullComparedEntityType = (IEntityType)nonNullEntityReference.StructuralType;
129129

130-
if (nonNullEntityReference is { Parameter.ValueBufferExpression: JsonQueryExpression jsonQueryExpression })
130+
SqlExpression? jsonDocument = nonNullEntityReference switch
131131
{
132-
var jsonScalarExpression = new JsonScalarExpression(
133-
jsonQueryExpression.JsonColumn,
134-
jsonQueryExpression.Path,
135-
jsonQueryExpression.JsonColumn.Type,
136-
jsonQueryExpression.JsonColumn.TypeMapping!,
137-
jsonQueryExpression.IsNullable);
132+
{ Parameter.ValueBufferExpression: JsonQueryExpression jsonQueryExpression } => JsonDocument(jsonQueryExpression),
138133

134+
// An owned JSON entity on the row of a single-result subquery (see TryBindMember)
135+
{
136+
Subquery: { ShaperExpression: StructuralTypeShaperExpression
137+
{
138+
ValueBufferExpression: ProjectionBindingExpression projectionBinding
139+
} } subquery
140+
} when ((SelectExpression)subquery.QueryExpression).GetProjection(projectionBinding) is JsonQueryExpression
141+
=> BindOverSubquery(subquery, projection => JsonDocument((JsonQueryExpression)projection)),
142+
143+
_ => null
144+
};
145+
146+
if (jsonDocument != null)
147+
{
139148
result = nodeType == ExpressionType.Equal
140-
? _sqlExpressionFactory.IsNull(jsonScalarExpression)
141-
: _sqlExpressionFactory.IsNotNull(jsonScalarExpression);
149+
? _sqlExpressionFactory.IsNull(jsonDocument)
150+
: _sqlExpressionFactory.IsNotNull(jsonDocument);
142151

143152
return true;
144153
}
@@ -283,6 +292,14 @@ var multipleMappings when multipleMappings.SingleOrDefault(m => m.IsSplitEntityT
283292
: Expression.OrElse(l, r)));
284293

285294
return true;
295+
296+
static JsonScalarExpression JsonDocument(JsonQueryExpression jsonQueryExpression)
297+
=> new(
298+
jsonQueryExpression.JsonColumn,
299+
jsonQueryExpression.Path,
300+
jsonQueryExpression.JsonColumn.Type,
301+
jsonQueryExpression.JsonColumn.TypeMapping!,
302+
jsonQueryExpression.IsNullable);
286303
}
287304

288305
bool TryRewriteComplexTypeEquality(bool collection, [NotNullWhen(true)] out SqlExpression? result)

‎src/EFCore.Relational/Query/RelationalSqlTranslatingExpressionVisitor.cs‎

Lines changed: 25 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1339,32 +1339,39 @@ private SqlExpression BindProperty(StructuralTypeReferenceExpression typeReferen
13391339
}
13401340

13411341
case { Subquery: { } subquery }:
1342-
{
1343-
var shaper = (StructuralTypeShaperExpression)subquery.ShaperExpression;
1344-
var subSelectExpression = ((SelectExpression)subquery.QueryExpression).Clone();
1345-
1346-
var projectionBindingExpression = (ProjectionBindingExpression)shaper.ValueBufferExpression;
1347-
var innerProjection = subSelectExpression.GetProjection(projectionBindingExpression) switch
1348-
{
1349-
// An included owned navigation can be an optional dependent sharing its owner's table (see TryBindMember)
1350-
StructuralTypeProjectionExpression projection => BindProperty(projection, typeReference.StructuralType, property),
1351-
1352-
// A JSON complex type bound over a subquery (see BindComplexProperty)
1353-
JsonQueryExpression jsonQuery => jsonQuery.BindProperty(property),
1342+
return BindOverSubquery(
1343+
subquery,
1344+
projection => projection switch
1345+
{
1346+
// An included owned navigation can be an optional dependent sharing its owner's table (see TryBindMember)
1347+
StructuralTypeProjectionExpression structuralTypeProjection
1348+
=> BindProperty(structuralTypeProjection, typeReference.StructuralType, property),
13541349

1355-
_ => throw new UnreachableException()
1356-
};
1357-
subSelectExpression.ReplaceProjection([innerProjection]);
1358-
subSelectExpression.ApplyProjection();
1350+
// A JSON complex type bound over a subquery (see BindComplexProperty)
1351+
JsonQueryExpression jsonQuery => jsonQuery.BindProperty(property),
13591352

1360-
return new ScalarSubqueryExpression(subSelectExpression);
1361-
}
1353+
_ => throw new UnreachableException()
1354+
});
13621355

13631356
default:
13641357
throw new UnreachableException();
13651358
}
13661359
}
13671360

1361+
// Binds a scalar over the row of a single-result subquery: the scalar is computed from the subquery's projection of the structural
1362+
// type, and projected from a clone of the subquery.
1363+
private static ScalarSubqueryExpression BindOverSubquery(ShapedQueryExpression subquery, Func<Expression, SqlExpression> bind)
1364+
{
1365+
var shaper = (StructuralTypeShaperExpression)subquery.ShaperExpression;
1366+
var subSelectExpression = ((SelectExpression)subquery.QueryExpression).Clone();
1367+
1368+
var projection = subSelectExpression.GetProjection((ProjectionBindingExpression)shaper.ValueBufferExpression);
1369+
subSelectExpression.ReplaceProjection([bind(projection)]);
1370+
subSelectExpression.ApplyProjection();
1371+
1372+
return new ScalarSubqueryExpression(subSelectExpression);
1373+
}
1374+
13681375
private SqlExpression BindProperty(StructuralTypeProjectionExpression projection, ITypeBase structuralType, IProperty property)
13691376
{
13701377
var propertyAccess = projection.BindProperty(property);

‎test/EFCore.Cosmos.FunctionalTests/Query/Associations/ComplexProperties/ComplexPropertiesPrimitiveCollectionCosmosTest.cs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,9 @@ FROM root c
119119
""");
120120
}
121121

122+
public override Task Any_predicate_on_GroupBy_First()
123+
=> AssertTranslationFailed(base.Any_predicate_on_GroupBy_First);
124+
122125
[Fact]
123126
public virtual void Check_all_tests_overridden()
124127
=> TestHelpers.AssertAllMethodsOverridden(GetType());

‎test/EFCore.Relational.Specification.Tests/Query/OwnedEntityQueryRelationalTestBase.cs‎

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2228,6 +2228,29 @@ public virtual async Task Optional_owned_property_sharing_owner_column_on_GroupB
22282228
Assert.Equal("With details", Assert.Single(result));
22292229
}
22302230

2231+
// The JsonDetails of the "With details" product is a document whose values are all null; comparing JsonDetails to null on the
2232+
// element of a grouping must check the document itself, as it does without a subquery.
2233+
[Theory, MemberData(nameof(IsAsyncData))]
2234+
public virtual async Task Optional_owned_json_compared_to_null_on_GroupBy_element(bool async)
2235+
{
2236+
var contextFactory = await InitializeNonSharedTest<Context36296>(seed: c => c.SeedAsync());
2237+
using var context = contextFactory.CreateDbContext();
2238+
ClearLog();
2239+
2240+
var elements = context.Set<Context36296.Product>()
2241+
.GroupBy(e => e.Category)
2242+
.Select(g => g.OrderBy(e => e.Id).First(e => e.Id > 0));
2243+
2244+
var nullQuery = elements.Where(e => e.JsonDetails == null).Select(e => e.Category);
2245+
var notNullQuery = elements.Where(e => e.JsonDetails != null).Select(e => e.Category);
2246+
2247+
var nullResult = async ? await nullQuery.ToListAsync() : nullQuery.ToList();
2248+
var notNullResult = async ? await notNullQuery.ToListAsync() : notNullQuery.ToList();
2249+
2250+
Assert.Equal("Without details", Assert.Single(nullResult));
2251+
Assert.Equal("With details", Assert.Single(notNullResult));
2252+
}
2253+
22312254
// Protected so that it can be used by inheriting tests, and so that things like unused setters are not removed.
22322255
protected class Context36296(DbContextOptions options) : DbContext(options)
22332256
{
@@ -2236,12 +2259,19 @@ protected override void OnModelCreating(ModelBuilder modelBuilder)
22362259
{
22372260
b.Property(e => e.Name).HasColumnName("Name");
22382261
b.OwnsOne(e => e.Details, d => d.Property(e => e.Name).HasColumnName("Name"));
2262+
b.OwnsOne(e => e.JsonDetails, d => d.ToJson());
22392263
});
22402264

22412265
public Task SeedAsync()
22422266
{
22432267
AddRange(
2244-
new Product { Category = "With details", Name = "Shared", Details = new Details { Name = "Shared", Weight = 1 } },
2268+
new Product
2269+
{
2270+
Category = "With details",
2271+
Name = "Shared",
2272+
Details = new Details { Name = "Shared", Weight = 1 },
2273+
JsonDetails = new JsonDetails()
2274+
},
22452275
new Product { Category = "Without details", Name = "Shared" });
22462276

22472277
return SaveChangesAsync();
@@ -2253,13 +2283,19 @@ public class Product
22532283
public string Category { get; set; } = null!;
22542284
public string Name { get; set; } = null!;
22552285
public Details? Details { get; set; }
2286+
public JsonDetails? JsonDetails { get; set; }
22562287
}
22572288

22582289
public class Details
22592290
{
22602291
public string? Name { get; set; }
22612292
public int Weight { get; set; }
22622293
}
2294+
2295+
public class JsonDetails
2296+
{
2297+
public string? Note { get; set; }
2298+
}
22632299
}
22642300

22652301
#endregion

‎test/EFCore.Specification.Tests/Query/Associations/ComplexProperties/ComplexPropertiesPrimitiveCollectionTestBase.cs‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,4 +5,12 @@ namespace Microsoft.EntityFrameworkCore.Query.Associations.ComplexProperties;
55

66
public abstract class ComplexPropertiesPrimitiveCollectionTestBase<TFixture>(TFixture fixture)
77
: AssociationsPrimitiveCollectionTestBase<TFixture>(fixture)
8-
where TFixture : ComplexPropertiesFixtureBase, new();
8+
where TFixture : ComplexPropertiesFixtureBase, new()
9+
{
10+
[Fact]
11+
public virtual Task Any_predicate_on_GroupBy_First()
12+
=> AssertQuery(ss => ss.Set<RootEntity>()
13+
.GroupBy(e => e.Id % 2)
14+
.Select(g => g.OrderBy(e => e.Id).First(e => e.Id > 0))
15+
.Where(e => e.RequiredAssociate.Ints.Any(i => i == 2)));
16+
}

‎test/EFCore.SqlServer.FunctionalTests/Query/Associations/ComplexJson/ComplexJsonPrimitiveCollectionSqlServerTest.cs‎

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,85 @@ FROM OPENJSON(JSON_QUERY([r].[RequiredAssociate], '$.Ints')) WITH ([value] int '
128128
""");
129129
}
130130

131+
public override async Task Any_predicate_on_GroupBy_First()
132+
{
133+
await base.Any_predicate_on_GroupBy_First();
134+
135+
if (Fixture.UsingJsonType)
136+
{
137+
AssertSql(
138+
"""
139+
SELECT [r7].[Id], [r7].[Name], [r7].[c], [r7].[c0], [r7].[c1]
140+
FROM (
141+
SELECT [r0].[Key]
142+
FROM (
143+
SELECT [r].[Id] % 2 AS [Key]
144+
FROM [RootEntity] AS [r]
145+
) AS [r0]
146+
GROUP BY [r0].[Key]
147+
HAVING JSON_CONTAINS((
148+
SELECT TOP(1) JSON_QUERY([r3].[c1], '$.Ints')
149+
FROM (
150+
SELECT [r4].[Id], [r4].[RequiredAssociate] AS [c1], [r4].[Id] % 2 AS [Key]
151+
FROM [RootEntity] AS [r4]
152+
) AS [r3]
153+
WHERE ([r0].[Key] = [r3].[Key] OR ([r0].[Key] IS NULL AND [r3].[Key] IS NULL)) AND [r3].[Id] > 0
154+
ORDER BY [r3].[Id]), 2) = 1
155+
) AS [r5]
156+
LEFT JOIN (
157+
SELECT [r6].[Id], [r6].[Name], [r6].[c] AS [c], [r6].[c0] AS [c0], [r6].[c1] AS [c1], [r6].[Key]
158+
FROM (
159+
SELECT [r1].[Id], [r1].[Name], [r1].[c] AS [c], [r1].[c0] AS [c0], [r1].[c1] AS [c1], [r1].[Key], ROW_NUMBER() OVER(PARTITION BY [r1].[Key] ORDER BY [r1].[Id]) AS [row]
160+
FROM (
161+
SELECT [r2].[Id], [r2].[Name], [r2].[AssociateCollection] AS [c], [r2].[OptionalAssociate] AS [c0], [r2].[RequiredAssociate] AS [c1], [r2].[Id] % 2 AS [Key]
162+
FROM [RootEntity] AS [r2]
163+
) AS [r1]
164+
WHERE [r1].[Id] > 0
165+
) AS [r6]
166+
WHERE [r6].[row] <= 1
167+
) AS [r7] ON [r5].[Key] = [r7].[Key] OR ([r5].[Key] IS NULL AND [r7].[Key] IS NULL)
168+
""");
169+
}
170+
else
171+
{
172+
AssertSql(
173+
"""
174+
SELECT [r7].[Id], [r7].[Name], [r7].[c], [r7].[c0], [r7].[c1]
175+
FROM (
176+
SELECT [r0].[Key]
177+
FROM (
178+
SELECT [r].[Id] % 2 AS [Key]
179+
FROM [RootEntity] AS [r]
180+
) AS [r0]
181+
GROUP BY [r0].[Key]
182+
HAVING 2 IN (
183+
SELECT [i].[value]
184+
FROM OPENJSON((
185+
SELECT TOP(1) JSON_QUERY([r3].[c1], '$.Ints')
186+
FROM (
187+
SELECT [r4].[Id], [r4].[RequiredAssociate] AS [c1], [r4].[Id] % 2 AS [Key]
188+
FROM [RootEntity] AS [r4]
189+
) AS [r3]
190+
WHERE ([r0].[Key] = [r3].[Key] OR ([r0].[Key] IS NULL AND [r3].[Key] IS NULL)) AND [r3].[Id] > 0
191+
ORDER BY [r3].[Id])) WITH ([value] int '$') AS [i]
192+
)
193+
) AS [r5]
194+
LEFT JOIN (
195+
SELECT [r6].[Id], [r6].[Name], [r6].[c] AS [c], [r6].[c0] AS [c0], [r6].[c1] AS [c1], [r6].[Key]
196+
FROM (
197+
SELECT [r1].[Id], [r1].[Name], [r1].[c] AS [c], [r1].[c0] AS [c0], [r1].[c1] AS [c1], [r1].[Key], ROW_NUMBER() OVER(PARTITION BY [r1].[Key] ORDER BY [r1].[Id]) AS [row]
198+
FROM (
199+
SELECT [r2].[Id], [r2].[Name], [r2].[AssociateCollection] AS [c], [r2].[OptionalAssociate] AS [c0], [r2].[RequiredAssociate] AS [c1], [r2].[Id] % 2 AS [Key]
200+
FROM [RootEntity] AS [r2]
201+
) AS [r1]
202+
WHERE [r1].[Id] > 0
203+
) AS [r6]
204+
WHERE [r6].[row] <= 1
205+
) AS [r7] ON [r5].[Key] = [r7].[Key] OR ([r5].[Key] IS NULL AND [r7].[Key] IS NULL)
206+
""");
207+
}
208+
}
209+
131210
[Fact]
132211
public virtual void Check_all_tests_overridden()
133212
=> TestHelpers.AssertAllMethodsOverridden(GetType());

0 commit comments

Comments
 (0)