From 2e38c3445a2629f1b8c823ab1e47b90be48f0178 Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Tue, 1 Dec 2026 18:09:35 -0800 Subject: [PATCH] Add ToArrayAsync and ToImmutableArrayAsync on a DbDataReader Siblings of the transform form of `ToListAsync` on `DbDataReader`: each reads the remaining rows of the current result set through an asynchronous transform into pooled chunks and copies them once, into an array of exactly their number. On .NET 8 and later the immutable array wraps that array and is not copied again; on .NET Standard it is a copy. The three share one private core, specialized per result by a struct type argument (the build the mapped terminals use), so none has a closure. `ToListAsync` keeps its behavior, including the guards inside the returned task. Tests: every row in order and the exact length (none, one, a few, thousands), the null guards (in the returned task), a transform that throws and a cancel (the chain is parked again after each), for the three terminals; and bytes per call against an `ImmutableArray` builder of unknown capacity, with an explicit probe that prints the numbers. Co-Authored-By: Claude Sonnet 5.5 --- Source/Core/Extensions/DataReader.cs | 56 ++++++- Source/Core/PublicAPI.Unshipped.txt | 2 + .../DataReaderExtensionsTests.cs | 139 ++++++++++++++++++ .../ReaderCollectAllocationProbe.cs | 105 +++++++++++++ docsite/articles/release-notes.md | 1 + 5 files changed, 300 insertions(+), 3 deletions(-) create mode 100644 Tests/Open.Database.Extensions.Core.Tests/ReaderCollectAllocationProbe.cs diff --git a/Source/Core/Extensions/DataReader.cs b/Source/Core/Extensions/DataReader.cs index b58dec89..d883f00e 100644 --- a/Source/Core/Extensions/DataReader.cs +++ b/Source/Core/Extensions/DataReader.cs @@ -640,17 +640,67 @@ static async IAsyncEnumerable SelectAsyncCore( /// /// or is . /// - public static async ValueTask> ToListAsync(this DbDataReader reader, + public static ValueTask> ToListAsync(this DbDataReader reader, Func> transform, CancellationToken cancellationToken = default) + => CollectAsync, List>(reader, transform, cancellationToken); + + /// + /// Asynchronously iterates the remaining records of the current result set and returns the results of an asynchronous transform as an array. + /// + /// + /// The to read from. + /// + /// The asynchronous function to transform each into a result. + /// + /// + /// + /// A task that represents the asynchronous operation. + /// Its result is an array of exactly the transformed results. + /// + /// + /// or is . + /// + public static ValueTask ToArrayAsync(this DbDataReader reader, + Func> transform, CancellationToken cancellationToken = default) + => CollectAsync, T[]>(reader, transform, cancellationToken); + + /// + /// Asynchronously iterates the remaining records of the current result set and returns the results of an asynchronous transform as an immutable array. + /// + /// + /// On .NET 8 and later the immutable array wraps the array of the results, which is not copied again; + /// on .NET Standard it is a copy of it, as there is no way to wrap an array there. + /// + /// + /// The to read from. + /// + /// The asynchronous function to transform each into a result. + /// + /// + /// + /// A task that represents the asynchronous operation. + /// Its result is an immutable array of the transformed results. + /// + /// + /// or is . + /// + public static ValueTask> ToImmutableArrayAsync(this DbDataReader reader, + Func> transform, CancellationToken cancellationToken = default) + => CollectAsync, ImmutableArray>(reader, transform, cancellationToken); + + // The rows go into pooled chunks and are copied once into a result of exactly their number, as the mapped terminals do. + // The build is a struct type argument, so each result has its own code and none has a closure. + static async ValueTask CollectAsync(DbDataReader reader, + Func> transform, CancellationToken cancellationToken) + where TBuild : struct, IChainBuild { if (reader is null) throw new ArgumentNullException(nameof(reader)); if (transform is null) throw new ArgumentNullException(nameof(transform)); Contract.EndContractBlock(); - // The rows go into pooled chunks and are copied once into a list of exactly their number, as the mapped terminals do. using var chain = ChunkChain.Rent(Views.Defaults.Config); while (await reader.ReadAsync(cancellationToken).ConfigureAwait(false)) chain.Add(await transform(reader).ConfigureAwait(false)); - return chain.ToList(); + return default(TBuild).Build(chain); } /// diff --git a/Source/Core/PublicAPI.Unshipped.txt b/Source/Core/PublicAPI.Unshipped.txt index ca9ac00a..107b9b62 100644 --- a/Source/Core/PublicAPI.Unshipped.txt +++ b/Source/Core/PublicAPI.Unshipped.txt @@ -13,3 +13,5 @@ Open.Database.Extensions.MappedQueryWithTake.SequentialAccess() -> Open.Datab static Open.Database.Extensions.Synchronous.SyncCommandExtensions.ToDataTable(this System.Data.IDbCommand! command, System.Data.CommandBehavior behavior = System.Data.CommandBehavior.Default) -> System.Data.DataTable! *REMOVED*static Open.Database.Extensions.Synchronous.SyncCommandExtensions.ToDataTables(this System.Data.IDbCommand! command, System.Data.CommandBehavior behavior = System.Data.CommandBehavior.SequentialAccess) -> System.Collections.Generic.List! static Open.Database.Extensions.Synchronous.SyncCommandExtensions.ToDataTables(this System.Data.IDbCommand! command, System.Data.CommandBehavior behavior = System.Data.CommandBehavior.Default) -> System.Collections.Generic.List! +static Open.Database.Extensions.DataReaderExtensions.ToArrayAsync(this System.Data.Common.DbDataReader! reader, System.Func>! transform, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +static Open.Database.Extensions.DataReaderExtensions.ToImmutableArrayAsync(this System.Data.Common.DbDataReader! reader, System.Func>! transform, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask> diff --git a/Tests/Open.Database.Extensions.Core.Tests/DataReaderExtensionsTests.cs b/Tests/Open.Database.Extensions.Core.Tests/DataReaderExtensionsTests.cs index d47519ec..df19dc26 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/DataReaderExtensionsTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/DataReaderExtensionsTests.cs @@ -66,6 +66,145 @@ public static async Task ToListAsync_ReadsEveryRow_InOrder_IntoAListOfExactlyTha Assert.Equal(count, list.Capacity); } + static CancellationToken Ct => TestContext.Current.CancellationToken; + + static ValueTask Id(IDataRecord r) => new((int)r.GetValue(0)); + + [Theory] + [InlineData(0)] + [InlineData(1)] + [InlineData(5)] + [InlineData(2000)] + public static async Task ToArrayAsync_ReadsEveryRow_InOrder_IntoAnArrayOfExactlyThatLength(int count) + { + System.Data.Common.DbDataReader reader = FakeReader.CreateDb(["Id"], IdRows(count)); + + int[] array = await reader.ToArrayAsync(Id, Ct); + + Assert.Equal(Enumerable.Range(0, count), array); + } + + [Theory] + [InlineData(0)] + [InlineData(1)] + [InlineData(5)] + [InlineData(2000)] + public static async Task ToImmutableArrayAsync_ReadsEveryRow_InOrder_WrappingTheArray(int count) + { + System.Data.Common.DbDataReader reader = FakeReader.CreateDb(["Id"], IdRows(count)); + + ImmutableArray result = await reader.ToImmutableArrayAsync(Id, Ct); + + Assert.False(result.IsDefault); + Assert.Equal(Enumerable.Range(0, count), result); + // The array behind it is the one of the rows: exactly their number. + Assert.Equal(count, System.Runtime.InteropServices.ImmutableCollectionsMarshal.AsArray(result)!.Length); + } + + [Fact] + public static async Task TheCollectingTerminals_RejectANullReaderOrTransform() + { + System.Data.Common.DbDataReader reader = FakeReader.CreateDb(["Id"], IdRows(1)); + System.Data.Common.DbDataReader? none = null; + Func>? noTransform = null; + + // The calls are made as the arguments, outside any assert: one that threw at the call would fail the test. + static async Task Rejected(string parameter, ValueTask call) + { + ArgumentNullException e = await Assert.ThrowsAsync(async () => await call); + Assert.Equal(parameter, e.ParamName); + } + + await Rejected("reader", none!.ToListAsync(Id, Ct)); + await Rejected("reader", none!.ToArrayAsync(Id, Ct)); + await Rejected("reader", none!.ToImmutableArrayAsync(Id, Ct)); + await Rejected("transform", reader.ToListAsync(noTransform!, Ct)); + await Rejected("transform", reader.ToArrayAsync(noTransform!, Ct)); + await Rejected("transform", reader.ToImmutableArrayAsync(noTransform!, Ct)); + } + + // One row type for each of the next tests, so that nothing else rents or parks its chain. + sealed record ThrowRow(int Id); + + sealed record CancelRow(int Id); + + static object? ParkedChain() + => typeof(Open.Database.Extensions.Core.ChunkChain) + .GetField("_spare", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static)! + .GetValue(null); + + [Fact] + public static async Task TheCollectingTerminals_ATransformThatThrows_FaultsTheTask_AndGivesTheChainBack() + { + static async ValueTask Throws(IDataRecord r) + { + await Task.Yield(); + int id = (int)r.GetValue(0); + return id == 3 ? throw new InvalidOperationException("transform failed") : new ThrowRow(id); + } + + Assert.Null(ParkedChain()); + + for (int i = 0; i < 3; i++) + { + System.Data.Common.DbDataReader reader = FakeReader.CreateDb(["Id"], IdRows(10)); + Func call = i switch + { + 0 => async () => await reader.ToListAsync(Throws, Ct), + 1 => async () => await reader.ToArrayAsync(Throws, Ct), + _ => async () => await reader.ToImmutableArrayAsync(Throws, Ct), + }; + + InvalidOperationException e = await Assert.ThrowsAsync(async () => await call()); + + Assert.Equal("transform failed", e.Message); + // Disposed on the way out: the chain is parked again. + Assert.NotNull(ParkedChain()); + } + + // And the parked chain is the next call's: it still gives the right rows. + System.Data.Common.DbDataReader again = FakeReader.CreateDb(["Id"], IdRows(3)); + ThrowRow[] rows = await again.ToArrayAsync(static r => new ValueTask(new ThrowRow((int)r.GetValue(0))), Ct); + Assert.Equal([new ThrowRow(0), new ThrowRow(1), new ThrowRow(2)], rows); + } + + [Fact] + public static async Task TheCollectingTerminals_ACancel_StopsReading_AndGivesTheChainBack() + { + Assert.Null(ParkedChain()); + + for (int i = 0; i < 3; i++) + { + System.Data.Common.DbDataReader reader = FakeReader.CreateDb(["Id"], IdRows(10)); + // A provider's ReadAsync honors the token. + reader.ReadAsync(Arg.Any()).Returns(ci + => ci.Arg().IsCancellationRequested + ? Task.FromCanceled(ci.Arg()) + : Task.FromResult(reader.Read())); + + using var source = CancellationTokenSource.CreateLinkedTokenSource(Ct); + int transformed = 0; + ValueTask Transform(IDataRecord r) + { + if (++transformed == 3) source.Cancel(); + return new ValueTask(new CancelRow((int)r.GetValue(0))); + } + + CancellationToken token = source.Token; + Func call = i switch + { + 0 => async () => await reader.ToListAsync(Transform, token), + 1 => async () => await reader.ToArrayAsync(Transform, token), + _ => async () => await reader.ToImmutableArrayAsync(Transform, token), + }; + + await Assert.ThrowsAnyAsync(async () => await call()); + + Assert.Equal(3, transformed); + Assert.NotNull(ParkedChain()); + } + } + #if !DEBUG // The rows are collected in pooled chunks and copied once, so a call allocates the list and not the growth of one. [Fact] diff --git a/Tests/Open.Database.Extensions.Core.Tests/ReaderCollectAllocationProbe.cs b/Tests/Open.Database.Extensions.Core.Tests/ReaderCollectAllocationProbe.cs new file mode 100644 index 00000000..4c4ae7d0 --- /dev/null +++ b/Tests/Open.Database.Extensions.Core.Tests/ReaderCollectAllocationProbe.cs @@ -0,0 +1,105 @@ +using System.Data.Common; + +namespace Open.Database.Extensions.Tests; + +#nullable enable + +// Bytes per call of the reader's ToArrayAsync and ToImmutableArrayAsync (pooled chunks, one copy) +// against the same rows read into an ImmutableArray.Builder whose capacity is not known. +// A count of bytes, not a time. The reader is an in-memory DataTableReader, whose +// ReadAsync finishes at once and allocates nothing, so a thread-local counter sees everything. +// The read alone is measured too, so that what the rows themselves cost can be taken off. +// Run it by itself, in Release: dotnet test --filter-method "*Probe_BytesPerCall" with the Explicit run option. +[ExcludeFromCodeCoverage] +[Collection("Heap measurements")] +public sealed class ReaderCollectAllocationProbe(ITestOutputHelper output) +{ + const int Rounds = 15; + + static DataTable Table(int rows) + { + var table = new DataTable(); + table.Columns.Add("Id", typeof(int)); + for (int i = 0; i < rows; i++) table.Rows.Add(i); + return table; + } + + static ValueTask Id(IDataRecord r) => new(r.GetInt32(0)); + + // The smallest of several runs, each with a new reader made before the count starts. + static async Task Measure(DataTable table, Func call) + { + for (int i = 0; i < 20; i++) await call(table.CreateDataReader()); + + long best = long.MaxValue; + for (int i = 0; i < Rounds; i++) + { + DbDataReader reader = table.CreateDataReader(); + GC.Collect(); + GC.WaitForPendingFinalizers(); + long before = GC.GetAllocatedBytesForCurrentThread(); + await call(reader); + best = Math.Min(best, GC.GetAllocatedBytesForCurrentThread() - before); + } + + return best; + } + +#if !DEBUG + // The rows go into pooled chunks and are copied once, so a call allocates the result and not the growth of a builder. + [Theory] + [InlineData(1000)] + [InlineData(100_000)] + public async Task ToImmutableArrayAsync_AllocatesLessThanABuilderOfUnknownCapacity(int rows) + { + DataTable table = Table(rows); + + long chain = await Measure(table, async r + => GC.KeepAlive(await r.ToImmutableArrayAsync(Id, TestContext.Current.CancellationToken))); + long builder = await Measure(table, async r => + { + ImmutableArray.Builder b = ImmutableArray.CreateBuilder(); + while (await r.ReadAsync(TestContext.Current.CancellationToken)) b.Add(r.GetInt32(0)); + GC.KeepAlive(b.ToImmutable()); + }); + + Assert.True(chain < builder, $"{rows} rows: chain {chain} B, builder {builder} B."); + } +#endif + + [Fact(Explicit = true)] + public async Task Probe_BytesPerCall() + { + output.WriteLine("rows | read alone | ToImmutableArrayAsync | builder + ToImmutable | ToArrayAsync | List + ToArray | (bytes; net of the read alone in the next line)"); + foreach (int rows in new[] { 0, 1, 1000, 100_000 }) + { + DataTable table = Table(rows); + + long read = await Measure(table, async r => + { + int sum = 0; + while (await r.ReadAsync(TestContext.Current.CancellationToken)) sum += r.GetInt32(0); + GC.KeepAlive(sum); + }); + long chain = await Measure(table, async r + => GC.KeepAlive(await r.ToImmutableArrayAsync(Id, TestContext.Current.CancellationToken))); + long builder = await Measure(table, async r => + { + ImmutableArray.Builder b = ImmutableArray.CreateBuilder(); + while (await r.ReadAsync(TestContext.Current.CancellationToken)) b.Add(r.GetInt32(0)); + GC.KeepAlive(b.ToImmutable()); + }); + long array = await Measure(table, async r + => GC.KeepAlive(await r.ToArrayAsync(Id, TestContext.Current.CancellationToken))); + long list = await Measure(table, async r => + { + var l = new List(); + while (await r.ReadAsync(TestContext.Current.CancellationToken)) l.Add(r.GetInt32(0)); + GC.KeepAlive(l.ToArray()); + }); + + output.WriteLine($"{rows,7} | {read,9} | {chain,9} | {builder,9} | {array,9} | {list,9}"); + output.WriteLine($"{"net",7} | {"",9} | {chain - read,9} | {builder - read,9} | {array - read,9} | {list - read,9}"); + } + } +} diff --git a/docsite/articles/release-notes.md b/docsite/articles/release-notes.md index cbd7f19e..94330924 100644 --- a/docsite/articles/release-notes.md +++ b/docsite/articles/release-notes.md @@ -9,6 +9,7 @@ Version 11 is `11.0.0-rc.16`. For moving a 10.x codebase, read [Coming from earl - **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. - **Fixed: `CreateCommand` on a `SqlTransaction` that has no connection throws `InvalidOperationException`.** The SQL Server package threw `ArgumentNullException` named `connection`; it now reports "Transaction has no connection.", as the core package does. `CreateTextCommand` and `CreateStoredProcedureCommand` follow. +- **New: `ToArrayAsync` and `ToImmutableArrayAsync` on a `DbDataReader`.** Like `ToListAsync(transform)`, they read the remaining rows of the current result set through an asynchronous transform into pooled chunks and copy them once, into an array of exactly their number; on .NET 8 and later the immutable array wraps that array and does not copy it again (on .NET Standard it is a copy). ### Changes since rc.15