From 38e96d2bc6ed5c6b61f37c1be6bc466ac823894b Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Tue, 1 Dec 2026 13:07:09 -0800 Subject: [PATCH] Remove unused internals; a cancelled pooled all-columns read ends quietly Deletes code nothing calls, and tidies a few small things. No public API changes. - Removed: `ListSink`; the `ValueTask` overload of `CancelledAsFalse`; the non-generic `CancellationTokens.RunAsync`; `DbQueryBinding.MemberNames`; the view-level `WithConfig` on `MappedQuery`, `MappedQueryWithSkip` and `MappedQueryWithTake` (the core's and the command view's stay); the `readStarted` parameter of the private `AsAsyncEnumerableInternal` pair, which was always `false`; a no-op `Contract.EndContractBlock()` in an iterator; `TextNameCache.Names` (its two callers use the parser); the second copy of `Bare` in `NameSet`; the `partial` on `DataRecordExtensions`, which has no other part. - Tidied: the open-connection mask in `ExpressiveCommandBase` is `!NeedsOpen`, as everywhere else; an empty `PooledBuffer` is made by `CreateEmptyOwner()`; comments that described the code wrongly (the chunk shift is a bit shift, not doublings; the no-allocation note on `CancellationTokens.RunAsync`). - Fixed: the pooled all-columns form of `AsAsyncEnumerable(arrayPool)` did not pass its token to `ReadAsync` or treat a cancelled read as the end, as the three other forms do. A read the provider cancels now ends the enumeration quietly with the rows already yielded. A test pins it, with the token reaching every read. - Release notes: the cancel fix is under "Changes since rc.16". Core tests pass with the generator on and off, the samples pass, the VS solution build has no errors, and `dotnet format style` and `analyzers` at `--severity info` report nothing on every project. Co-Authored-By: Claude Sonnet 5.5 --- Source/Core/ChunkSizing.cs | 4 +-- Source/Core/Core/CancellationTokens.cs | 33 +---------------- Source/Core/Core/RowReader.cs | 7 ---- Source/Core/DbQueryBinding.cs | 13 +------ Source/Core/ExpressiveCommandBase.cs | 6 ++-- Source/Core/Extensions/DataReader.cs | 35 +++++++++---------- Source/Core/Extensions/DataRecord.cs | 2 +- Source/Core/Extensions/_.cs | 20 ----------- Source/Core/MappedQuery.cs | 17 --------- Source/Core/MappedViews.cs | 7 +++- Source/Core/NameSet.cs | 7 ++-- Source/Core/PooledBuffer.cs | 2 +- Source/Core/TextNameCache.cs | 5 --- .../DataReaderEdgeTests.cs | 34 ++++++++++++++++++ docsite/articles/release-notes.md | 1 + 15 files changed, 69 insertions(+), 124 deletions(-) diff --git a/Source/Core/ChunkSizing.cs b/Source/Core/ChunkSizing.cs index ead23bb5..7167dec5 100644 --- a/Source/Core/ChunkSizing.cs +++ b/Source/Core/ChunkSizing.cs @@ -52,7 +52,7 @@ internal sealed class ChunkSizes /// most 2^20. The default is 16. /// /// - /// The doublings per chunk of the chain: 1 to 4. The default is 1. + /// The bit shift per chunk of the chain (1 doubles, 2 quadruples), 1 to 4. The default is 1. /// /// /// The rows in the largest chunk of the chain: a power of two, at most 2^26. @@ -101,7 +101,7 @@ public ChunkSizes( /// Gets the number of rows in the first chunk of the collecting chain. public int CollectFirstRows { get; } - /// Gets the number of doublings per chunk of the chain. + /// Gets the bit shift per chunk of the chain (1 doubles, 2 quadruples). public int CollectShift { get; } /// Gets the number of rows in the largest chunk of the chain. diff --git a/Source/Core/Core/CancellationTokens.cs b/Source/Core/Core/CancellationTokens.cs index dec1e737..e2463198 100644 --- a/Source/Core/Core/CancellationTokens.cs +++ b/Source/Core/Core/CancellationTokens.cs @@ -63,7 +63,7 @@ public static ValueTask RunAsync( commandToken, callToken, out CancellationTokenSource? linked); - // When no linked source is needed there is no state machine and no allocation; a static lambda with a state keeps it that way for a call with at most one token. + // When no linked source is needed there is no state machine and no allocation. return linked is null ? start(state, token) : Linked(linked, token, state, start); @@ -78,35 +78,4 @@ static async ValueTask Linked( return await start(state, token).ConfigureAwait(false); } } - - /// - /// The type of the state. - /// A task that represents the call. - [SuppressMessage( - "Design", "CA1068:CancellationToken parameters must come last")] - public static ValueTask RunAsync( - CancellationToken commandToken, - CancellationToken callToken, - TState state, - Func start) - { - CancellationToken token = Combine( - commandToken, - callToken, - out CancellationTokenSource? linked); - return linked is null - ? start(state, token) - : Linked(linked, token, state, start); - - static async ValueTask Linked( - CancellationTokenSource linked, - CancellationToken token, - TState state, - Func start) - { - using (linked) - await start(state, token).ConfigureAwait(false); - } - } } diff --git a/Source/Core/Core/RowReader.cs b/Source/Core/Core/RowReader.cs index 529cc37e..909478ca 100644 --- a/Source/Core/Core/RowReader.cs +++ b/Source/Core/Core/RowReader.cs @@ -846,13 +846,6 @@ static ValueTask ReadRowAsync(DbDataReader reader, bool useReadAsync, Canc #endregion } -internal readonly struct ListSink(List list) : IRowSink -{ - public List List { get; } = list; - public void Add(T item) => List.Add(item); - public int Count => List.Count; -} - /// /// Makes the result of a collecting terminal from the rows in a chain. /// diff --git a/Source/Core/DbQueryBinding.cs b/Source/Core/DbQueryBinding.cs index 7b27cb6f..6ecf1c79 100644 --- a/Source/Core/DbQueryBinding.cs +++ b/Source/Core/DbQueryBinding.cs @@ -68,17 +68,6 @@ public static string ResolveDerived( return last.Real; } - /// - /// Gets the names of the members of an object. - /// - /// The type of the object. - /// The object. - /// The names of the members. - public static string[] MemberNames(T value) - => typeof(T) == typeof(object) - ? RuntimeParamSource.Of(value!.GetType()).Names - : ParamSource.Names; - /// /// Adds a parameter of a written or derived name. /// @@ -308,7 +297,7 @@ static bool Has(DbCommand command, string name) public static bool SameName(string a, string b) => Bare(a).Equals(Bare(b), StringComparison.OrdinalIgnoreCase); - static ReadOnlySpan Bare(string name) + internal static ReadOnlySpan Bare(string name) => name.Length > 0 && name[0] == '@' ? name.AsSpan(1) : name.AsSpan(); diff --git a/Source/Core/ExpressiveCommandBase.cs b/Source/Core/ExpressiveCommandBase.cs index 7508e53e..70d88d61 100644 --- a/Source/Core/ExpressiveCommandBase.cs +++ b/Source/Core/ExpressiveCommandBase.cs @@ -1050,7 +1050,7 @@ void Apply( // A member of an object that the procedure does not take is simply not sent; an argument named by the caller must match. if (p.FromObject) { names[i] = null; continue; } // the pooled slot holds whatever an earlier renter left: write it before it is read - throw NoMatch(expression, scan ? TextNameCache.Names(Command) : real!.Names); + throw NoMatch(expression, scan ? SqlTextParameters.Parse(Command) : real!.Names); } names[i] = name; @@ -1078,7 +1078,7 @@ void Apply( for (int j = i + 1; j < count; j++) { if (names[j] is { } second && DbQueryBinding.SameName(first, second)) - throw Collision(first, list[i], list[j], scan ? TextNameCache.Names(Command) : real?.Names ?? default); + throw Collision(first, list[i], list[j], scan ? SqlTextParameters.Parse(Command) : real?.Names ?? default); } } @@ -1312,7 +1312,7 @@ static ValueTask> EnsureOpenScopeUnlessOpenAsync( CancellationToken cancellationToken) { ConnectionState state = connection.State; - if ((state & (ConnectionState.Open | ConnectionState.Broken)) == ConnectionState.Open) + if (!ConnectionExtensions.NeedsOpen(state)) { return new ValueTask>( pool is null diff --git a/Source/Core/Extensions/DataReader.cs b/Source/Core/Extensions/DataReader.cs index f1abaf2a..b58dec89 100644 --- a/Source/Core/Extensions/DataReader.cs +++ b/Source/Core/Extensions/DataReader.cs @@ -308,8 +308,6 @@ public static IEnumerable Select( static async IAsyncEnumerable AsAsyncEnumerableCore(DbDataReader reader, [EnumeratorCancellation] CancellationToken cancellationToken) { - Contract.EndContractBlock(); - if (cancellationToken.IsCancellationRequested || !await reader.ReadAsync(cancellationToken).CancelledAsFalse().ConfigureAwait(false)) { @@ -329,8 +327,11 @@ static async IAsyncEnumerable AsAsyncEnumerableCore(DbDataReader reade static async IAsyncEnumerable AsAsyncEnumerableCore(DbDataReader reader, ArrayPool arrayPool, [EnumeratorCancellation] CancellationToken cancellationToken) { - if (cancellationToken.IsCancellationRequested || !await reader.ReadAsync().ConfigureAwait(false)) + if (cancellationToken.IsCancellationRequested + || !await reader.ReadAsync(cancellationToken).CancelledAsFalse().ConfigureAwait(false)) + { yield break; + } int fieldCount = reader.FieldCount; do @@ -339,7 +340,8 @@ static async IAsyncEnumerable AsAsyncEnumerableCore(DbDataReader reade reader.GetValues(row); yield return row; } - while (!cancellationToken.IsCancellationRequested && await reader.ReadAsync().ConfigureAwait(false)); + while (!cancellationToken.IsCancellationRequested + && await reader.ReadAsync(cancellationToken).CancelledAsFalse().ConfigureAwait(false)); } /// @@ -385,20 +387,19 @@ public static IAsyncEnumerable AsAsyncEnumerable( } static IAsyncEnumerable AsAsyncEnumerableInternal( - this DbDataReader reader, + DbDataReader reader, IEnumerable ordinals, - bool readStarted, CancellationToken cancellationToken) { return reader is null ? throw new ArgumentNullException(nameof(reader)) : ordinals is null ? throw new ArgumentNullException(nameof(ordinals)) - : AsAsyncEnumerableInternalCore(reader, ordinals, readStarted, cancellationToken); + : AsAsyncEnumerableInternalCore(reader, ordinals, cancellationToken); - static async IAsyncEnumerable AsAsyncEnumerableInternalCore(DbDataReader reader, IEnumerable ordinals, bool readStarted, [EnumeratorCancellation] CancellationToken cancellationToken) + static async IAsyncEnumerable AsAsyncEnumerableInternalCore(DbDataReader reader, IEnumerable ordinals, [EnumeratorCancellation] CancellationToken cancellationToken) { - if (!readStarted && (cancellationToken.IsCancellationRequested || !await reader.ReadAsync(cancellationToken).CancelledAsFalse().ConfigureAwait(false))) + if (cancellationToken.IsCancellationRequested || !await reader.ReadAsync(cancellationToken).CancelledAsFalse().ConfigureAwait(false)) yield break; IList o = ordinals as IList ?? ordinals.ToArray(); @@ -428,9 +429,8 @@ static async IAsyncEnumerable AsAsyncEnumerableInternalCore(DbDataRead } static IAsyncEnumerable AsAsyncEnumerableInternal( - this DbDataReader reader, + DbDataReader reader, IEnumerable ordinals, - bool readStarted, ArrayPool arrayPool, CancellationToken cancellationToken) { @@ -439,17 +439,16 @@ static IAsyncEnumerable AsAsyncEnumerableInternal( Debug.Assert(arrayPool is not null); Contract.EndContractBlock(); - return AsAsyncEnumerableInternalCore(reader, ordinals, readStarted, arrayPool, cancellationToken); + return AsAsyncEnumerableInternalCore(reader, ordinals, arrayPool, cancellationToken); static async IAsyncEnumerable AsAsyncEnumerableInternalCore( DbDataReader reader, IEnumerable ordinals, - bool readStarted, ArrayPool arrayPool, [EnumeratorCancellation] CancellationToken cancellationToken) { - if (!readStarted && (cancellationToken.IsCancellationRequested - || !await reader.ReadAsync(cancellationToken).CancelledAsFalse().ConfigureAwait(false))) + if (cancellationToken.IsCancellationRequested + || !await reader.ReadAsync(cancellationToken).CancelledAsFalse().ConfigureAwait(false)) { yield break; } @@ -484,7 +483,7 @@ static async IAsyncEnumerable AsAsyncEnumerableInternalCore( /// /// public static IAsyncEnumerable AsAsyncEnumerable(this DbDataReader reader, IEnumerable ordinals, CancellationToken cancellationToken = default) - => AsAsyncEnumerableInternal(reader, ordinals, false, cancellationToken); + => AsAsyncEnumerableInternal(reader, ordinals, cancellationToken); /// /// Asynchronously enumerates the remaining records of the current result set of a as arrays of values; @@ -515,8 +514,8 @@ public static IAsyncEnumerable AsAsyncEnumerable(this DbDataReader rea /// public static IAsyncEnumerable AsAsyncEnumerable(this DbDataReader reader, IEnumerable ordinals, ArrayPool? arrayPool, CancellationToken cancellationToken = default) => arrayPool is null - ? AsAsyncEnumerableInternal(reader, ordinals, false, cancellationToken) - : AsAsyncEnumerableInternal(reader, ordinals, false, arrayPool, cancellationToken); + ? AsAsyncEnumerableInternal(reader, ordinals, cancellationToken) + : AsAsyncEnumerableInternal(reader, ordinals, arrayPool, cancellationToken); /// /// Asynchronously and lazily transforms each remaining record of a through a function. diff --git a/Source/Core/Extensions/DataRecord.cs b/Source/Core/Extensions/DataRecord.cs index d9e71e71..560602a3 100644 --- a/Source/Core/Extensions/DataRecord.cs +++ b/Source/Core/Extensions/DataRecord.cs @@ -6,7 +6,7 @@ /// /// These methods read the record's current row and result-set metadata; they never advance the reader. Methods that return a lazy read from the record while they are enumerated, so enumerate them before the reader advances or is disposed. Methods that return an array, , or dictionary read everything before they return. Null database values are represented as , except where noted. /// -public static partial class DataRecordExtensions +public static class DataRecordExtensions { /// /// Lazily enumerates the column names of the current result set in ordinal order. diff --git a/Source/Core/Extensions/_.cs b/Source/Core/Extensions/_.cs index ab344021..52cb9e4f 100644 --- a/Source/Core/Extensions/_.cs +++ b/Source/Core/Extensions/_.cs @@ -6,26 +6,6 @@ public static partial class CoreExtensions { - internal static ValueTask CancelledAsFalse(this ValueTask task) - { - if (task.IsCompletedSuccessfully) - return task; - - return CancelledAsFalseCore(task); - - static async ValueTask CancelledAsFalseCore(ValueTask task) - { - try - { - return await task.ConfigureAwait(false); - } - catch (OperationCanceledException) - { - return false; - } - } - } - internal static async ValueTask CancelledAsFalse(this Task task) { try diff --git a/Source/Core/MappedQuery.cs b/Source/Core/MappedQuery.cs index 3f77304e..91baf474 100644 --- a/Source/Core/MappedQuery.cs +++ b/Source/Core/MappedQuery.cs @@ -1268,15 +1268,6 @@ public readonly record struct MappedQuery public MappedQuery UsePool(ArrayPool pool, bool clearOnReturn) => new(_core.WithPool(pool, clearOnReturn)); - /// - /// Returns the query with a whole configuration - /// (pool, clear, chunk sizes, bin), for a test or a benchmark. - /// - /// The configuration to use. - /// A copy of the query that uses . - internal MappedQuery WithConfig(ChunkConfig config) - => new(_core.WithConfig(config)); - /// Gets the query as a call when it was made from a definition. internal bool TryGetCall(out DbQueryCall call) => _core.TryGetCall(out call); @@ -1781,10 +1772,6 @@ public readonly record struct MappedQueryWithSkip public MappedQueryWithSkip UsePool(ArrayPool pool, bool clearOnReturn) => new(_core.WithPool(pool, clearOnReturn)); - /// - internal MappedQueryWithSkip WithConfig(ChunkConfig config) - => new(_core.WithConfig(config)); - internal List ToList() => _core.ToList(); /// public ValueTask> ToListAsync(CancellationToken cancellationToken = default) => _core.ToListAsync(cancellationToken); @@ -1924,10 +1911,6 @@ public readonly record struct MappedQueryWithTake public MappedQueryWithTake UsePool(ArrayPool pool, bool clearOnReturn) => new(_core.WithPool(pool, clearOnReturn)); - /// - internal MappedQueryWithTake WithConfig(ChunkConfig config) - => new(_core.WithConfig(config)); - internal List ToList() => _core.ToList(); /// public ValueTask> ToListAsync(CancellationToken cancellationToken = default) => _core.ToListAsync(cancellationToken); diff --git a/Source/Core/MappedViews.cs b/Source/Core/MappedViews.cs index 70b1f86a..805e1fd4 100644 --- a/Source/Core/MappedViews.cs +++ b/Source/Core/MappedViews.cs @@ -894,7 +894,12 @@ public MappedCommand SequentialAccess() public MappedCommand UsePool(ArrayPool pool, bool clearOnReturn) => new(_core.WithPool(pool, clearOnReturn)); - /// + /// + /// Returns the query with a whole configuration + /// (pool, clear, chunk sizes, bin), for a test or a benchmark. + /// + /// The configuration to use. + /// A copy of the query that uses . internal MappedCommand WithConfig(ChunkConfig config) => new(_core.WithConfig(config)); diff --git a/Source/Core/NameSet.cs b/Source/Core/NameSet.cs index d6f53750..d502a5f8 100644 --- a/Source/Core/NameSet.cs +++ b/Source/Core/NameSet.cs @@ -72,18 +72,15 @@ sealed class BareComparer : IEqualityComparer { internal static readonly BareComparer Instance = new(); - static ReadOnlySpan Bare(string name) - => name.Length > 0 && name[0] == '@' ? name.AsSpan(1) : name.AsSpan(); - public bool Equals(string? x, string? y) - => Bare(x!).Equals(Bare(y!), StringComparison.OrdinalIgnoreCase); + => DbQueryBinding.Bare(x!).Equals(DbQueryBinding.Bare(y!), StringComparison.OrdinalIgnoreCase); public int GetHashCode(string obj) { unchecked { int h = 17; - foreach (char c in Bare(obj)) h = h * 31 + char.ToUpperInvariant(c); + foreach (char c in DbQueryBinding.Bare(obj)) h = h * 31 + char.ToUpperInvariant(c); return h; } } diff --git a/Source/Core/PooledBuffer.cs b/Source/Core/PooledBuffer.cs index 316b9fc2..42a04522 100644 --- a/Source/Core/PooledBuffer.cs +++ b/Source/Core/PooledBuffer.cs @@ -254,7 +254,7 @@ static PooledBuffer Create(ReadOnlySpan rows, ChunkConfig config) { System.Diagnostics.Debug.Assert(rows.Length <= MaxFromRows); - if (rows.IsEmpty) return new([], 0, 1); + if (rows.IsEmpty) return CreateEmptyOwner(); // One array that is one first chunk: row i is at i, so the indexer always lands in chunk 0. int firstRows = 1; diff --git a/Source/Core/TextNameCache.cs b/Source/Core/TextNameCache.cs index c4599565..2cefca8b 100644 --- a/Source/Core/TextNameCache.cs +++ b/Source/Core/TextNameCache.cs @@ -43,11 +43,6 @@ internal static bool HasMarkers(string text) return SqlTextParameters.NextMarker(text, ref position, out _, out _); } - /// Gets the distinct markers of the text, for a message. - /// The SQL text. - /// The markers, each with its @. - internal static ImmutableArray Names(string text) => SqlTextParameters.Parse(text); - /// /// Gets the marker (with its @) that the argument expression stands for, as the text spells it, or when none fits. /// diff --git a/Tests/Open.Database.Extensions.Core.Tests/DataReaderEdgeTests.cs b/Tests/Open.Database.Extensions.Core.Tests/DataReaderEdgeTests.cs index 0b56466e..b253811b 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/DataReaderEdgeTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/DataReaderEdgeTests.cs @@ -690,6 +690,40 @@ public static async Task AsAsyncEnumerable_Cancelled_EndsQuietlyWithTheRowsReadS Assert.InRange(rows.Count, cancelAtRead, 9); } + /// A reader whose provider cancels the read it is in, as one does when the command is cancelled. + sealed class CancellingReader(int rows, int cancelAtRead) + : TypedReader([("Id", typeof(int))], [.. Enumerable.Range(1, rows).Select(i => (object?[])[i])]) + { + public List Tokens { get; } = []; + + public override Task ReadAsync(CancellationToken cancellationToken) + { + Tokens.Add(cancellationToken); + if (Tokens.Count == cancelAtRead) + return Task.FromException(new OperationCanceledException(cancellationToken)); + + return Task.FromResult(base.Read()); + } + } + + // A read the provider cancels ends the enumeration quietly, whether or not the rows are pooled, and the token reaches every read. + [Theory] + [InlineData(false)] + [InlineData(true)] + public static async Task AsAsyncEnumerable_AllColumns_AReadTheProviderCancels_EndsQuietlyWithTheRowsReadSoFar(bool usePool) + { + using var cts = new CancellationTokenSource(); + var reader = new CancellingReader(5, cancelAtRead: 3); + + List rows = await Collect(usePool + ? reader.AsAsyncEnumerable(new SizedPool(), cts.Token) + : reader.AsAsyncEnumerable(cts.Token)); + + Assert.Equal([1, 2], [.. rows.Select(r => r[0])]); + Assert.Equal(3, reader.Tokens.Count); + Assert.All(reader.Tokens, t => Assert.Equal(cts.Token, t)); + } + // ---- IterateWhile ---- [Theory] diff --git a/docsite/articles/release-notes.md b/docsite/articles/release-notes.md index 0d13837a..390d8646 100644 --- a/docsite/articles/release-notes.md +++ b/docsite/articles/release-notes.md @@ -7,6 +7,7 @@ Version 11 is `11.0.0-rc.16`. For moving a 10.x codebase, read [Coming from earl ### Changes since rc.16 - **Generated row readers for `DbQuery` too.** A plain `Map()` on a `DbQuery`, a `DbQuery` or a query bound with `Using` now gets its row reader written at build time, as on a command or a reader; before, it used the runtime map. The runtime map's conversions are therefore no longer applied there: see [Generated readers](mapping.md#generated-readers) for the differences and the switch. +- **Fixed: a cancel during `AsAsyncEnumerable(pool)`.** On a `DbDataReader`, `AsAsyncEnumerable(arrayPool)` with a pool (the form that reads every column) did not pass its token to `ReadAsync`, so a read the provider cancelled threw out of the enumeration. It now ends the enumeration quietly with the rows already yielded, as the other forms do. ### Changes since rc.15