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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ The first preview of the 11 line: the same public API as 10.0.0, on .NET 11. Not
- EF Core (NodaTime): Npgsql 11's own temporal keys accept `YearMonthRange` and the NodaTime range and multirange columns. `HasKey(…).WithoutOverlaps()` and `WithPeriod()` foreign keys work over them on PostgreSQL 18 with `SetPostgresVersion(18, 0)` ([Temporal keys](https://github.com/CaffeinatedCoder/CodoMetis.ValueRanges/blob/main/docs/efcore.md#reject-overlapping-rows-with-npgsqls-temporal-keys-postgresql-18)).
- EF Core: `Length` on `Int32Range` and `Int64Range` runs as SQL, so a query can filter and sort by it. It counts the integers as memory does: 0 for the empty range, and `null` for an unbounded side or, on `Int64Range`, a count larger than `long.MaxValue` ([What runs where](https://github.com/CaffeinatedCoder/CodoMetis.ValueRanges/blob/main/docs/efcore.md#what-runs-where)).
- EF Core: `Clamp` on `Int32Range`, `Int64Range` and `DecimalRange` runs as SQL, so a query can filter and sort by the clamped value. It answers as memory does: the value inside the range, otherwise the bound it passes, and `null` for the empty range or a `null` range or value ([What runs where](https://github.com/CaffeinatedCoder/CodoMetis.ValueRanges/blob/main/docs/efcore.md#what-runs-where)).
- EF Core: `Clamp` runs as SQL on every range type, no longer only on `Int32Range`, `Int64Range` and `DecimalRange`, and answers as memory does, at the extremes too. A `DateTime` stored as `timestamp with time zone` against a `DateTimeRange` runs in memory, because PostgreSQL would compare them through the session's time zone ([What runs where](https://github.com/CaffeinatedCoder/CodoMetis.ValueRanges/blob/main/docs/efcore.md#what-runs-where)).
- EF Core: `DateRange.Month`, `Quarter`, `Year` and `IsoWeek` run as SQL when they read a column, so `DateRange.Month(b.Day)` works in a `Where` and an `OrderBy`. They build the range memory builds, the extremes included, and an argument memory rejects fails in PostgreSQL too. The NodaTime forms stay in memory ([What runs where](https://github.com/CaffeinatedCoder/CodoMetis.ValueRanges/blob/main/docs/efcore.md#what-runs-where)).
- EF Core: `Union`, `Add`, `Intersect` and `Except` on value sets run as SQL for every set type except `StringSet` and `StringSet<TElement>`. They give the deduplicated, sorted set memory gives, so a query can compare, count, group by and store the result ([What runs where](https://github.com/CaffeinatedCoder/CodoMetis.ValueRanges/blob/main/docs/efcore.md#what-runs-where)).
- Docs: the guides, the package READMEs, the changelog and an API reference are published as a [documentation site](https://caffeinatedcoder.github.io/CodoMetis.ValueRanges/) with one set of pages per line. It opens on the stable 10.x line, and the 11.x previews are under `/11.x/`.
Expand Down
14 changes: 9 additions & 5 deletions docs/efcore.md
Original file line number Diff line number Diff line change
Expand Up @@ -961,7 +961,7 @@ parameters. A text value set `Union` composes only under some operators; see
| | `IsEmpty`, `IsUnboundedStart`/`End`, `IsInfinity`, `IsFinite` | `isempty`, `lower_inf`, `upper_inf`, and combinations |
| | `LowerBound`/`UpperBound`, `LowerBoundInclusive`/`UpperBoundInclusive` | `lower`, `upper`, `lower_inc`, `upper_inc` |
| | `Length` on `Int32Range` and `Int64Range` | `upper(x) - lower(x)` after a widening cast, and 0 for the empty range |
| | `Clamp(value)` on `Int32Range`, `Int64Range` and `DecimalRange` | `LEAST(GREATEST(value, lower(x)), upper(x))`, one step back from a discrete type's exclusive upper bound, and NULL for the empty range |
| | `Clamp(value)` | `LEAST(GREATEST(value, lower(x)), upper(x))`, one step back from a discrete type's exclusive upper bound, and NULL for the empty range |
| | `CreateFinite`/`CreateUnboundedStart`/`CreateUnboundedEnd` | range constructor functions |
| | `DateRange.Month`, `Quarter`, `Year` and `IsoWeek` with an argument read from a column | `daterange(first, last, '[]')`, the days from `date_trunc` or `make_date`, and an error where memory throws |
| | `RangeAgg`, `RangeIntersectAgg`, over ranges or sets | `range_agg`, `range_intersect_agg` |
Expand All @@ -983,7 +983,7 @@ translation, and in the final projection EF runs them in memory instead:
| `ToRangeSet()` / `ToInt32Set()` and the other bridge conversions | Not translated. An array becomes a multirange through `range_agg` over one-element ranges, which needs care at the element type's extremes: `[2147483647,2147483647]` can't be built as an `int4range`. A multirange becomes an array only by enumerating it, as `Values` does. |
| `Shift`, `Expand` on any range | Not translated. Rebuilding the range from `lower(x) + d` differs from memory unless each case is handled: the empty range becomes `(,)`, `time` wraps at midnight where `TimeRange` throws, and a bound moved past the last date .NET holds throws in memory where PostgreSQL returns a later date. A bound at `infinity` stays there in both. |
| `LocalDateRange.Month`, `Quarter`, `Year` and `IsoWeek`, and `YearMonthRange.Quarter` and `Year`, with an argument read from a column | Not translated. PostgreSQL has no dates before 4714-11-24 BC, so the month and the year that hold its first day have no start, and the database would fail where memory returns a range. That holds with Npgsql's infinity conversions on or off. Built from values your code passes in, the range is computed in memory and sent as one constant, so comparing a column against a month runs as SQL. On `DateRange` these run as SQL. |
| `Clamp(value)` on the other range types | Not translated. The same `LEAST(GREATEST(…))` form would apply, but it has only been checked against memory on `Int32Range`, `Int64Range` and `DecimalRange`, where it runs as SQL. |
| `Clamp(value)` on a `DateTimeRange`, with a `DateTime` stored as `timestamp with time zone` | Not translated. Npgsql stores a `DateTime` property as `timestamp with time zone` unless you map it otherwise, and a `DateTimeRange` as a `tsrange`. `GREATEST` and `LEAST` would compare the two through the session's time zone, while memory compares the clock times. Map the property with `HasColumnType("timestamp without time zone")` and `Clamp` runs as SQL. |
| `Intersect`, `Except` and `Add` on `StringSet` and `StringSet<TElement>` | Not translated. Their results have to be sorted, and PostgreSQL sorts `text` by the database collation rather than ordinally. On the other set types they run as SQL. |
| The value set indexer, `set[0]` | Subscripting reads the stored array, which is canonical only for rows this library wrote ([Rows written by other tools](#rows-written-by-other-tools)). PostgreSQL arrays also start at 1, and an index past the end is `NULL` where memory throws. |
| `Values` on a value set | It is the loaded array itself. In a query, use the set's own members, such as `Contains` and `Count`. |
Expand All @@ -997,9 +997,13 @@ Good to know:
- **`Length` on `Int32Range` and `Int64Range` counts in the database as it does in memory.** `[1,10]`
measures 10, the empty range 0, and a range unbounded on either side `null`. An `Int64Range` whose
count is larger than `long.MaxValue` measures `null` too, so you can filter and sort by `Length`.
- **`Clamp` on `Int32Range`, `Int64Range` and `DecimalRange` clamps in the database as it does in
memory.** A value inside the range comes back as it is, and one outside comes back as the bound it
passes, even an exclusive one. The empty range gives `null`, and so does a `null` range or value.
- **`Clamp` clamps in the database as it does in memory, on every range type.** A value inside the
range comes back as it is, and one outside comes back as the bound it passes, even an exclusive
one. The empty range gives `null`, and so does a `null` range or value.
- **A value you pass to `Clamp` comes back at the column's precision.** PostgreSQL keeps a
microsecond, so `TimeOnly.MaxValue` comes back as `23:59:59.999999`, as any value sent to the
database does. A bound at a date extreme, which the database holds as an infinity, clamps to the
extreme as in memory.
- **`DateRange.Month`, `Quarter`, `Year` and `IsoWeek` over a column build the same range in the
database as in memory.** `DateRange.Month(b.Day)` gives the month that holds each row's day, so
you can filter, join and sort by it. The first period starts at `-infinity` and the last ends at
Expand Down
2 changes: 1 addition & 1 deletion docs/oracles.md
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,7 @@ range, a multirange or a value set, one key per overload, a generic family kept
overloads an expression tree cannot hold (`ReadOnlySpan<char>`, `out`) are out by rule.

```json
{ "members": "RangeExtensions.Clamp(*", "support": "client", "reason": "docs/efcore.md#what-runs-where: …" }
{ "members": "*Range.Shift(*", "support": "client", "reason": "docs/efcore.md#what-runs-where: …" }
```

- The first entry whose `members` pattern matches a key classifies it: `server` (translates, and answers in
Expand Down
4 changes: 2 additions & 2 deletions docs/ranges.md
Original file line number Diff line number Diff line change
Expand Up @@ -381,8 +381,8 @@ Good to know:

- **The empty range returns `null`.** There is no value to snap to.
- **An unbounded side never constrains.** Clamping into `(-∞, 10]` only ever pulls a value down.
- **`Clamp` runs as SQL on `Int32Range`, `Int64Range` and `DecimalRange`.** On the other range types
it runs in memory ([What runs where](efcore.md#what-runs-where)).
- **`Clamp` runs as SQL on every range type.** The one exception is a `DateTimeRange` clamping a
`DateTime` stored with a time zone, which runs in memory ([What runs where](efcore.md#what-runs-where)).

### Compare positions

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ The first preview of the 11 line: the same public API as 10.0.0, on .NET 11, EF

- EF Core: Npgsql 11's own temporal keys accept `YearMonthRange` and the NodaTime range and multirange columns. `HasKey(…).WithoutOverlaps()` and `WithPeriod()` foreign keys work over them on PostgreSQL 18 with `SetPostgresVersion(18, 0)` ([Temporal keys](https://github.com/CaffeinatedCoder/CodoMetis.ValueRanges/blob/main/docs/efcore.md#reject-overlapping-rows-with-npgsqls-temporal-keys-postgresql-18)).
- EF Core: `Union`, `Add`, `Intersect` and `Except` on the NodaTime value sets, their versions with your own element type and `YearMonthSet` run as SQL. They give the deduplicated, sorted set memory gives, so a query can compare, count, group by and store the result ([What runs where](https://github.com/CaffeinatedCoder/CodoMetis.ValueRanges/blob/main/docs/efcore.md#what-runs-where)).
- EF Core: `Clamp` runs as SQL on `LocalDateRange`, `LocalDateTimeRange`, `InstantRange` and `YearMonthRange`, so a query can filter and sort by the clamped value. It answers as memory does, at the element types' extremes too ([What runs where](https://github.com/CaffeinatedCoder/CodoMetis.ValueRanges/blob/main/docs/efcore.md#what-runs-where)).

### Changed

Expand Down
1 change: 1 addition & 0 deletions src/CodoMetis.ValueRanges.EFCore.PostgreSQL/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ The first preview of the 11 line: the same public API as 10.0.0, on .NET 11, EF
- EF Core: Npgsql 11's own temporal keys accept the range and multirange columns this package maps. `HasKey(…).WithoutOverlaps()` and `WithPeriod()` foreign keys work over a `DateRange`, a `TimeRange` or a `RangeSet`, on PostgreSQL 18 with `SetPostgresVersion(18, 0)` ([Temporal keys](https://github.com/CaffeinatedCoder/CodoMetis.ValueRanges/blob/main/docs/efcore.md#reject-overlapping-rows-with-npgsqls-temporal-keys-postgresql-18)).
- EF Core: `Length` on `Int32Range` and `Int64Range` runs as SQL, so a query can filter and sort by it. It counts the integers as memory does: 0 for the empty range, and `null` for an unbounded side or, on `Int64Range`, a count larger than `long.MaxValue` ([What runs where](https://github.com/CaffeinatedCoder/CodoMetis.ValueRanges/blob/main/docs/efcore.md#what-runs-where)).
- EF Core: `Clamp` on `Int32Range`, `Int64Range` and `DecimalRange` runs as SQL, so a query can filter and sort by the clamped value. It answers as memory does: the value inside the range, otherwise the bound it passes, and `null` for the empty range or a `null` range or value ([What runs where](https://github.com/CaffeinatedCoder/CodoMetis.ValueRanges/blob/main/docs/efcore.md#what-runs-where)).
- EF Core: `Clamp` runs as SQL on every range type, no longer only on `Int32Range`, `Int64Range` and `DecimalRange`, and answers as memory does, at the extremes too. A `DateTime` stored as `timestamp with time zone` against a `DateTimeRange` runs in memory, because PostgreSQL would compare them through the session's time zone ([What runs where](https://github.com/CaffeinatedCoder/CodoMetis.ValueRanges/blob/main/docs/efcore.md#what-runs-where)).
- EF Core: `DateRange.Month`, `Quarter`, `Year` and `IsoWeek` run as SQL when they read a column, so `DateRange.Month(b.Day)` works in a `Where` and an `OrderBy`. They build the range memory builds, the extremes included, and an argument memory rejects fails in PostgreSQL too. The NodaTime forms stay in memory ([What runs where](https://github.com/CaffeinatedCoder/CodoMetis.ValueRanges/blob/main/docs/efcore.md#what-runs-where)).
- EF Core: `Union`, `Add`, `Intersect` and `Except` on value sets run as SQL for every set type except `StringSet` and `StringSet<TElement>`. They give the deduplicated, sorted set memory gives, so a query can compare, count, group by and store the result ([What runs where](https://github.com/CaffeinatedCoder/CodoMetis.ValueRanges/blob/main/docs/efcore.md#what-runs-where)).

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,12 +83,10 @@ IRelationalTypeMappingSource typeMappingSource
private static readonly MethodInfo LowerBoundInclusiveMethod = GetExtensionMethod(nameof(RangeExtensions.LowerBoundInclusive));
private static readonly MethodInfo UpperBoundInclusiveMethod = GetExtensionMethod(nameof(RangeExtensions.UpperBoundInclusive));

// -- RangeExtensions.Clamp: extension<T>(IRange<T>), on the types whose bounds read as memory's (#406) --
// -- RangeExtensions.Clamp: extension<T>(IRange<T>), on every range type (#406, #486) --

private static readonly MethodInfo ClampMethod = GetExtensionMethod(nameof(RangeExtensions.Clamp));

private static readonly HashSet<Type> ClampsAsSql = [typeof(Int32Range), typeof(Int64Range), typeof(DecimalRange)];

// -- The calendar factories (Month, Quarter, Year, IsoWeek) over a column, on the types whose every answer
// PostgreSQL can hold (#191) --

Expand Down Expand Up @@ -339,9 +337,12 @@ SqlExpression Range(int index)
if (generic == UpperBoundInclusiveMethod)
return UpperInclusiveFunction(Range(0), definition);

// On every other range type Clamp runs in memory (docs/efcore.md#what-runs-where).
// A value whose time zone differs from the range's elements runs in memory (MixesTimeZones).
if (generic == ClampMethod)
return ClampsAsSql.Contains(definition.RangeClrType) ? ClampFunction(Range(0), ApplyElementMapping(arguments[1], definition), definition) : null;
{
var value = ApplyElementMapping(arguments[1], definition);
return MixesTimeZones(value, definition) ? null : ClampFunction(Range(0), value, definition);
}

return null;
}
Expand Down Expand Up @@ -1049,19 +1050,30 @@ private SqlExpression UpperBoundFunction(SqlExpression argument, IRangeTypeDefin
}

/// <summary>
/// <c>Clamp(value)</c> on <see cref="Int32Range"/>, <see cref="Int64Range"/> and <see cref="DecimalRange"/>
/// (#406): <c>CASE WHEN x IS NULL OR v IS NULL OR isempty(x) THEN NULL ELSE LEAST(GREATEST(v, lower(x)),
/// &lt;upper&gt;) END</c>, where <c>&lt;upper&gt;</c> is the bound <see cref="UpperBoundFunction"/> reads:
/// <c>upper(x) - 1</c> on the discrete types, <c>upper(x)</c> on <c>numrange</c>.
/// <c>Clamp(value)</c> on every range type (#406, #486): <c>CASE WHEN x IS NULL OR v IS NULL OR isempty(x)
/// THEN NULL ELSE LEAST(GREATEST(v, lower(x)), &lt;upper&gt;) END</c>, where <c>&lt;upper&gt;</c> is the bound
/// <see cref="UpperBoundFunction"/> reads: <c>upper(x) - 1</c> on the discrete types, <c>upper(x)</c> on the
/// continuous ones.
/// </summary>
/// <remarks>
/// <para>
/// Memory's rule: <see langword="null"/> for the empty range, the value itself inside the range, and
/// otherwise the finite bound it falls outside of, whatever that bound's inclusiveness. An unbounded
/// side never constrains, and <c>GREATEST</c> and <c>LEAST</c> skip the NULL <c>lower</c> or
/// <c>upper</c> returns there. They skip a NULL range or value too, so both are tested first, which
/// makes a NULL operand NULL (rule (c)) rather than the other one. Measured on PostgreSQL 16, the domain
/// extremes included: <c>upper(x) - 1</c> cannot overflow, since a stored upper bound is at least one
/// above a value.
/// </para>
/// <para>
/// The same form holds on the other types (#486), measured against memory on every shape and inclusiveness
/// with the extremes as bounds and values (<c>ClampDomainParityTests</c>). A temporal extreme is an
/// infinity on the server, which memory reads back as the extreme: <c>infinity - 1</c> is still
/// <c>infinity</c>, and a range ending at the last date is stored <c>infinity]</c>, inclusive, so that is the
/// date memory clamps to. A <c>YearMonthRange</c> steps back one day from its
/// first-of-month upper bound to the last day of its last month, which reads as that month; its value is
/// the first day of its month, so it compares as memory compares months.
/// </para>
/// </remarks>
private SqlExpression ClampFunction(SqlExpression range, SqlExpression value, IRangeTypeDefinition definition)
{
Expand All @@ -1088,6 +1100,29 @@ SqlExpression Skipping(string name, SqlExpression left, SqlExpression right)
Skipping("LEAST", Skipping("GREATEST", value, BoundFunction("lower", range, definition)), UpperBoundFunction(range, definition)));
}

/// <summary>
/// Whether a value and the range's elements differ in carrying a time zone: a <c>timestamptz</c> value
/// against a <see cref="DateTimeRange"/>'s <c>tsrange</c>, which is what Npgsql maps a <see cref="DateTime"/>
/// property to by default.
/// </summary>
/// <remarks>
/// <c>GREATEST</c> and <c>LEAST</c> resolve their arguments to a common type, and between <c>timestamp</c>
/// and <c>timestamptz</c> that is <c>timestamptz</c>, reached through the session's <c>TimeZone</c>: the
/// range's bounds move by the session's offset, while memory compares ticks. In a Europe/Berlin session,
/// <c>[08:00,18:00)</c> clamped 17:30Z to 17:00Z (#486). The operators that take an element refuse the pair on
/// the server instead (<c>operator does not exist: tsrange @&gt; timestamp with time zone</c>), so declining
/// here keeps <c>Clamp</c> as loud as they are in a filter, and gives memory's answer in a final projection.
/// </remarks>
private bool MixesTimeZones(SqlExpression value, IRangeTypeDefinition definition)
=> value.TypeMapping?.StoreType is { } valueType
&& ElementMapping(definition)?.StoreType is { } elementType
&& CarriesTimeZone(valueType) != CarriesTimeZone(elementType);

private static bool CarriesTimeZone(string storeType)
=> storeType.Contains("with time zone", StringComparison.OrdinalIgnoreCase)
|| storeType.StartsWith("timestamptz", StringComparison.OrdinalIgnoreCase)
|| storeType.StartsWith("timetz", StringComparison.OrdinalIgnoreCase);

/// <summary>
/// The <c>upper_inc()</c> equivalent. On discrete types the model's canonical form is
/// closed, so the upper bound is inclusive exactly when a finite upper bound exists —
Expand Down
Loading
Loading