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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@ has the rules.

- EF Core: a fifth package, `CodoMetis.ValueRanges.EFCore.PostgreSQL.SchemaKit`, adds **`Overlaps`** to SchemaKit's exclusion constraints for every range and range set type, NodaTime's included. `pg.Exclusion(pg.Equal(b => b.RoomId).Overlaps(b => b.Period))` replaces `WithUncheckedOperator(b => b.Period, "&&")` and does not compile for any other property ([Reject overlapping rows](https://github.com/CaffeinatedCoder/CodoMetis.ValueRanges/blob/main/docs/efcore.md#reject-overlapping-rows-with-an-exclusion-constraint)).

### Fixed

- EF Core: a set built inline in a query from an array, `Int32Set.From(new[] { 1, 2 })`, translates as the set it builds. Since C# 14 that call takes a span, and EF Core threw while evaluating it. An array of captured variables is refused with what to write instead ([#583](https://github.com/CaffeinatedCoder/CodoMetis.ValueRanges/issues/583)).

## [11.0.0-preview.2] — 2026-11-30

The range set type was renamed, one kind of switch stops compiling, and some calls answer differently: [Migration from v10.x](https://github.com/CaffeinatedCoder/CodoMetis.ValueRanges/blob/main/docs/migration.md#migration-from-v10x).
Expand Down
4 changes: 3 additions & 1 deletion src/CodoMetis.ValueRanges.EFCore.PostgreSQL/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ covers all five packages, which share one version number and release together.

## [11.0.0-preview.3]

No change in this package.
### Fixed

- EF Core: a set built inline in a query from an array, `Int32Set.From(new[] { 1, 2 })`, translates as the set it builds. Since C# 14 that call takes a span, and EF Core threw while evaluating it. An array of captured variables is refused with what to write instead ([#583](https://github.com/CaffeinatedCoder/CodoMetis.ValueRanges/issues/583)).

## [11.0.0-preview.2] — 2026-11-30

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ public static IServiceCollection AddEntityFrameworkNpgsqlValueRanges(this IServi
.TryAdd<IMemberTranslatorPlugin, ValueSetsMemberTranslatorPlugin>()
.TryAdd<IAggregateMethodCallTranslatorPlugin, ValueRangesAggregateMethodCallTranslatorPlugin>()
.TryAdd<IInterceptor, ValueRangesQueryExpressionInterceptor>()
.TryAdd<IEvaluatableExpressionFilterPlugin, ArraySpanConversionFilterPlugin>()
.TryAdd<IConventionSetPlugin, ValueRangesConventionSetPlugin>();

// No plugin seam exists after translation, so the final-SQL check decorates the provider's
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
using System.Linq.Expressions;
using Microsoft.EntityFrameworkCore.Query;

namespace CodoMetis.ValueRanges.EntityFrameworkCore.PostgreSQL.Query;

/// <summary>
/// Keeps EF Core from evaluating the implicit conversion of an array to a span, so that
/// <c>Int32Set.From(new[] { 1, 2 })</c> inline in a query reaches the query interceptor (#583).
/// </summary>
/// <remarks>
/// <para>
/// Since C# 14 an array converts to a span implicitly, and overload resolution prefers
/// <c>From(params ReadOnlySpan&lt;T&gt;)</c> to <c>From(IEnumerable&lt;T&gt;)</c>, so the tree holds
/// <c>ReadOnlySpan&lt;T&gt;.op_Implicit(array)</c>. EF Core evaluates a subtree that depends on nothing
/// in the query with the LINQ interpreter before any plugin sees the query, and the interpreter cannot
/// call a method that returns a ref struct: every such query threw "An exception was thrown while
/// attempting to evaluate a LINQ query parameter expression". EF Core rewrites the conversion away for
/// <see cref="MemoryExtensions"/> only.
/// </para>
/// <para>
/// Declared not evaluatable, the conversion stays in the tree with the array under it, which EF Core
/// keeps as an inline array of constants and parameters, and the query interceptor replaces the call
/// with its <see cref="IEnumerable{T}"/> overload. No expression that evaluates today is changed: the
/// interpreter fails on every one that holds this conversion.
/// </para>
/// </remarks>
internal sealed class ArraySpanConversionFilterPlugin : IEvaluatableExpressionFilterPlugin
{
public bool IsEvaluatableExpression(Expression expression)
=> !IsArrayToSpan(expression);

/// <summary><c>Span&lt;T&gt;.op_Implicit(T[])</c> or <c>ReadOnlySpan&lt;T&gt;.op_Implicit(T[])</c>.</summary>
internal static bool IsArrayToSpan(Expression expression)
=> expression is MethodCallExpression
{
Method: { Name: "op_Implicit", DeclaringType: { IsGenericType: true } declaringType },
Arguments: [{ Type.IsArray: true }]
}
&& declaringType.GetGenericTypeDefinition() is var definition
&& (definition == typeof(ReadOnlySpan<>) || definition == typeof(Span<>));
}
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,10 @@ namespace CodoMetis.ValueRanges.EntityFrameworkCore.PostgreSQL.Query;
/// the natural order — see <see cref="RangeComparerRewriter"/>.
/// </para>
/// <para>
/// A seventh turns a set built inline from an array, <c>Int32Set.From(new[] { 1, 2 })</c>, which C# 14
/// binds to the span overload, into the set it builds — see <see cref="SpanFromRewriter"/>.
/// </para>
/// <para>
/// The value set refusals — a server-computed <c>Union</c> consumed by an order- or
/// multiplicity-sensitive operation, and <c>ExecuteUpdate</c> writing a value set into a JSON
/// column — are not made here but on the translated SQL, by <see cref="ValueSetSqlGuard"/>: at the
Expand All @@ -48,7 +52,8 @@ public Expression QueryCompilationStarting(Expression queryExpression, QueryExpr
RangeVariantConstantRetyper.Instance.Visit(
NullOperandCompareToRewriter.Instance.Visit(
RangeComparerRewriter.Instance.Visit(
RangeSetContainsRewriter.Instance.Visit(RangeSetOperatorRewriter.Instance.Visit(queryExpression))))),
RangeSetContainsRewriter.Instance.Visit(
RangeSetOperatorRewriter.Instance.Visit(SpanFromRewriter.Instance.Visit(queryExpression)))))),
DefaultCollectionMode(eventData.Context));

private static ParameterTranslationMode DefaultCollectionMode(DbContext? context)
Expand Down Expand Up @@ -472,6 +477,95 @@ private static bool IsRangeOrSetType(Type type)
}
}

