Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 19 additions & 2 deletions src/EFCore.PG/Query/NpgsqlSqlExpressionFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -816,10 +816,27 @@ when left.Type.FullName is "NodaTime.Instant" or "NodaTime.LocalDateTime" or "No
$"Incorrect {nameof(operatorType)} for {nameof(pgBinaryExpression)}: {operatorType}");
}

// Preserve the element converter and store type, but give each operand a converter for its own CLR collection type.
// Other concrete collection parameters are materialized to List<T> before conversion in EF8; keep their existing mapping.
// Converter-free mappings can keep using the original array/list parameter without copying.
return new PgBinaryExpression(
operatorType,
ApplyTypeMapping(left, inferredTypeMapping),
ApplyTypeMapping(right, inferredTypeMapping),
ApplyTypeMapping(
left,
inferredTypeMapping is NpgsqlArrayTypeMapping { Converter: not null } leftArrayMapping
&& left.Type != leftArrayMapping.ClrType
&& (left.Type.IsArrayOrGenericList() || left.Type.IsInterface)
? _typeMappingSource.FindCollectionMapping(
leftArrayMapping.StoreType, left.Type, leftArrayMapping.ElementTypeMapping)
: inferredTypeMapping),
ApplyTypeMapping(
right,
inferredTypeMapping is NpgsqlArrayTypeMapping { Converter: not null } rightArrayMapping
&& right.Type != rightArrayMapping.ClrType
&& (right.Type.IsArrayOrGenericList() || right.Type.IsInterface)
? _typeMappingSource.FindCollectionMapping(
rightArrayMapping.StoreType, right.Type, rightArrayMapping.ElementTypeMapping)
: inferredTypeMapping),
resultType,
resultTypeMapping ?? _typeMappingSource.FindMapping(resultType));

Expand Down
9 changes: 9 additions & 0 deletions src/EFCore.PG/Storage/Internal/NpgsqlTypeMappingSource.cs
Original file line number Diff line number Diff line change
Expand Up @@ -577,6 +577,15 @@ is PropertyInfo globalEnumTypeMappingsProperty
return null;
}

/// <summary>
/// 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.
/// </summary>
internal RelationalTypeMapping? FindCollectionMapping(string storeType, Type modelType, RelationalTypeMapping elementMapping)
=> FindCollectionMapping(new RelationalTypeMappingInfo(modelType, storeTypeName: storeType), modelType, null, elementMapping);

/// <summary>
/// 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
Expand Down
39 changes: 39 additions & 0 deletions test/EFCore.PG.FunctionalTests/Query/ArrayArrayQueryTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -831,6 +831,45 @@ WHERE s."ValueConvertedArrayOfEnum" && @__list_0
""");
}

[ConditionalTheory]
[InlineData(false)]
[InlineData(true)]
public virtual async Task Intersect_any_without_converter_does_not_copy_parameter(bool list)
{
await using var context = CreateContext();
IEnumerable<int> values = list ? new List<int> { 3 } : new[] { 3 };

var query = context.SomeEntities.Where(e => e.IntArray.Intersect(values).Any()).Select(e => e.Id);
var reversed = context.SomeEntities.Where(e => values.Intersect(e.IntArray).Any()).Select(e => e.Id);

using var command = query.CreateDbCommand();
using var reversedCommand = reversed.CreateDbCommand();
Assert.Same(values, command.Parameters[0].Value);
Assert.Same(values, reversedCommand.Parameters[0].Value);

var result = await query.ToArrayAsync();
var reversedResult = await reversed.ToArrayAsync();
Assert.Equal([1], result);
Assert.Equal([1], reversedResult);

AssertSql(
"""
@__values_0={ '3' } (DbType = Object)

SELECT s."Id"
FROM "SomeEntities" AS s
WHERE s."IntArray" && @__values_0
""",
//
"""
@__values_0={ '3' } (DbType = Object)

