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
3 changes: 1 addition & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ and every other agent read the same rules. Edit this file, never `CLAUDE.md`.

In-memory range and multirange types for .NET 10, mirroring PostgreSQL's six built-in range domains (`int4range`, `int8range`, `numrange`, `daterange`, `tsrange`, `tstzrange`) plus two v5 additions: `TimeRange` over `TimeOnly` (maps to the custom `timerange` type β€” needs `HasPostgresRange` + `EnableUnmappedTypes` on the EF side) and, in the NodaTime satellite, `YearMonthRange` over `YearMonth` (stored as a month-aligned `daterange`). Since 10.0.0, `Float64Range` and `Float32Range` cover finite `double` and `float` (the custom `float8range` and `float4range`, set up like `timerange`), with `Float64Set`/`Float32Set` and their arities on `double precision[]`/`real[]`. Each range type is a discriminated union of five sealed variants with exhaustive pattern matching.

Since v6 there is a second type family: **value sets** (`Sets/`) β€” immutable, canonical (deduplicated, sorted, no nulls) sets of scalar values stored as native PostgreSQL arrays (`StringSet`/`text[]`, `GuidSet`/`uuid[]`, …), plus a validated-wrapper arity for every family (`StringSet<T>` … `DateTimeOffsetSet<T>`, and five more in the NodaTime satellite) constrained only on BCL interfaces. EF maps them as scalars with plugin-owned mappings and translators (`@>`, `&&`, `<@`, `cardinality`, `array_remove`) β€” never through EF's primitive-collection machinery. Since 10.4.0 `Union`, `Add`, `Intersect` and `Except` run as one canonicalizing subquery (`ARRAY((SELECT DISTINCT ON (x) x FROM unnest(…) WITH ORDINALITY … ORDER BY x, ordinality))`) for every family whose order PostgreSQL shares (`ISetTypeDefinition.CanonicalizesInSql`, #478), built by the SQL guard. Only text is left out: `ORDER BY` follows the database collation rather than ordinal order, so on `StringSet`/`StringSet<T>` `Union` stays `array_cat` and On text they run as SQL only where order and repeats don't count (#485): left unsorted under `@>`/`<@`/`&&`, `IsEmpty` and the outermost projection, `Count` as `count(DISTINCT …)` and `==`/`!=` as mutual containment, until #479 decides the order (`docs/efcore.md#combine-sets-with-union`). Since 10.5.0 `ToRangeSet()` on `Int32Set`, `Int64Set`, `DateSet`, `LocalDateSet` and `YearMonthSet` runs as SQL too, as `range_agg` over the one-element range of each value, built by the same guard (#487); the conversions back to a set run in memory.
Since v6 there is a second type family: **value sets** (`Sets/`) β€” immutable, canonical (deduplicated, sorted, no nulls) sets of scalar values stored as native PostgreSQL arrays (`StringSet`/`text[]`, `GuidSet`/`uuid[]`, …), plus a validated-wrapper arity for every family (`StringSet<T>` … `DateTimeOffsetSet<T>`, and five more in the NodaTime satellite) constrained only on BCL interfaces. EF maps them as scalars with plugin-owned mappings and translators (`@>`, `&&`, `<@`, `cardinality`, `array_remove`) β€” never through EF's primitive-collection machinery. Since 10.4.0 `Union`, `Add`, `Intersect` and `Except` run as one canonicalizing subquery (`ARRAY((SELECT DISTINCT ON (x) x FROM unnest(…) WITH ORDINALITY … ORDER BY x, ordinality))`) for every family whose order PostgreSQL shares (`ISetTypeDefinition.CanonicalizesInSql`, #478), built by the SQL guard. Only text is left out: `ORDER BY` follows the database collation rather than ordinal order, so on `StringSet`/`StringSet<T>` `Union` stays `array_cat` and On text they run as SQL only where order and repeats don't count (#485): left unsorted under `@>`/`<@`/`&&`, `IsEmpty` and the outermost projection, `Count` as `count(DISTINCT …)` and `==`/`!=` as mutual containment, until #479 decides the order (`docs/efcore.md#combine-sets-with-union`).

## Stack
.NET 10 Β· C# 14 (extension methods) Β· MSTest 4.x Β· EF Core + Npgsql (PostgreSQL bridge)
Expand Down Expand Up @@ -137,5 +137,4 @@ the work, and close it from the PR (`Closes #n`).
- **Value sets β€” a set type whose element type System.Text.Json cannot serialize as a scalar MUST override `IValueSetFactory<TSet,T>.ElementJsonConverter`.** JSON delegates elements to the serializer, which property-dumps an unknown type on write and yields `default` on read β€” silently, both legs. The hook is consulted last (only when `GetTypeInfo(typeof(T)).Kind != None`), so it never overrides a registered converter. The primitive-backed families are natively serializable and leave it `null`; the wrapper arities and the five NodaTime sets define one. Integer-backed wrappers write a JSON **number**, not a string, and decimal-backed ones a number keeping scale β€” the token type must always match the primitive the wrapper wraps. Byte-for-byte parity additionally holds for the string, Guid, integer and decimal arities; for the temporal and NodaTime ones the text differs (seven fraction digits, `+` escaped) while the value does not, which is asserted in `SetJsonConverterTests` rather than fixed
- **Value sets β€” a wrapper arity over a type whose default text form is lossy MUST pin a round-trip format**, in `FormatValue` *and* in its `SetTypeRegistry` bridge entry, and parse it strictly. `TimeOnly.ToString(null, invariant)` is `09:30` and `DateTime`'s is `06/15/2024 10:30:00` β€” an arity built like `Int32Set<T>` stores every temporal truncated to the second, and loses `DateTimeKind`, silently on the way to the column. The four temporal arities and the five NodaTime ones do this β€” since 9.0.0 the core `ParseValue` parses strictly too, not only the EF bridge; the string, Guid, integer and decimal ones correctly take the default
- **Value sets β€” canonical form in SQL is built by `ValueSetSqlGuard`, never by a translator.** For every family with `CanonicalizesInSql`, the translator emits `ValueSetSqlGuard.CanonicalUnion`/`CanonicalAdd`/`CanonicalIntersect`/`CanonicalExcept` and the guard's `CanonicalExpander` builds the subquery: it needs table aliases, and EF Core's alias pass (which runs after translation and before the guard) parses every alias as one letter and a number, while a translator has no `SqlAliasManager`. Keep `ORDER BY x, ordinality` with `DISTINCT ON`: it keeps the first copy of each value as `ValueSetCore` does (`1.0` vs `1.00`, `-0` vs `0`); a plain `DISTINCT` keeps any copy (seed `canonical-set-keeps-any-copy`). Drop NULL elements (`WHERE x IS NOT NULL`), and write the multiset form only where order and duplicates cannot change the answer. A family joins only if PostgreSQL orders its store type as the family's canonical comparer does; a wrapper arity relies on its element's `CompareTo` ordering as the primitive does (`docs/value-sets.md`). `CanonicalSetOperationParityTests` (integration) is the authority
- **Value sets β€” `ToRangeSet()` in SQL is built by `ValueSetSqlGuard` too, and per element it is the range this library stores for `[x,x]`.** The translator recognizes the bridge by its declaring class (`SetTypeRegistry.RegisterRangeBridgeExtensions`, never by the name alone) and emits `ValueSetSqlGuard.RangeBridge` inside `CASE WHEN set IS NULL THEN NULL`; the guard builds `COALESCE((SELECT range_agg(<range>(vrN.x, vrN.x, '[]')) FROM unnest(set) AS vrN(x) WHERE vrN.x IS NOT NULL), '{}')` (#487). Keep all three guards: without the `COALESCE` the empty set is NULL, without the `WHERE` a NULL element another tool wrote becomes `(,)`, the whole domain, and without the `CASE` a NULL set is `{}`. Where `[x,x]` has no stored form the query fails as storing it does: `int.MaxValue` and `long.MaxValue` raise `22003`, and are never written as `[max,)`, which loads as an unbounded range. A date at an extreme is the stored sentinel, so it stays apart from its neighbour until the row is read (`docs/architecture.md#domain-width-and-the-boundary`). A `YearMonthSet` element spans its month (`CoarseUpperBound`): 9999-12 ends at `infinity` while Npgsql's infinity conversions are on, and a non-finite date keeps `[x,x]`, because `-infinity + 1 month` is `-infinity`, an empty range that would drop the first month without an error. The reverse direction enumerates and stays in memory (#407). `RangeBridgeParityTests` (integration) is the authority, with `RangeBridgeInfinityDisabledTests` for the switch
- **Value sets β€” a text `Union`, `Add`, `Intersect` or `Except` is NOT canonical in SQL.** PostgreSQL sorts `text` by the database collation, so the translator emits `ValueSetSqlGuard.UnguardedUnion`/`UnguardedAdd`/`UnguardedIntersect`/`UnguardedExcept` and the guard builds each unsorted: `array_cat`, `array_cat` with a one-element array, or a filter of the first array. Only order- and multiplicity-insensitive uses may compose on such a value: `@>`, `<@`, `&&` (the proper subset/superset pair is written as `<@ AND NOT @>` for exactly that reason), `cardinality(…) = 0`, a null test, the outermost projection (materialization canonicalizes), and two the guard rewrites (#485): `cardinality` becomes `(SELECT count(DISTINCT x) FROM unnest(…))`, NULL over a NULL set, and `=`/`<>`/`NULLIF` with such a value on a side become mutual containment, `a @> b AND b @> a`. A stored-column `=` keeps `=` and its index. No `COLLATE "C"` anywhere: a collated operand turns a GIN-indexed `@>` into a sequential scan, and #483 rejects a collation on a string set column that may not compare bytes, so the column's own equality is byte equality. Since 9.0.0 everything else is refused on the **final SQL tree** by `ValueSetSqlGuard`, run from a decorator around the provider's `IRelationalParameterBasedSqlProcessorFactory` (every query, `ExecuteUpdate` and `ExecuteDelete` passes through it). It **fails closed**: only the guard builds the placeholders, so a `ReplaceService` that drops the decorator makes every server-side text operation fail on the server instead of silently skipping the refusals. Never emit `array_cat` directly, and never match it by name before the guard has run. The walker follows values *derived* from one β€” through `array_remove` (which preserves canonical form rather than establishing it), `CASE`, `COALESCE`, `NULLIF` and subquery/set-operation columns β€” and the expander recognizes the same set structurally plus the walker's derived columns; `GROUP BY`, `DISTINCT`, `ORDER BY`, deduplicating set operations, `IN` and `UPDATE` setters throw. Never go back to recognizing these in LINQ: the 8.0.0 guard matched `==` inside a list of operators and a projection, a ternary, a coalesce, `GroupBy`, `Distinct` and `ExecuteUpdate` all translated and answered wrongly. The same guard refuses `to_jsonb(<value set>)` in an `UPDATE` setter β€” `ExecuteUpdate` of a value set inside a JSON column, which writes a JSON array where the document holds the literal, after which the row no longer loads β€” keyed off the translated setter, so a join or `EF.Property` cannot bypass it. `UnionCanonicalityTests`, the text sweep in `CanonicalSetOperationParityTests` and `ExecuteUpdateJsonTests` (integration) assert results, not SQL. Do not "fix" text by sorting it in SQL: `ORDER BY` on `text` uses the database collation, not ordinal, so it would disagree with the client's canonical order β€” the same defect one layer down (#479 decides whether text moves to code point order and `COLLATE "C"`)
6 changes: 1 addition & 5 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,7 @@ Some calls answer differently: [Changed answers in 10.5.0](https://github.com/Ca

### Changed answers

- EF Core: a final `Select` of `ToRangeSet()` runs in the database, where it ran in memory and returned the range set. A set holding `int.MaxValue` or `long.MaxValue` fails there with `integer out of range`, and a few results at a date type's ends don't load or count one range more. Call `AsEnumerable()` first for the in-memory answer ([#487](https://github.com/CaffeinatedCoder/CodoMetis.ValueRanges/issues/487), [Migration](https://github.com/CaffeinatedCoder/CodoMetis.ValueRanges/blob/main/docs/migration.md#check-a-final-select-of-torangeset-at-the-ends-of-a-domain)).

### Added

- EF Core: `ToRangeSet()` on `Int32Set`, `Int64Set`, `DateSet`, `LocalDateSet` and `YearMonthSet` runs as SQL, so a set column can go under the range operators, as in `b.Days.ToRangeSet().IsContainedBy(b.Stay)` ([Ask a range question of a set](https://github.com/CaffeinatedCoder/CodoMetis.ValueRanges/blob/main/docs/efcore.md#ask-a-range-question-of-a-set-with-torangeset)).
- JSON: a property declared as `IRangeFactory<TRange, T>` or `IValueSetFactory<TSet, T>` is written as the range's literal or the set's array, where it was written as `{}` with no error. Reading into one still throws `NotSupportedException` ([#581](https://github.com/CaffeinatedCoder/CodoMetis.ValueRanges/issues/581), [Migration](https://github.com/CaffeinatedCoder/CodoMetis.ValueRanges/blob/main/docs/migration.md#check-json-for-a-property-declared-as-a-factory-interface)).

### Fixed

Expand Down
Loading
Loading