/// <summary>
/// Turns <c>XSet.From(new[] { … })</c>, which C# 14 binds to <c>From(params ReadOnlySpan&lt;T&gt;)</c>,
/// into the set it builds (#583).
/// </summary>
/// <remarks>
/// <para>
/// <see cref="ArraySpanConversionFilterPlugin"/> keeps EF Core from evaluating the span conversion,
/// which its LINQ interpreter cannot run, so the call reaches here with the array under it as EF Core
/// left it. An array of constants is built into the set now, through <c>From(IEnumerable&lt;T&gt;)</c>,
/// and inlined as a constant, which is what EF Core does with <c>XSet.Parse("{1,2}", null)</c>. An
/// array that reads a column is handed to the <see cref="IEnumerable{T}"/> overload and left to the
/// rest of the query, where a final projection runs it.
/// </para>
/// <para>
/// An array of captured variables cannot be built here: their values are bound when the query runs,
/// and this rewrite runs once, when it compiles. EF Core would have evaluated the whole call as one
/// parameter and failed in the interpreter, so it is refused, with the two spellings that evaluate.
/// </para>
/// </remarks>
private sealed class SpanFromRewriter : ExpressionVisitor
{
public static readonly SpanFromRewriter Instance = new();

protected override Expression VisitMethodCall(MethodCallExpression node)
{
if (node is not { Object: null, Method: { Name: "From", DeclaringType: { } setType }, Arguments: [MethodCallExpression conversion] }
|| !ArraySpanConversionFilterPlugin.IsArrayToSpan(conversion)
|| !IsSetType(setType)
|| EnumerableFrom(setType, conversion.Arguments[0].Type.GetElementType()!) is not { } enumerableFrom)
return base.VisitMethodCall(node);

var array = Visit(conversion.Arguments[0]);
var call = Expression.Call(enumerableFrom, Expression.Convert(array, enumerableFrom.GetParameters()[0].ParameterType));

return ReadsOf(array) switch
{
Reads.Nothing => Expression.Constant(
Expression.Lambda<Func<object>>(Expression.Convert(call, typeof(object))).Compile(preferInterpretation: true)(),
node.Type),
Reads.ParametersOnly => throw CapturedRefused(setType, array.Type.GetElementType()!),
_ => call
};
}

private static bool IsSetType(Type type)
=> SetTypeRegistry.TryGetByClrType(type, out _)
|| (RangeTypeRegistry.TryGetByClrType(type, out _, out var isSet) && isSet);

private static MethodInfo? EnumerableFrom(Type setType, Type element)
=> setType.GetMethod("From", BindingFlags.Public | BindingFlags.Static, [typeof(IEnumerable<>).MakeGenericType(element)]);

private static InvalidOperationException CapturedRefused(Type setType, Type element)
=> new($"'{setType.Name}.From(new[] {{ … }})' over captured variables cannot be evaluated in a query: since C# 14 it "
+ $"calls 'From(ReadOnlySpan<{element.Name}>)', and EF Core evaluates query parameters with an interpreter that "
+ $"cannot create a span. Build the set before the query and capture it, or pass the array as "
+ $"'IEnumerable<{element.Name}>' (a list, or '(IEnumerable<{element.Name}>)new[] {{ … }}').");

private enum Reads { Nothing, ParametersOnly, Query }

/// <summary>What an array expression reads: nothing, only query parameters, or the query itself.</summary>
private static Reads ReadsOf(Expression array)
{
var visitor = new ReadsVisitor();
visitor.Visit(array);

return visitor.Query ? Reads.Query : visitor.Parameters ? Reads.ParametersOnly : Reads.Nothing;
}

private sealed class ReadsVisitor : ExpressionVisitor
{
public bool Parameters { get; private set; }
public bool Query { get; private set; }

protected override Expression VisitParameter(ParameterExpression node)
{
Query = true;
return node;
}

protected override Expression VisitExtension(Expression node)
{
if (node is QueryParameterExpression) Parameters = true;
else Query = true;

return node;
}
}
}