SELECT s."Id"
FROM "SomeEntities" AS s
WHERE @__values_0 && s."IntArray"
""");
}

public override async Task All_Contains(bool async)
{
await base.All_Contains(async);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System.Collections.Immutable;
using Npgsql.EntityFrameworkCore.PostgreSQL.Internal;
using Npgsql.EntityFrameworkCore.PostgreSQL.TestUtilities;

Expand Down Expand Up @@ -148,6 +149,195 @@ public class Order
}
}

[ConditionalTheory]
[InlineData(nameof(Context3805.Entity.Array), "array")]
[InlineData(nameof(Context3805.Entity.Array), "list")]
[InlineData(nameof(Context3805.Entity.Array), "immutable")]
[InlineData(nameof(Context3805.Entity.Array), "set")]
[InlineData(nameof(Context3805.Entity.Array), "enumerable")]
[InlineData(nameof(Context3805.Entity.List), "array")]
[InlineData(nameof(Context3805.Entity.List), "list")]
[InlineData(nameof(Context3805.Entity.List), "immutable")]
[InlineData(nameof(Context3805.Entity.List), "set")]
[InlineData(nameof(Context3805.Entity.List), "enumerable")]
public virtual async Task Intersect_any_with_element_converter_and_different_collection_types(
string propertyName,
string parameterType)
{
var contextFactory = await InitializeAsync<Context3805>(
seed: context => context.Database.ExecuteSqlRaw(
"""
INSERT INTO "Entities" ("Id", "Array", "List")
VALUES (1, ARRAY[42]::bigint[], ARRAY[42]::bigint[]),
(2, ARRAY[99]::bigint[], ARRAY[99]::bigint[]),
(3, ARRAY[]::bigint[], ARRAY[]::bigint[])
"""));

await using var context = contextFactory.CreateContext();

IEnumerable<Context3805.WrappedId> values = parameterType switch
{
"array" => new Context3805.WrappedId[] { new(42) },
"list" => new List<Context3805.WrappedId> { new(42) },
"immutable" => ImmutableList.Create(new Context3805.WrappedId(42)),
"set" => new HashSet<Context3805.WrappedId> { new(42) },
"enumerable" => new[] { new Context3805.WrappedId(42) }.Where(_ => true),
_ => throw new ArgumentOutOfRangeException(nameof(parameterType))
};

var result = await context.Entities
.Where(e => EF.Property<IEnumerable<Context3805.WrappedId>>(e, propertyName).Intersect(values).Any())
.Select(e => e.Id).ToArrayAsync();
var reversed = await context.Entities
.Where(e => values.Intersect(EF.Property<IEnumerable<Context3805.WrappedId>>(e, propertyName)).Any())
.Select(e => e.Id).ToArrayAsync();

Assert.Equal([1], result);
Assert.Equal([1], reversed);

AssertSql(
$$"""
@__values_0={ '42' } (DbType = Object)

SELECT e."Id"
FROM "Entities" AS e
WHERE e."{{propertyName}}" && @__values_0
""",
//
$$"""
@__values_0={ '42' } (DbType = Object)

SELECT e."Id"
FROM "Entities" AS e
WHERE @__values_0 && e."{{propertyName}}"
""");
}

[ConditionalFact]
public virtual async Task Intersect_any_with_element_converter_and_concrete_immutable_list_parameter()
{
var contextFactory = await InitializeAsync<Context3805>(
seed: context => context.Database.ExecuteSqlRaw(
"""
INSERT INTO "Entities" ("Id", "Array", "List")
VALUES (1, ARRAY[42]::bigint[], ARRAY[42]::bigint[]),
(2, ARRAY[99]::bigint[], ARRAY[99]::bigint[]),
(3, ARRAY[]::bigint[], ARRAY[]::bigint[])
"""));

await using var context = contextFactory.CreateContext();
var values = ImmutableList.Create(new Context3805.WrappedId(42));

var result = await context.Entities.Where(e => e.List.Intersect(values).Any()).Select(e => e.Id).ToArrayAsync();
var reversed = await context.Entities.Where(e => values.Intersect(e.List).Any()).Select(e => e.Id).ToArrayAsync();

Assert.Equal([1], result);
Assert.Equal([1], reversed);

AssertSql(
"""
@__values_0={ '42' } (DbType = Object)

