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
56 changes: 53 additions & 3 deletions Source/Core/Extensions/DataReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -640,17 +640,67 @@ static async IAsyncEnumerable<T> SelectAsyncCore(
/// <exception cref="ArgumentNullException">
/// <paramref name="reader"/> or <paramref name="transform"/> is <see langword="null"/>.
/// </exception>
public static async ValueTask<List<T>> ToListAsync<T>(this DbDataReader reader,
public static ValueTask<List<T>> ToListAsync<T>(this DbDataReader reader,
Func<IDataRecord, ValueTask<T>> transform, CancellationToken cancellationToken = default)
=> CollectAsync<T, ListBuild<T>, List<T>>(reader, transform, cancellationToken);

/// <summary>
/// Asynchronously iterates the remaining records of the current result set and returns the results of an asynchronous transform as an array.
/// </summary>
/// <include file="Readers.docs.xml" path="docs/members[@name='transform-T']/*" />
/// <param name="reader">The <see cref="DbDataReader"/> to read from.</param>
/// <param name="transform">
/// The asynchronous function to transform each <see cref="IDataRecord"/> into a result.
/// </param>
/// <include file="Readers.docs.xml" path="docs/members[@name='cancellationToken']/*" />
/// <returns>
/// A task that represents the asynchronous operation.
/// Its result is an array of exactly the transformed results.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="reader"/> or <paramref name="transform"/> is <see langword="null"/>.
/// </exception>
public static ValueTask<T[]> ToArrayAsync<T>(this DbDataReader reader,
Func<IDataRecord, ValueTask<T>> transform, CancellationToken cancellationToken = default)
=> CollectAsync<T, ArrayBuild<T>, T[]>(reader, transform, cancellationToken);

/// <summary>
/// Asynchronously iterates the remaining records of the current result set and returns the results of an asynchronous transform as an immutable array.
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
/// <include file="Readers.docs.xml" path="docs/members[@name='transform-T']/*" />
/// <param name="reader">The <see cref="DbDataReader"/> to read from.</param>
/// <param name="transform">
/// The asynchronous function to transform each <see cref="IDataRecord"/> into a result.
/// </param>
/// <include file="Readers.docs.xml" path="docs/members[@name='cancellationToken']/*" />
/// <returns>
/// A task that represents the asynchronous operation.
/// Its result is an immutable array of the transformed results.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="reader"/> or <paramref name="transform"/> is <see langword="null"/>.
/// </exception>
public static ValueTask<ImmutableArray<T>> ToImmutableArrayAsync<T>(this DbDataReader reader,
Func<IDataRecord, ValueTask<T>> transform, CancellationToken cancellationToken = default)
=> CollectAsync<T, ImmutableArrayBuild<T>, ImmutableArray<T>>(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<TResult> CollectAsync<T, TBuild, TResult>(DbDataReader reader,
Func<IDataRecord, ValueTask<T>> transform, CancellationToken cancellationToken)
where TBuild : struct, IChainBuild<T, TResult>
{
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<T>.Rent(Views.Defaults<T>.Config);
while (await reader.ReadAsync(cancellationToken).ConfigureAwait(false)) chain.Add(await transform(reader).ConfigureAwait(false));
return chain.ToList();
return default(TBuild).Build(chain);
}

/// <summary>
Expand Down
2 changes: 2 additions & 0 deletions Source/Core/PublicAPI.Unshipped.txt
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,5 @@ Open.Database.Extensions.MappedQueryWithTake<T>.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<System.Data.DataTable!>!
static Open.Database.Extensions.Synchronous.SyncCommandExtensions.ToDataTables(this System.Data.IDbCommand! command, System.Data.CommandBehavior behavior = System.Data.CommandBehavior.Default) -> System.Collections.Generic.List<System.Data.DataTable!>!
static Open.Database.Extensions.DataReaderExtensions.ToArrayAsync<T>(this System.Data.Common.DbDataReader! reader, System.Func<System.Data.IDataRecord!, System.Threading.Tasks.ValueTask<T>>! transform, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask<T[]!>
static Open.Database.Extensions.DataReaderExtensions.ToImmutableArrayAsync<T>(this System.Data.Common.DbDataReader! reader, System.Func<System.Data.IDataRecord!, System.Threading.Tasks.ValueTask<T>>! transform, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask<System.Collections.Immutable.ImmutableArray<T>>
139 changes: 139 additions & 0 deletions Tests/Open.Database.Extensions.Core.Tests/DataReaderExtensionsTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<int> 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<int> 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<IDataRecord, ValueTask<int>>? 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<TResult>(string parameter, ValueTask<TResult> call)
{
ArgumentNullException e = await Assert.ThrowsAsync<ArgumentNullException>(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<T>()
=> typeof(Open.Database.Extensions.Core.ChunkChain<T>)
.GetField("_spare", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static)!
.GetValue(null);

[Fact]
public static async Task TheCollectingTerminals_ATransformThatThrows_FaultsTheTask_AndGivesTheChainBack()
{
static async ValueTask<ThrowRow> 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<ThrowRow>());

for (int i = 0; i < 3; i++)
{
System.Data.Common.DbDataReader reader = FakeReader.CreateDb(["Id"], IdRows(10));
Func<ValueTask> 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<InvalidOperationException>(async () => await call());

Assert.Equal("transform failed", e.Message);
// Disposed on the way out: the chain is parked again.
Assert.NotNull(ParkedChain<ThrowRow>());
}

// 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<ThrowRow>(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<CancelRow>());

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<CancellationToken>()).Returns(ci
=> ci.Arg<CancellationToken>().IsCancellationRequested
? Task.FromCanceled<bool>(ci.Arg<CancellationToken>())
: Task.FromResult(reader.Read()));

using var source = CancellationTokenSource.CreateLinkedTokenSource(Ct);
int transformed = 0;
ValueTask<CancelRow> Transform(IDataRecord r)
{
if (++transformed == 3) source.Cancel();
return new ValueTask<CancelRow>(new CancelRow((int)r.GetValue(0)));
}

CancellationToken token = source.Token;
Func<ValueTask> 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<OperationCanceledException>(async () => await call());

Assert.Equal(3, transformed);
Assert.NotNull(ParkedChain<CancelRow>());
}
}

#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]
Expand Down
Original file line number Diff line number Diff line change
@@ -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<int> 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<long> Measure(DataTable table, Func<DbDataReader, Task> 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<int>.Builder b = ImmutableArray.CreateBuilder<int>();
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<int>.Builder b = ImmutableArray.CreateBuilder<int>();
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<int>();
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}");
}
}
}
1 change: 1 addition & 0 deletions docsite/articles/release-notes.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<T>()` on a `DbQuery`, a `DbQuery<TParams>` 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

Expand Down