private sealed class RangeSetOperatorRewriter : ExpressionVisitor
{
public static readonly RangeSetOperatorRewriter Instance = new();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
using System.Globalization;
using System.Linq.Expressions;
using System.Reflection;
using Microsoft.EntityFrameworkCore;

namespace CodoMetis.ValueRanges.EFCore.PostgreSQL.Tests;

/// <summary>
/// A set built inline in a query from an array, <c>Int32Set.From(new[] { 1, 2 })</c> (#583). Since C# 14
/// an array converts to a span implicitly, so the call binds <c>From(params ReadOnlySpan&lt;T&gt;)</c> and
/// the expression tree holds <c>ReadOnlySpan&lt;T&gt;.op_Implicit(array)</c>, which the LINQ interpreter
/// EF Core evaluates query parameters with cannot run: the query threw "An exception was thrown while
/// attempting to evaluate a LINQ query parameter expression". It now gives the SQL of the same set built
/// inline through <c>From(IEnumerable&lt;T&gt;)</c>.
/// </summary>
/// <remarks>
/// The tree is built here as the C# 14 compiler writes it, for every set and range set column of
/// <see cref="Booking"/>, so a set type added later is covered without an edit.
/// </remarks>
[TestClass]
public sealed class InlineSetFromArrayTests
{
// Tried in order; the first an element type parses is its sample.
private static readonly string[] SampleTexts =
[
"1", "00000000-0000-0000-0000-000000000001", "2026-01-01", "10:30", "2026-01-01 10:30:00",
"2026-01-01 10:30:00+00", "[1,5)", "[2026-01-01,2026-01-03)", "[10:00,11:00)", "[1.5,2.5)"
];

public static IEnumerable<object[]> SetColumns
=> typeof(Booking).GetProperties()
.Select(p => p.PropertyType)
.Where(t => SpanFrom(t) is not null && EnumerableFrom(t) is not null)
.Distinct()
.Select(t => new object[] { t });

[TestMethod]
public void EverySetColumn_IsCovered()
=> Assert.IsGreaterThan(20, SetColumns.Count());

[TestMethod]
[DynamicData(nameof(SetColumns))]
public void FromAnInlineArray_TranslatesAsTheSetItBuilds(Type setType)
{
var element = SpanFrom(setType)!.GetParameters()[0].ParameterType.GetGenericArguments()[0];
var sample = Sample(element);
var array = Expression.NewArrayInit(element, Expression.Constant(sample, element));

// ReadOnlySpan<T>.op_Implicit(T[]), the conversion C# 14 writes for From(new[] { x }).
var toSpan = typeof(ReadOnlySpan<>).MakeGenericType(element)
.GetMethod("op_Implicit", [element.MakeArrayType()])!;
var inline = Expression.Call(SpanFrom(setType)!, Expression.Call(toSpan, array));

var values = Array.CreateInstance(element, 1);
values.SetValue(sample, 0);
var expected = Expression.Constant(EnumerableFrom(setType)!.Invoke(null, [values]), setType);

Assert.AreEqual(Where(setType, expected), Where(setType, inline));
}

/// <summary>The tree the compiler writes, rather than one built here, so the shape above is the real one.</summary>
[TestMethod]
public void AsWrittenInCSharp()
{
using var db = new TestDbContext();

Assert.AreEqual(
db.Bookings.Where(b => b.Codes == Int32Set.Parse("{1,2}", null)).ToQueryString(),
db.Bookings.Where(b => b.Codes == Int32Set.From(new[] { 2, 1, 2 })).ToQueryString());
}

/// <summary>
/// A column in the array leaves the call to the rest of the query: a final projection reads the array
/// and builds the set in memory, through <c>From</c>, so it is canonical.
/// </summary>
[TestMethod]
public void AnArrayReadingAColumn_RunsInTheProjection()
{
using var db = new TestDbContext();

StringAssert.Contains(
db.Bookings.Select(b => Int32Set.From(new[] { b.Id, 1 })).ToQueryString(),
"ARRAY[b.\"Id\",1]::integer[]");
}

/// <summary>
/// Captured variables are bound when the query runs, after the rewrite, so the call cannot be built; it
/// is refused with the spellings that work, where EF Core's interpreter failed without naming either.
/// </summary>
[TestMethod]
public void AnArrayOfCapturedVariables_IsRefusedWithTheWayOut()
{
using var db = new TestDbContext();
var (first, second) = (1, 2);

var error = Assert.ThrowsExactly<InvalidOperationException>(
() => db.Bookings.Where(b => b.Codes == Int32Set.From(new[] { first, second })).ToQueryString());

StringAssert.Contains(error.Message, "Int32Set.From(new[] { … })");
StringAssert.Contains(error.Message, "IEnumerable<Int32>");
}

private static string Where(Type setType, Expression operand)
{
using var db = new TestDbContext();
var booking = Expression.Parameter(typeof(Booking), "b");
var column = Expression.Property(booking, typeof(Booking).GetProperties().First(p => p.PropertyType == setType));
var lambda = Expression.Lambda<Func<Booking, bool>>(Expression.Equal(column, operand), booking);
var sql = db.Bookings.Where(lambda).ToQueryString();

return sql[sql.IndexOf("WHERE", StringComparison.Ordinal)..].Trim();
}

private static MethodInfo? SpanFrom(Type setType)
=> setType.GetMethods(BindingFlags.Public | BindingFlags.Static)
.FirstOrDefault(m => m is { Name: "From" }
&& m.GetParameters() is [{ ParameterType: { IsGenericType: true } p }]
&& p.GetGenericTypeDefinition() == typeof(ReadOnlySpan<>));

private static MethodInfo? EnumerableFrom(Type setType)
=> setType.GetMethods(BindingFlags.Public | BindingFlags.Static)
.FirstOrDefault(m => m is { Name: "From" }
&& m.GetParameters() is [{ ParameterType: { IsGenericType: true } p }]
&& p.GetGenericTypeDefinition() == typeof(IEnumerable<>));

private static object Sample(Type element)
{
if (element == typeof(string)) return "a";

var parse = element.GetMethod("Parse", BindingFlags.Public | BindingFlags.Static, [typeof(string), typeof(IFormatProvider)])!;

foreach (var text in SampleTexts)
{
try { return parse.Invoke(null, [text, CultureInfo.InvariantCulture])!; }
catch (TargetInvocationException) { }
}

throw new AssertFailedException($"No sample text parses as {element}.");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,20 @@ Oracles: RangeOrderParityTests
Fails: every CompareTo comparison with a null operand that memory answers true (> 0, >= 0, != 0), which returns no rows
History: found by the pre-tag analysis (#179), fixed before 10.0.0 shipped (#220)
diff --git a/src/CodoMetis.ValueRanges.EFCore.PostgreSQL/Query/ValueRangesQueryExpressionInterceptor.cs b/src/CodoMetis.ValueRanges.EFCore.PostgreSQL/Query/ValueRangesQueryExpressionInterceptor.cs
index d8a20c2..de88f0f 100644
index a22fc74..b061156 100644
--- a/src/CodoMetis.ValueRanges.EFCore.PostgreSQL/Query/ValueRangesQueryExpressionInterceptor.cs
+++ b/src/CodoMetis.ValueRanges.EFCore.PostgreSQL/Query/ValueRangesQueryExpressionInterceptor.cs
@@ -44,9 +44,8 @@ public sealed class ValueRangesQueryExpressionInterceptor : IQueryExpressionInte
@@ -50,10 +50,9 @@ public sealed class ValueRangesQueryExpressionInterceptor : IQueryExpressionInte
public Expression QueryCompilationStarting(Expression queryExpression, QueryExpressionEventData eventData)
=> CollectionParameterExpander.Expand(
RangeVariantConstantRetyper.Instance.Visit(
- NullOperandCompareToRewriter.Instance.Visit(
- RangeComparerRewriter.Instance.Visit(
- RangeSetContainsRewriter.Instance.Visit(RangeSetOperatorRewriter.Instance.Visit(queryExpression))))),
- RangeSetContainsRewriter.Instance.Visit(
- RangeSetOperatorRewriter.Instance.Visit(SpanFromRewriter.Instance.Visit(queryExpression)))))),
+ RangeComparerRewriter.Instance.Visit(
+ RangeSetContainsRewriter.Instance.Visit(RangeSetOperatorRewriter.Instance.Visit(queryExpression)))),
+ RangeSetContainsRewriter.Instance.Visit(
+ RangeSetOperatorRewriter.Instance.Visit(SpanFromRewriter.Instance.Visit(queryExpression))))),
DefaultCollectionMode(eventData.Context));

private static ParameterTranslationMode DefaultCollectionMode(DbContext? context)
Loading
Loading