SELECT e."Id"
FROM "Entities" AS e
WHERE e."List" && @__values_0
""",
//
"""
@__values_0={ '42' } (DbType = Object)

SELECT e."Id"
FROM "Entities" AS e
WHERE @__values_0 && e."List"
""");
}

protected class Context3805(DbContextOptions options) : DbContext(options)
{
public DbSet<Entity> Entities => Set<Entity>();

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Entity>().PrimitiveCollection(e => e.Array).ElementType().HasConversion<WrappedIdConverter>();
modelBuilder.Entity<Entity>().PrimitiveCollection(e => e.List).ElementType().HasConversion<WrappedIdConverter>();
}

public class Entity
{
public int Id { get; set; }
public WrappedId[] Array { get; set; } = [];
public List<WrappedId> List { get; set; } = [];
}

public readonly record struct WrappedId(long Value);

private class WrappedIdConverter() : ValueConverter<WrappedId, long>(v => v.Value, v => new WrappedId(v));
}

[ConditionalTheory]
[InlineData(nameof(Context3805Ranges.Entity.Ranges))]
[InlineData(nameof(Context3805Ranges.Entity.RangeList))]
public virtual async Task Intersect_any_with_range_array_and_list_parameter(string propertyName)
{
var contextFactory = await InitializeAsync<Context3805Ranges>(
seed: context =>
{
context.Entities.AddRange(
new Context3805Ranges.Entity { Id = 1, Ranges = [new(1, true, 5, false)], RangeList = [new(1, true, 5, false)] },
new Context3805Ranges.Entity { Id = 2, Ranges = [new(10, true, 15, false)], RangeList = [new(10, true, 15, false)] },
new Context3805Ranges.Entity { Id = 3, Ranges = [], RangeList = [] });
context.SaveChanges();
});

await using var context = contextFactory.CreateContext();
List<NpgsqlRange<int>> ranges = [new(1, true, 5, false)];

var result = await context.Entities
.Where(e => EF.Property<IEnumerable<NpgsqlRange<int>>>(e, propertyName).Intersect(ranges).Any())
.Select(e => e.Id).ToArrayAsync();
var reversed = await context.Entities
.Where(e => ranges.Intersect(EF.Property<IEnumerable<NpgsqlRange<int>>>(e, propertyName)).Any())
.Select(e => e.Id).ToArrayAsync();

Assert.Equal([1], result);
Assert.Equal([1], reversed);

AssertSql(
$$"""
@__ranges_0={ '[1,5)' } (DbType = Object)

SELECT e."Id"
FROM "Entities" AS e
WHERE e."{{propertyName}}" && @__ranges_0
""",
//
$$"""
@__ranges_0={ '[1,5)' } (DbType = Object)

SELECT e."Id"
FROM "Entities" AS e
WHERE @__ranges_0 && e."{{propertyName}}"
""");
}

protected class Context3805Ranges(DbContextOptions options) : DbContext(options)
{
public DbSet<Entity> Entities => Set<Entity>();

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Entity>().PrimitiveCollection(e => e.Ranges).HasColumnType("int4range[]");
modelBuilder.Entity<Entity>().PrimitiveCollection(e => e.RangeList).HasColumnType("int4range[]");
}

public class Entity
{
public int Id { get; set; }
public NpgsqlRange<int>[] Ranges { get; set; } = [];
public IList<NpgsqlRange<int>> RangeList { get; set; } = [];
}
}

protected override ITestStoreFactory TestStoreFactory
=> NpgsqlTestStoreFactory.Instance;
}
Loading