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 @@ -13,6 +13,10 @@ has the rules.

## [9.1.0] — 2026-10-17

### Fixed

- Literals: whitespace at either end of a quoted or escaped range bound is dropped, as in PostgreSQL, so `[" 2026-01-01",2026-02-01)` parses, where it threw `FormatException` ([Literals](https://github.com/CaffeinatedCoder/CodoMetis.ValueRanges/blob/main/docs/serialization.md)).

## [9.0.0] — 2026-10-11

Nothing was removed or renamed. What existing calls write, accept and translate changed, and the compiler can't show you where: [Migration from v8.x](https://github.com/CaffeinatedCoder/CodoMetis.ValueRanges/blob/main/docs/migration.md#migration-from-v8x).
Expand Down
7 changes: 6 additions & 1 deletion docs/serialization.md
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,8 @@ A bound is read the way PostgreSQL's `range_in` reads it:
- **A doubled quote** inside a quoted section is a literal `"`.
- **A backslash** takes the next character literally, inside quotes or out, so `[\1,5)` is
`[1,5)`.
- **Whitespace** around the unquoted part of a bound is dropped.
- **Whitespace at either end of a bound** is dropped, inside quotes or out. So
`[" 2026-01-01",2026-02-01)` is `[2026-01-01,2026-02-01)`.

Good to know:

Expand All @@ -205,6 +206,10 @@ Good to know:
(`FormatException`), as PostgreSQL does with `invalid input syntax for type integer: ""`.
- **Before 9.0, an empty quoted bound read as infinite.** `["",5)` read as `(,4]`, and `("","")`
as `(,)`.
- **Only ASCII whitespace is dropped:** space, tab, newline, carriage return, vertical tab and form
feed. A no-break space stays in the bound, so the bound fails, as it does in PostgreSQL.
- **Before 9.1, whitespace inside quotes was kept.** `[" 2026-01-01",2026-02-01)` failed
(`FormatException`), where PostgreSQL reads it.

### Bind a range from configuration

Expand Down
4 changes: 3 additions & 1 deletion src/CodoMetis.ValueRanges.NodaTime/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ covers all four packages, which share one version number and release together.

## [9.1.0] — 2026-10-17

No change in this package.
### Fixed

- Literals: whitespace at either end of a quoted or escaped range bound is dropped, as in PostgreSQL, so `[" 2026-01-01",2026-02-01)` parses, where it threw `FormatException` ([Literals](https://github.com/CaffeinatedCoder/CodoMetis.ValueRanges/blob/main/docs/serialization.md)).

## [9.0.0] — 2026-10-11

Expand Down
4 changes: 3 additions & 1 deletion src/CodoMetis.ValueRanges/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ covers all four packages, which share one version number and release together.

## [9.1.0] — 2026-10-17

No change in this package.
### Fixed

- Literals: whitespace at either end of a quoted or escaped range bound is dropped, as in PostgreSQL, so `[" 2026-01-01",2026-02-01)` parses, where it threw `FormatException` ([Literals](https://github.com/CaffeinatedCoder/CodoMetis.ValueRanges/blob/main/docs/serialization.md)).

## [9.0.0] — 2026-10-11

Expand Down
34 changes: 12 additions & 22 deletions src/CodoMetis.ValueRanges/Internals/RangeFormat.cs
Original file line number Diff line number Diff line change
Expand Up @@ -71,20 +71,19 @@ internal static TRange Parse<TRange, T>(ReadOnlySpan<char> s, IFormatProvider? p
/// Within a bound, a double quote opens or closes a quoted section anywhere (<c>"1"2</c> is
/// <c>12</c>), a doubled quote inside one is a literal quote, and a backslash takes the next
/// character literally, inside quotes or out. An unquoted, unescaped comma, <c>)</c> or <c>]</c>
/// ends the bound. Whitespace around the unquoted part is dropped: PostgreSQL hands it to the
/// element's input function, and every input function behind these types ignores it. That is
/// ASCII whitespace only (<see cref="LiteralWhiteSpace"/>): a no-break space stays in the bound,
/// where the element parser refuses it as PostgreSQL's does.
/// ends the bound. Whitespace at either end of the bound text is dropped once the bound is read,
/// whether it was quoted, escaped or neither: PostgreSQL keeps it all and hands it to the
/// element's input function, and every input function behind these types strips it (measured
/// for all seven range types, #45). That is ASCII whitespace only (<see cref="LiteralWhiteSpace"/>):
/// a no-break space stays in the bound, where the element parser refuses it as PostgreSQL's does.
/// Until 9.1.0 only unquoted whitespace was dropped, so <c>[" 2026-01-01",2026-02-01)</c> threw.
/// </para>
/// </remarks>
private static string? ScanBound(ReadOnlySpan<char> inner, ref int position, ReadOnlySpan<char> literal)
{
var start = position;
var sb = new StringBuilder();

// The length of the text up to its last character that is not unquoted whitespace.
var significant = 0;
var inQuotes = false;
var start = position;
var sb = new StringBuilder();
var inQuotes = false;

while (position < inner.Length && (inQuotes || inner[position] is not (',' or ')' or ']')))
{
Expand All @@ -96,34 +95,26 @@ internal static TRange Parse<TRange, T>(ReadOnlySpan<char> s, IFormatProvider? p
throw new FormatException($"The input string '{LiteralExcerpt.Of(literal)}' is not a valid range literal: unterminated escape.");

sb.Append(inner[position++]);
significant = sb.Length;
}
else if (c == '"')
{
if (!inQuotes)
{
inQuotes = true;
significant = sb.Length;
inQuotes = true;
}
else if (position < inner.Length && inner[position] == '"')
{
sb.Append('"');
significant = sb.Length;
position++;
}
else
{
inQuotes = false;
}
}
else if (inQuotes || !LiteralWhiteSpace.Is(c))
else
{
sb.Append(c);
significant = sb.Length;
}
else if (sb.Length > 0 || significant > 0)
{
sb.Append(c); // inner whitespace; dropped below if nothing significant follows
}
}

Expand All @@ -132,8 +123,7 @@ internal static TRange Parse<TRange, T>(ReadOnlySpan<char> s, IFormatProvider? p

if (position == start) return null;

sb.Length = significant;
return sb.ToString();
return LiteralWhiteSpace.Trim(sb.ToString()).ToString();
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,9 @@ namespace CodoMetis.ValueRanges.Conventions.Tests;
/// Every range type reads a bound as PostgreSQL's <c>range_in</c> does: only an <em>absent</em> bound
/// is infinite; a quoted <c>""</c> or a bound of only whitespace is a value — one no element type here
/// accepts; quotes may wrap any part of a bound and a backslash escapes the next character, inside
/// quotes or out. Swept through <c>Parse</c>, <c>TryParse</c>, the span overload, JSON, the
/// <c>TypeConverter</c> and the multirange literal.
/// quotes or out; ASCII whitespace at either end of a bound is stripped, quoted or not. Swept through
/// <c>Parse</c>, <c>TryParse</c>, the span overload, JSON, the <c>TypeConverter</c> and the
/// multirange literal.
/// </summary>
/// <remarks>
/// <para>
Expand Down Expand Up @@ -82,18 +83,36 @@ private static IEnumerable<string> Failures<TRange, T>()
// Whitespace around an unquoted bound is not part of it for any element type here.
Reads($"[ {lo} , {hi} )", finite);

// Nor is ASCII whitespace at either end of a quoted or escaped bound: range_in keeps it and
// every element input function behind these types strips it (#45, measured on PostgreSQL 17).
foreach (var ws in AsciiWhiteSpace)
{
Reads($"[\"{ws}{lo}\",\"{hi}{ws}\")", finite);
Reads($"[\"{ws}{lo}{ws}\",{hi})", finite);
Reads($"[\\{ws}{lo},{hi}\\{ws})", finite);
Reads($"[ \"{ws}{lo}\" ,{hi})", finite);
}

// Structure PostgreSQL refuses: a second comma, a closing bracket inside a bound, an
// unterminated quote or escape, Unicode whitespace where only ASCII whitespace is skipped.
foreach (var literal in new[]
{
$"[{lo},{hi},{hi})", $"[{lo}),{hi})", $"[{lo}],{hi})", $"[\"{lo},{hi})", $"[{lo},{hi}\\)",
// Only ASCII whitespace is skipped, as in PostgreSQL: a no-break space is bound text.
$"[\u00A0{lo},{hi})", $"\u00A0[{lo},{hi})"
// Only ASCII whitespace is skipped, as in PostgreSQL: a no-break space is bound text,
// quoted or not.
$"[\u00A0{lo},{hi})", $"\u00A0[{lo},{hi})", $"[\"\u00A0{lo}\",{hi})", $"[{lo},\"{hi}\u2003\")"
})
{
Refused(literal);
}

// A quoted or escaped bound of only whitespace is present and empty once stripped.
foreach (var ws in AsciiWhiteSpace)
{
Refused($"[\"{ws}\",{hi})");
Refused($"[{lo},\\{ws})");
}

return failures;

void Refused(string literal)
Expand Down Expand Up @@ -147,5 +166,8 @@ void Reads(string literal, TRange expected)
}
}

/// <summary>The whitespace PostgreSQL's element input functions strip: <c>isspace</c> in the C locale.</summary>
private static readonly string[] AsciiWhiteSpace = [" ", "\t", "\n", "\r", "\v", "\f"];

private static string EscapeEach(string text) => string.Concat(text.Select(c => $"\\{c}"));
}
Original file line number Diff line number Diff line change
Expand Up @@ -46,12 +46,31 @@ public sealed class LiteralGrammarParityTests
[
"[2024-01-01,2024-02-01)", "[\"2024-01-01\",\"2024-02-01\")", "[\"\",2024-02-01)", "[ ,2024-02-01)",
@"[2024\-01\-01,2024-02-01)", "(,infinity)", "[-infinity,2024-01-01)",
// Whitespace around an unquoted bound is the range grammar's to skip. Inside quotes it reaches
// the element, where PostgreSQL's date_in trims it and the strict ISO grammar refuses it —
// deliberately, and loudly (TemporalLiteralGrammarTests.Date_Rejects), so it is not listed.
"[ 2024-01-01 , 2024-02-01 )", " [2024-01-01,2024-02-01) "
"[ 2024-01-01 , 2024-02-01 )", " [2024-01-01,2024-02-01) ", "[\" 2024-01-01\",2024-02-01)"
];

/// <summary>
/// Each range type with a lower and upper bound text its element parser and PostgreSQL's both
/// read. The server's output goes back through the same parser, so the comparison is by value.
/// </summary>
private static readonly (string Type, string Low, string High, Func<string, string> Client)[] BoundWhitespaceTypes =
[
("int4range", "1", "5", l => Int32Range.TryParse(l, CultureInfo.InvariantCulture, out var r) ? r.ToString() : "refused"),
("int8range", "1", "5", l => Int64Range.TryParse(l, CultureInfo.InvariantCulture, out var r) ? r.ToString() : "refused"),
("numrange", "1.5", "5", l => DecimalRange.TryParse(l, CultureInfo.InvariantCulture, out var r) ? r.ToString() : "refused"),
("daterange", "2026-01-01", "2026-02-01", l => DateRange.TryParse(l, CultureInfo.InvariantCulture, out var r) ? r.ToString() : "refused"),
("daterange", "-infinity", "2026-02-01", l => DateRange.TryParse(l, CultureInfo.InvariantCulture, out var r) ? r.ToString() : "refused"),
("tsrange", "2026-01-01 10:00:00", "2026-02-01 00:00:00", l => DateTimeRange.TryParse(l, CultureInfo.InvariantCulture, out var r) ? r.ToString() : "refused"),
("tstzrange", "2026-01-01 10:00:00+00", "2026-02-01 00:00:00+00", l => DateTimeOffsetRange.TryParse(l, CultureInfo.InvariantCulture, out var r) ? r.ToString() : "refused"),
("timerange", "09:00:00", "17:00:00", l => TimeRange.TryParse(l, CultureInfo.InvariantCulture, out var r) ? r.ToString() : "refused"),
("daterange", "2026-01-01", "2026-02-01", l => LocalDateRange.TryParse(l, CultureInfo.InvariantCulture, out var r) ? r.ToString() : "refused"),
("tsrange", "2026-01-01 10:00:00", "2026-02-01 00:00:00", l => LocalDateTimeRange.TryParse(l, CultureInfo.InvariantCulture, out var r) ? r.ToString() : "refused"),
("tstzrange", "2026-01-01 10:00:00+00", "2026-02-01 00:00:00+00", l => InstantRange.TryParse(l, CultureInfo.InvariantCulture, out var r) ? r.ToString() : "refused")
];

/// <summary>ASCII whitespace PostgreSQL strips, and two Unicode spaces it does not.</summary>
private static readonly string[] BoundWhiteSpace = [" ", "\t", "\n", "\r", "\v", "\f", "\u00A0", "\u2003"];

private static readonly string[] Int4MultirangeLiterals =
[
"{[1,5),[7,9)}", "{}", "{ [1,5) , [7,9) }", "{[\"\",5)}", "{[1,5),[\"\",9)}", "{[\"1\",\"5\")}", "{ [1,5)}"
Expand Down Expand Up @@ -116,27 +135,61 @@ await Compare("int4multirange", Int4MultirangeLiterals,

Assert.IsEmpty(failures, "Range literals read differently:\n" + string.Join("\n", failures));

async Task Compare(string type, string[] literals, Func<string, string> client)
Task Compare(string type, string[] literals, Func<string, string> client)
=> CompareRangeLiterals(connection, type, literals, client, failures);
}

/// <summary>
/// Whitespace at either end of a quoted or escaped bound, and a bound of only whitespace, for
/// every range type: PostgreSQL's <c>range_in</c> keeps it in the bound and the element input
/// function decides (#45). Until 9.1.0 the library refused <c>[" 2026-01-01",2026-02-01)</c>,
/// which PostgreSQL reads as <c>[2026-01-01,2026-02-01)</c>.
/// </summary>
[TestMethod]
public async Task BoundWhitespace_ReadsAsPostgresReadsIt()
{
ContainerLifecycle.RequireDatabase();
await using var connection = new NpgsqlConnection(ContainerLifecycle.ConnectionString);
await connection.OpenAsync();

var failures = new List<string>();

foreach (var (type, lo, hi, client) in BoundWhitespaceTypes)
{
foreach (var literal in literals)
var literals = BoundWhiteSpace.SelectMany(ws => new[]
{
string server;
try
{
// Compared as values, not text: the library writes a discrete range closed
// ([1,4] for PostgreSQL's [1,5)) and an infinite date as MaxValue, so the
// server's canonical output goes through the same parser.
server = client((await ScalarAsync<string>(connection, $"SELECT $1::{type}::text", literal))!);
}
catch (PostgresException)
{
server = "refused";
}
$"[\"{ws}{lo}\",{hi})", $"[\"{lo}{ws}\",{hi})", $"[\"{ws}{lo}{ws}\",\"{ws}{hi}{ws}\")",
$"[\\{ws}{lo},{hi})", $"[{lo}\\{ws},{hi})", $"[ \"{ws}{lo}\" ,{hi})",
$"[\"{ws}\",{hi})", $"[{lo},\"{ws}{ws}\")", $"[\\{ws},{hi})"
}).ToArray();

await CompareRangeLiterals(connection, type, literals, client, failures);
}

var mine = client(literal);
if (mine != server)
failures.Add($" {type} {Show(literal)}: library {mine}, PostgreSQL {server}");
Assert.IsEmpty(failures, "Bound whitespace read differently:\n" + string.Join("\n", failures));
}

private static async Task CompareRangeLiterals(
NpgsqlConnection connection, string type, string[] literals, Func<string, string> client, List<string> failures)
{
foreach (var literal in literals)
{
string server;
try
{
// Compared as values, not text: the library writes a discrete range closed
// ([1,4] for PostgreSQL's [1,5)) and an infinite date as MaxValue, so the
// server's canonical output goes through the same parser.
server = client((await ScalarAsync<string>(connection, $"SELECT $1::{type}::text", literal))!);
}
catch (PostgresException)
{
server = "refused";
}

var mine = client(literal);
if (mine != server)
failures.Add($" {type} {Show(literal)}: library {mine}, PostgreSQL {server}");
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -170,4 +170,28 @@ public void TryParse_ValidLiteral_ReturnsTrue()
Assert.IsTrue(LocalDateRange.TryParse("[2025-01-01,2025-01-31]", null, out var range));
Assert.AreEqual("[2025-01-01,2025-01-31]", range.ToString());
}

/// <summary>
/// Whitespace at either end of a quoted bound is stripped for every NodaTime range type, as
/// PostgreSQL strips it (#45); a no-break space is not.
/// </summary>
[TestMethod]
public void Parse_QuotedBoundWithSurroundingWhitespace_ReadsTheTrimmedBound()
{
Assert.AreEqual(
LocalDateRange.CreateFinite(new LocalDate(2026, 1, 1), new LocalDate(2026, 2, 1), endInclusive: false),
LocalDateRange.Parse("[\" 2026-01-01\",\"2026-02-01\t\")", null));
Assert.AreEqual(
LocalDateTimeRange.CreateFinite(new LocalDateTime(2026, 1, 1, 10, 0), new LocalDateTime(2026, 2, 1, 0, 0), endInclusive: false),
LocalDateTimeRange.Parse("[\" 2026-01-01 10:00:00\",2026-02-01T00:00:00)", null));
Assert.AreEqual(
InstantRange.CreateFinite(Instant.FromUtc(2026, 1, 1, 10, 0), Instant.FromUtc(2026, 2, 1, 0, 0), endInclusive: false),
InstantRange.Parse("[\"\n2026-01-01T10:00:00Z \",2026-02-01T00:00:00Z)", null));
Assert.AreEqual(
YearMonthRange.CreateFinite(new YearMonth(2026, 1), new YearMonth(2026, 3), endInclusive: false),
YearMonthRange.Parse("[\" 2026-01\",2026-03)", null));

Assert.ThrowsExactly<FormatException>(() => LocalDateRange.Parse("[\"\u00A02026-01-01\",2026-02-01)", null));
Assert.ThrowsExactly<FormatException>(() => InstantRange.Parse("[\" \",2026-02-01T00:00:00Z)", null));
}
}
Loading