Skip to content

Commit 6a9e9fb

Browse files
authored
Fix #34849: Union in collection subquery cannot be translated (#39726)
Fixes #34849
1 parent c27a3a3 commit 6a9e9fb

9 files changed

Lines changed: 169 additions & 16 deletions

File tree

‎src/EFCore.Relational/Query/SqlExpressions/SelectExpression.cs‎

Lines changed: 24 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -2275,6 +2275,9 @@ private void ApplySetOperation(
22752275
var outerIdentifiers = select1._identifier.Count == select2._identifier.Count
22762276
? new ColumnExpression?[select1._identifier.Count]
22772277
: [];
2278+
// A distinct set operation's result is uniquely identified by all its projected columns, so they can serve as the identifier
2279+
// even when the identifiers of the two sides can't be matched (e.g. they have different counts).
2280+
var canIdentifyByProjection = distinct && select1._identifier.Count > 0 && select2._identifier.Count > 0;
22782281
var entityProjectionIdentifiers = new List<ColumnExpression>();
22792282
var entityProjectionValueComparers = new List<ValueComparer>();
22802283
var otherExpressions = new List<(SqlExpression Expression, ValueComparer Comparer)>();
@@ -2386,7 +2389,10 @@ private void ApplySetOperation(
23862389
outerIdentifiers = [];
23872390
}
23882391
}
2392+
}
23892393

