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
30 changes: 19 additions & 11 deletions Source/Core/Core/RowReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -134,23 +134,31 @@ public static void Fill<T, TSink>(IRowSource<T> source, IDataReader reader, int
/// <param name="reader">The reader positioned on a result set.</param>
/// <param name="skip">The number of rows to skip.</param>
/// <param name="take">The number of rows to read; 0 reads none.</param>
/// <param name="config">The pool and the clearing rule of the chain.</param>
/// <param name="abandon">Cancels the command at an early stop, or <see langword="null"/>.</param>
/// <param name="token">The token that cancels the read; only a reader that is not a <see cref="DbDataReader"/> observes it.</param>
/// <returns>The rows, in a new list.</returns>
/// <returns>The rows, in a new list of exactly their number.</returns>
// The two hottest terminals (this one and ToArray) keep their own loops:
// the sink indirection of Fill is measurable with a tiny projection
// (benchmarked), so the list and the array are written out directly.
public static List<T> ToList<T>(IRowSource<T> source, IDataReader reader, int skip, int take, ReaderAbandon? abandon = null, CancellationToken token = default)
// (benchmarked), so the rows are written out directly, into the chain of pooled arrays
// (as ToListAsync does) and copied once into the list.
// A bare IDataReader has no DbDataReader fast path: Fill reads it through Stream into the same chain.
public static List<T> ToList<T>(IRowSource<T> source, IDataReader reader, int skip, int take, ChunkConfig<T> config, ReaderAbandon? abandon = null, CancellationToken token = default)
{
if (reader is not DbDataReader db)
return [.. Stream(source, reader, skip, take, false, abandon, token)];
{
using var viaStream = ChunkChain<T>.Rent(config);
var sink = new ChainSink<T>(viaStream);
Fill(source, reader, skip, take, ref sink, abandon, token);
return viaStream.ToList();
}

var list = new List<T>();
if (TakesNone(take, abandon, db)) return list;
if (TakesNone(take, abandon, db)) return [];

if (!SkipRows(db, skip) || !db.Read()) return list;
if (!SkipRows(db, skip) || !db.Read()) return [];

Func<DbDataReader, T> map = source.Mapper(db);
using var chain = ChunkChain<T>.Rent(config);
int n = 0;
do
{
Expand All @@ -161,11 +169,11 @@ public static List<T> ToList<T>(IRowSource<T> source, IDataReader reader, int sk
}
catch (Exception ex) when (RowErrors.IsRowFailure(source, ex))
{
// The list's count, not n (see Fill).
throw RowErrors.Report<T>(ex, skip + list.Count);
// The chain's count, not n (see Fill).
throw RowErrors.Report<T>(ex, skip + chain.Count);
}

list.Add(item);
chain.Add(item);
if (++n == take)
{
abandon?.CancelIfMore(db);
Expand All @@ -174,7 +182,7 @@ public static List<T> ToList<T>(IRowSource<T> source, IDataReader reader, int sk
}
while (db.Read());

return list;
return chain.ToList();
}

/// <summary>
Expand Down
4 changes: 2 additions & 2 deletions Source/Core/MappedQuery.cs
Original file line number Diff line number Diff line change
Expand Up @@ -583,8 +583,8 @@ static IAsyncEnumerable<T> StreamAsync(IRowSource<T> source, IDataReader reader,
public List<T> ToList()
{
ReaderAbandon? abandon = NewAbandon();
return Run((_source, _skip, _take, abandon), static (reader, s)
=> RowReader.ToList(s._source, reader, s._skip, s._take, s.abandon), Behavior, abandon);
return Run((_source, _skip, _take, Config, abandon), static (reader, s)
=> RowReader.ToList(s._source, reader, s._skip, s._take, s.Config, s.abandon), Behavior, abandon);
}

public T[] ToArray()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -150,19 +150,19 @@ static MappedCommand<CopyOutRow> Rows(CountingPool<CopyOutRow> pool, bool? clear
public static TheoryData<string> Terminals
=> [
"ToListAsync", "ToArrayAsync", "ToImmutableArrayAsync", "ToHashSetAsync", "ToDictionaryAsync", "ToDictionaryAsync.Value",
// The synchronous ToList grows a list of its own and rents nothing, so there is nothing to clear.
"ToArray", "ToImmutableArray", "ToDictionary",
"ToList", "ToArray", "ToImmutableArray", "ToDictionary",
];

static async Task Run(string terminal, MappedCommand<CopyOutRow> view)
{
switch (terminal)
{
// The synchronous collectors read through RowReader.Collect, and ToArray through the array sink.
// The synchronous collectors read through RowReader.Collect, and ToList and ToArray through the chain and the array sink they write out themselves.
case "ToList": Assert.Equal(100, view.ToList().Count); break;
case "ToArray": Assert.Equal(100, view.ToArray().Length); break;
case "ToImmutableArray": Assert.Equal(100, view.ToImmutableArray().Length); break;
case "ToDictionary": Assert.Equal(100, view.ToDictionary(static r => r.Id).Count); break;
case "ToListAsync":Assert.Equal(100, (await view.ToListAsync(Ct)).Count); break;
case "ToListAsync": Assert.Equal(100, (await view.ToListAsync(Ct)).Count); break;
case "ToArrayAsync": Assert.Equal(100, (await view.ToArrayAsync(Ct)).Length); break;
case "ToImmutableArrayAsync": Assert.Equal(100, (await view.ToImmutableArrayAsync(Ct)).Length); break;
case "ToHashSetAsync": Assert.Equal(100, (await view.ToHashSetAsync(cancellationToken: Ct)).Count); break;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
namespace Open.Database.Extensions.Tests;

#nullable enable

// Bytes per call of the synchronous ToList of a mapped view, over an in-memory DataTable,
// against a List that grows (the old shape, written by hand over a DataTableReader).
// A count of bytes, not a time; the thread-local counter sees everything because nothing suspends.
// Run it by itself, in Release, with the test executable and -explicit only.
[ExcludeFromCodeCoverage]
[Collection("Heap measurements")]
public sealed class SyncToListAllocationProbe(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;
}

// The smallest of several runs, after a warm-up.
static long Measure(Action call)
{
for (int i = 0; i < 20; i++) call();

long best = long.MaxValue;
for (int i = 0; i < Rounds; i++)
{
GC.Collect();
GC.WaitForPendingFinalizers();
long before = GC.GetAllocatedBytesForCurrentThread();
call();
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 list and not the growth of one.
[Theory]
[InlineData(1000)]
[InlineData(100_000)]
public void ToList_AllocatesLessThanAListThatGrows(int rows)
{
DataTable table = Table(rows);

long chain = Measure(() => GC.KeepAlive(table.Map<int>().ToList()));
long grows = Measure(() =>
{
using DataTableReader r = table.CreateDataReader();
var l = new List<int>();
while (r.Read()) l.Add(r.GetInt32(0));
GC.KeepAlive(l);
});

Assert.True(chain < grows, $"{rows} rows: chain {chain} B, list that grows {grows} B.");
}
#endif

[Fact(Explicit = true)]
public void Probe_BytesPerCall()
{
output.WriteLine("rows | view.ToList() | List that grows (by hand) | view.ToArray() (bytes per call)");
foreach (int rows in new[] { 0, 1, 1000, 100_000 })
{
DataTable table = Table(rows);

long list = Measure(() => GC.KeepAlive(table.Map<int>().ToList()));
long grows = Measure(() =>
{
using DataTableReader r = table.CreateDataReader();
var l = new List<int>();
while (r.Read()) l.Add(r.GetInt32(0));
GC.KeepAlive(l);
});
long array = Measure(() => GC.KeepAlive(table.Map<int>().ToArray()));

output.WriteLine($"{rows,7} | {list,12} | {grows,12} | {array,12}");
}
}
}
148 changes: 148 additions & 0 deletions Tests/Open.Database.Extensions.Core.Tests/SyncToListTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
using Open.Database.Extensions.Core;
using System.Buffers;
using static Open.Database.Extensions.Tests.ChannelWait;

#nullable enable

namespace Open.Database.Extensions.Tests;

// The synchronous ToList reads into the chain of pooled arrays and copies once, as ToListAsync does,
// so a list is exactly as long as its rows, the arrays go back however the call ends, and the
// copy-out clearing applies to it (CopyOutClearingTests).
[ExcludeFromCodeCoverage]
public static class SyncToListTests
{
static CountingPool<CopyOutRow> NewPool()
=> new()
{
RoundUp = true,
Sentinel = static () => new CopyOutRow(-1),
IsDirty = static a => a.Any(static r => r.Id > 0),
};

static MappedCommand<CopyOutRow> Rows(int n, int? failAtRow = null, ArrayPool<CopyOutRow>? pool = null)
{
MappedCommand<CopyOutRow> view = new FakeDbCommand(
new FakeDbConnection(),
() => new ChannelTestReader(n, failAtRow: failAtRow))
.Map<CopyOutRow>();

return pool is null ? view : view.UsePool(pool, clearOnReturn: true);
}

public static TheoryData<int> Sizes
=> [0, 1, 15, 16, 17, 48, 49, 100, 8191, 8192, 8193, 20_000];

[Theory, MemberData(nameof(Sizes))]
public static void ToList_ReturnsEveryRowInOrder_ExactlySized(int n)
{
List<CopyOutRow> rows = Rows(n).ToList();

Assert.Equal(n, rows.Count);
Assert.Equal(n, rows.Capacity);
for (int i = 0; i < n; i++) Assert.Equal(i + 1, rows[i].Id);
}

[Fact]
public static void WithSkipAndTake_OnlyThoseRowsArrive()
{
List<CopyOutRow> list = Rows(100).Skip(10).Take(30).ToList();

Assert.Equal(30, list.Count);
Assert.Equal(11, list[0].Id);
Assert.Equal(40, list[^1].Id);
}

[Fact]
public static void ATakeOfZero_RentsNothingAndReturnsEmpty()
{
CountingPool<CopyOutRow> pool = NewPool();

Assert.Empty(Rows(50, pool: pool).Take(0).ToList());
Assert.Equal(0, pool.Rents);
}

[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(100)]
[InlineData(9000)]
public static async Task EveryArray_GoesBack_AndIsCleanWhenItDoes(int n)
{
CountingPool<CopyOutRow> pool = NewPool();

Assert.Equal(n, Rows(n, pool: pool).ToList().Count);

await Until(() => pool.Outstanding == 0, "the arrays back");
Assert.Equal(pool.Rents, pool.Returns);
Assert.Equal(0, pool.DirtyReturns);
Assert.Equal(n == 0, pool.Rents == 0);
}

[Fact]
public static async Task AFailureMidRead_ReturnsEveryArray_AndThrows()
{
CountingPool<CopyOutRow> pool = NewPool();

Assert.Throws<InvalidOperationException>(
() => Rows(100, failAtRow: 40, pool: pool).ToList());

await Until(() => pool.Outstanding == 0, "the arrays back");
Assert.True(pool.Rents > 0);
Assert.Equal(pool.Rents, pool.Returns);
Assert.Equal(0, pool.DirtyReturns);
}

// A bare IDataReader has no DbDataReader fast path: it is read through the same chain.
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(100)]
[InlineData(5000)]
public static void ABareIDataReader_ReadsIntoTheSameChain(int n)
{
IDataReader reader = FakeReader.Create(["Id"], [.. Enumerable.Range(1, n).Select(static i => (object?[])[i])]);

List<int> list = reader.Map<int>().ToList();

Assert.Equal(Enumerable.Range(1, n), list);
Assert.Equal(n, list.Capacity);
}

// A row type of its own, so no other test rents or parks its chain.
sealed record FailRow(int Id);

static object? ParkedChain<T>()
=> typeof(ChunkChain<T>)
.GetField("_spare", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static)!
.GetValue(null);

static InvalidOperationException ThirdRowFails(IDataReader reader)
{
int seen = 0;
MappedReader<FailRow> view = reader.Map<FailRow>(r
=> ++seen == 3
? throw new InvalidOperationException("mapper failed")
: new FailRow((int)r.GetValue(0)));

return Assert.Throws<InvalidOperationException>(() => view.ToList());
}

[Fact]
public static void AFailureMidRead_OfAReader_GivesTheChainBack_AndThrowsTheMappersOwnFailure()
{
object?[][] rows = [.. Enumerable.Range(1, 20).Select(static i => (object?[])[i])];
Assert.Null(ParkedChain<FailRow>());

// The fast path of a DbDataReader, then a bare IDataReader: the chain is parked again after each.
InvalidOperationException db = ThirdRowFails(FakeReader.CreateDb(["Id"], rows));
Assert.NotNull(ParkedChain<FailRow>());
InvalidOperationException bare = ThirdRowFails(FakeReader.Create(["Id"], rows));
// It took the parked chain and gave it back: a chain not disposed would leave none.
Assert.NotNull(ParkedChain<FailRow>());

// The caller's own mapper failure comes out as it was thrown, on both paths.
Assert.Equal("mapper failed", db.Message);
Assert.Equal("mapper failed", bare.Message);
}
}
1 change: 1 addition & 0 deletions docsite/articles/release-notes.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ Version 11 is `11.0.0-rc.16`. For moving a 10.x codebase, read [Coming from earl
- **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).
- **Changed: the collecting terminals clear their value rows when no pool is offered.** `ToList`, `ToArray`, `ToImmutableArray`, `ToHashSet` and the dictionaries, asynchronous and synchronous, on a view or on a `DbDataReader`, copy their rows out and never show their pooled arrays, so they hide their pooling: a query that does not call `UsePool` now always clears the used rows of those arrays before they go back, plain value rows included, whatever the `Open.Database.Extensions.ClearPooledArrays` switch says. `UsePool(pool, clearOnReturn)` is followed as before, so `clearOnReturn: false` still keeps the rows. Rows that hold references were always cleared. The buffers and streams are unchanged: their default is still not to clear value rows. A chunk of 128 KB or more is cleared in the background, as before, and the allocation of a call is the same.
- **Changed: the synchronous `ToList()` reads into pooled chunks, as `ToListAsync` does.** On a view or a reader it grew a list of its own, and so allocated the growth as well as the result and rented no pooled array; it now reads into the chain of pooled arrays and copies the rows once into a list of exactly their number, so the copy-out clearing above applies to it too. The growth is gone: 100,000 `int` rows allocate about 400 KB instead of about 1.05 MB, and 1,000 rows about 28.8 KB instead of 33.2 KB.

### Changes since rc.15

Expand Down