2394+
if (outerIdentifiers.Length > 0 || canIdentifyByProjection)
2395+
{
23902396
// we need comparer (that we get from type mapping) for identifiers
23912397
// it may happen that one side of the set operation comes from collection parameter
23922398
// and therefore doesn't have type mapping (yet - we infer those after the translation is complete)
@@ -2421,11 +2427,10 @@ private void ApplySetOperation(
24212427
select2.IsMutable = false;
24222428

24232429
// We should apply _identifiers only when it is distinct and actual select expression had identifiers.
2424-
if (distinct
2425-
&& outerIdentifiers.Length > 0)
2430+
if (canIdentifyByProjection)
24262431
{
24272432
// If we find matching identifier in outer level then we just use them.
2428-
if (outerIdentifiers.All(e => e != null))
2433+
if (outerIdentifiers.Length > 0 && outerIdentifiers.All(e => e != null))
24292434
{
24302435
_identifier.AddRange(outerIdentifiers.Zip(select1._identifier, (c, i) => (c!, i.Comparer)));
24312436
}
@@ -2507,20 +2512,23 @@ StructuralTypeProjectionExpression ProcessStructuralType(
25072512
outerIdentifiers = [];
25082513
}
25092514
}
2510-
// If the top-level projection - not the current nested one - is a complex type and not an entity type, then add
2511-
// all its columns to the "otherExpressions" list (i.e. columns not part of a an entity primary key). This is
2512-
// the same as with a non-structural type projection.
2513-
else if (projection1.StructuralType is IComplexType)
2514-
{
2515-
var outerTypeMapping = column1.TypeMapping ?? column1.TypeMapping;
2516-
if (outerTypeMapping == null)
2517-
{
2518-
throw new InvalidOperationException(
2519-
RelationalStrings.SetOperationsRequireAtLeastOneSideWithValidTypeMapping(setOperationType));
2520-
}
2515+
}
25212516

2522-
otherExpressions.Add((outerColumn, outerTypeMapping.KeyComparer));
2517+
// If the top-level projection - not the current nested one - is a complex type and not an entity type, then add
2518+
// all its columns to the "otherExpressions" list (i.e. columns not part of a an entity primary key). This is
2519+
// the same as with a non-structural type projection. Identifier columns are included too, since this list is
2520+
// only used when the outer identifiers couldn't all be matched.
2521+
if ((outerIdentifiers.Length > 0 || canIdentifyByProjection)
2522+
&& projection1.StructuralType is IComplexType)
2523+
{
2524+
var outerTypeMapping = column1.TypeMapping ?? column2.TypeMapping;
2525+
if (outerTypeMapping == null)
2526+
{
2527+
throw new InvalidOperationException(
2528+
RelationalStrings.SetOperationsRequireAtLeastOneSideWithValidTypeMapping(setOperationType));
25232529
}
2530+
2531+
otherExpressions.Add((outerColumn, outerTypeMapping.KeyComparer));
25242532
}
25252533
}
25262534

@@ -2633,7 +2641,7 @@ JsonQueryExpression ProcessJson(JsonQueryExpression jsonQuery1, JsonQueryExpress
26332641
type, propertyExpressions, complexPropertyCache, nullable: false, discriminatorExpression,
26342642
structuralProjection1.TableMap);
26352643

2636-
if (outerIdentifiers.Length > 0 && outerProjection is { StructuralType: IEntityType entityType })
2644+
if (canIdentifyByProjection && outerProjection is { StructuralType: IEntityType entityType })
26372645
{
26382646
var primaryKey = entityType.FindPrimaryKey();
26392647

‎test/EFCore.Cosmos.FunctionalTests/Query/ComplexTypeQueryCosmosTest.cs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -184,6 +184,9 @@ public override Task Union_entity_type_containing_complex_property(bool async)
184184
=> AssertTranslationFailedWithDetails(
185185
() => base.Union_entity_type_containing_complex_property(async), CosmosStrings.NonCorrelatedSubqueriesNotSupported);
186186

187+
public override Task Union_complex_type_with_different_identifiers_in_collection_projection(bool async)
188+
=> AssertTranslationFailed(() => base.Union_complex_type_with_different_identifiers_in_collection_projection(async));
189+
187190
public override Task Union_complex_type(bool async)
188191
=> AssertTranslationFailedWithDetails(() => base.Union_complex_type(async), CosmosStrings.NonCorrelatedSubqueriesNotSupported);
189192

‎test/EFCore.Cosmos.FunctionalTests/Query/ComplexTypeToJsonPropertyQueryCosmosTest.cs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -186,6 +186,9 @@ public override Task Union_entity_type_containing_complex_property(bool async)
186186
=> AssertTranslationFailedWithDetails(
187187
() => base.Union_entity_type_containing_complex_property(async), CosmosStrings.NonCorrelatedSubqueriesNotSupported);
188188

189+
public override Task Union_complex_type_with_different_identifiers_in_collection_projection(bool async)
190+
=> AssertTranslationFailed(() => base.Union_complex_type_with_different_identifiers_in_collection_projection(async));
191+
189192
public override Task Union_complex_type(bool async)
190193
=> AssertTranslationFailedWithDetails(() => base.Union_complex_type(async), CosmosStrings.NonCorrelatedSubqueriesNotSupported);
191194

‎test/EFCore.Specification.Tests/Query/ComplexTypeQueryTestBase.cs‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -252,6 +252,25 @@ public virtual Task Union_two_different_complex_type(bool async)
252252
async,
253253
ss => ss.Set<Customer>().Select(c => c.ShippingAddress).Union(ss.Set<Customer>().Select(c => c.BillingAddress)));
254254

255+
[Theory, MemberData(nameof(IsAsyncData))]
256+
public virtual Task Union_complex_type_with_different_identifiers_in_collection_projection(bool async)
257+
=> AssertQuery(
258+
async,
259+
ss => ss.Set<CustomerGroup>().Select(g => new
260+
{
261+
g.Id,
262+
// The Distinct side is identified by all its columns, the other one by the customer key.
263+
Addresses = ss.Set<Customer>().Select(c => c.ShippingAddress).Distinct()
264+
.Union(ss.Set<Customer>().Where(c => c.Id > 1).Select(c => c.ShippingAddress))
265+
.ToList()
266+
}),
267+
elementSorter: e => e.Id,
268+
elementAsserter: (e, a) =>
269+
{
270+
AssertEqual(e.Id, a.Id);
271+
AssertCollection(e.Addresses, a.Addresses, elementSorter: x => (x.AddressLine1, x.ZipCode, x.Country.Code));
272+
});
273+
255274
[Theory, MemberData(nameof(IsAsyncData))]
256275
public virtual Task Filter_on_property_inside_struct_complex_type(bool async)
257276
=> AssertQuery(

‎test/EFCore.Specification.Tests/Query/NorthwindSetOperationsQueryTestBase.cs‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -887,4 +887,40 @@ public virtual Task Nested_concat_with_distinct_in_the_middle_and_pruning(bool a
887887
.Concat(ss.Set<Customer>().Where(c => c.CustomerID.StartsWith("B")).Distinct())
888888
.Concat(ss.Set<Customer>().Where(c => c.CustomerID.StartsWith("A")))
889889
.Select(x => x.City));
890+
891+
[Theory, MemberData(nameof(IsAsyncData))]
892+
public virtual Task Union_of_different_shapes_in_collection_projection(bool async)
893+
=> AssertQuery(
894+
async,
895+
ss => ss.Set<Customer>().Where(c => c.CustomerID.StartsWith("A")).Select(c => new
896+
{
897+
c.CustomerID,
898+
Ids = c.Orders.Select(o => o.OrderID)
899+
.Union(c.Orders.SelectMany(o => o.OrderDetails).Select(od => od.ProductID))
900+
.ToList()
901+
}),
902+
elementSorter: e => e.CustomerID,
903+
elementAsserter: (e, a) =>
904+
{
905+
AssertEqual(e.CustomerID, a.CustomerID);
906+
AssertCollection(e.Ids, a.Ids, elementSorter: i => i);
907+
});
908+
909+
[Theory, MemberData(nameof(IsAsyncData))]
910+
public virtual Task Intersect_of_different_shapes_in_collection_projection(bool async)
911+
=> AssertQuery(
912+
async,
913+
ss => ss.Set<Customer>().Where(c => c.CustomerID.StartsWith("A")).Select(c => new
914+
{
915+
c.CustomerID,
916+
Ids = c.Orders.SelectMany(o => o.OrderDetails).Select(od => od.ProductID)
917+
.Intersect(ss.Set<Product>().Where(p => p.UnitsInStock > 50).Select(p => p.ProductID))
918+
.ToList()
919+
}),
920+
elementSorter: e => e.CustomerID,
921+
elementAsserter: (e, a) =>
922+
{
923+
AssertEqual(e.CustomerID, a.CustomerID);
924+
AssertCollection(e.Ids, a.Ids, elementSorter: i => i);
925+
});
890926
}

‎test/EFCore.SqlServer.FunctionalTests/Query/ComplexTypeQuerySqlServerTest.cs‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -380,6 +380,26 @@ public override async Task Concat_two_different_complex_type(bool async)
380380
AssertSql();
381381
}
382382

383+
public override async Task Union_complex_type_with_different_identifiers_in_collection_projection(bool async)
384+
{
385+
await base.Union_complex_type_with_different_identifiers_in_collection_projection(async);
386+
387+
AssertSql(
388+
"""
389+
SELECT [c].[Id], [u].[ShippingAddress_AddressLine1], [u].[ShippingAddress_AddressLine2], [u].[ShippingAddress_Tags], [u].[ShippingAddress_ZipCode], [u].[ShippingAddress_Country_Code], [u].[ShippingAddress_Country_FullName]
390+
FROM [CustomerGroup] AS [c]
391+
OUTER APPLY (
392+
SELECT [c0].[ShippingAddress_AddressLine1], [c0].[ShippingAddress_AddressLine2], [c0].[ShippingAddress_Tags], [c0].[ShippingAddress_ZipCode], [c0].[ShippingAddress_Country_Code], [c0].[ShippingAddress_Country_FullName]
393+
FROM [Customer] AS [c0]
394+
UNION
395+
SELECT [c1].[ShippingAddress_AddressLine1], [c1].[ShippingAddress_AddressLine2], [c1].[ShippingAddress_Tags], [c1].[ShippingAddress_ZipCode], [c1].[ShippingAddress_Country_Code], [c1].[ShippingAddress_Country_FullName]
396+
FROM [Customer] AS [c1]
397+
WHERE [c1].[Id] > 1
398+
) AS [u]
399+
ORDER BY [c].[Id], [u].[ShippingAddress_AddressLine1], [u].[ShippingAddress_AddressLine2], [u].[ShippingAddress_Tags], [u].[ShippingAddress_ZipCode], [u].[ShippingAddress_Country_Code]
400+
""");
401+
}
402+
383403
public override async Task Union_two_different_complex_type(bool async)
384404
{
385405
await base.Union_two_different_complex_type(async);

‎test/EFCore.SqlServer.FunctionalTests/Query/NorthwindSetOperationsQuerySqlServerTest.cs‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1820,6 +1820,52 @@ FROM [Customers] AS [c0]
18201820
""");
18211821
}
18221822

1823+
public override async Task Union_of_different_shapes_in_collection_projection(bool async)
1824+
{
1825+
await base.Union_of_different_shapes_in_collection_projection(async);
1826+
1827+
AssertSql(
1828+
"""
1829+
SELECT [c].[CustomerID], [u].[OrderID]
1830+
FROM [Customers] AS [c]
1831+
OUTER APPLY (
1832+
SELECT [o].[OrderID]
1833+
FROM [Orders] AS [o]
1834+
WHERE [c].[CustomerID] = [o].[CustomerID]
1835+
UNION
1836+
SELECT [o1].[ProductID] AS [OrderID]
1837+
FROM [Orders] AS [o0]
1838+
INNER JOIN [Order Details] AS [o1] ON [o0].[OrderID] = [o1].[OrderID]
1839+
WHERE [c].[CustomerID] = [o0].[CustomerID]
1840+
) AS [u]
1841+
WHERE [c].[CustomerID] LIKE N'A%'
1842+
ORDER BY [c].[CustomerID]
1843+
""");
1844+
}
1845+
1846+
public override async Task Intersect_of_different_shapes_in_collection_projection(bool async)
1847+
{
1848+
await base.Intersect_of_different_shapes_in_collection_projection(async);
1849+
1850+
AssertSql(
1851+
"""
1852+
SELECT [c].[CustomerID], [i].[ProductID]
1853+
FROM [Customers] AS [c]
1854+
OUTER APPLY (
1855+
SELECT [o0].[ProductID]
1856+
FROM [Orders] AS [o]
1857+
INNER JOIN [Order Details] AS [o0] ON [o].[OrderID] = [o0].[OrderID]
1858+
WHERE [c].[CustomerID] = [o].[CustomerID]
1859+
INTERSECT
1860+
SELECT [p].[ProductID]
1861+
FROM [Products] AS [p]
1862+
WHERE [p].[UnitsInStock] > CAST(50 AS smallint)
1863+
) AS [i]
1864+
WHERE [c].[CustomerID] LIKE N'A%'
1865+
ORDER BY [c].[CustomerID]
1866+
""");
1867+
}
1868+
18231869
private void AssertSql(params string[] expected)
18241870
=> Fixture.TestSqlLoggerFactory.AssertBaseline(expected);
18251871

‎test/EFCore.Sqlite.FunctionalTests/Query/ComplexTypeQuerySqliteTest.cs‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -379,6 +379,12 @@ public override async Task Concat_two_different_complex_type(bool async)
379379
AssertSql();
380380
}
381381

382+
public override async Task Union_complex_type_with_different_identifiers_in_collection_projection(bool async)
383+
=> Assert.Equal(
384+
SqliteStrings.ApplyNotSupported,
385+
(await Assert.ThrowsAsync<InvalidOperationException>(
386+
() => base.Union_complex_type_with_different_identifiers_in_collection_projection(async))).Message);
387+
382388
public override async Task Union_two_different_complex_type(bool async)
383389
{
384390
await base.Union_two_different_complex_type(async);

‎test/EFCore.Sqlite.FunctionalTests/Query/NorthwindSetOperationsQuerySqliteTest.cs‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
// Licensed to the .NET Foundation under one or more agreements.
22
// The .NET Foundation licenses this file to you under the MIT license.
33

4+
using Microsoft.EntityFrameworkCore.Sqlite.Internal;
5+
46
namespace Microsoft.EntityFrameworkCore.Query;
57

68
public class NorthwindSetOperationsQuerySqliteTest : NorthwindSetOperationsQueryRelationalTestBase<
@@ -83,6 +85,16 @@ SELECT 1
8385
""");
8486
}
8587

88+
public override async Task Union_of_different_shapes_in_collection_projection(bool async)
89+
=> Assert.Equal(
90+
SqliteStrings.ApplyNotSupported,
91+
(await Assert.ThrowsAsync<InvalidOperationException>(() => base.Union_of_different_shapes_in_collection_projection(async))).Message);
92+
93+
public override async Task Intersect_of_different_shapes_in_collection_projection(bool async)
94+
=> Assert.Equal(
95+
SqliteStrings.ApplyNotSupported,
96+
(await Assert.ThrowsAsync<InvalidOperationException>(() => base.Intersect_of_different_shapes_in_collection_projection(async))).Message);
97+
8698
private void AssertSql(params string[] expected)
8799
=> Fixture.TestSqlLoggerFactory.AssertBaseline(expected);
88100
}

0 commit comments

Comments
 (0)