Skip to content

Commit 374ffe9

Browse files
Merge master (#124, lazy Select) into this branch
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2 parents 440cf56 + 0a6ef97 commit 374ffe9

8 files changed

Lines changed: 1402 additions & 1 deletion

File tree

‎Source/Core/Extensions/MappedQueryExtensions.cs‎

Lines changed: 45 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
namespace Open.Database.Extensions;
22

33
/// <summary>
4-
/// Terminal operations for <see cref="IMappedQuery{T}"/>: they materialize the mapped rows into a collection or take a single row. <see cref="MappedQuery{T}"/> and its skip and take variants expose the same operations directly.
4+
/// Terminal operations for <see cref="IMappedQuery{T}"/>: they materialize the mapped rows into a collection or take a single row, and <see cref="Select{T, TResult}(IMappedQuery{T}, Func{T, TResult})"/> projects them lazily. <see cref="MappedQuery{T}"/> and its skip and take variants expose the same operations directly.
55
/// </summary>
66
/// <remarks>
77
/// <para>
@@ -412,4 +412,48 @@ public static ValueTask<HashSet<T>> ToHashSetAsync<T>(this IMappedQuery<T> query
412412
=> query.ReadAsync(
413413
async (items, token) => await items.SingleOrDefaultAsync(token).ConfigureAwait(false),
414414
cancellationToken);
415+
416+
/// <summary>
417+
/// Projects each mapped row with <paramref name="selector"/>, lazily: nothing runs until a terminal of the returned query runs.
418+
/// </summary>
419+
/// <typeparam name="T">The type each row is mapped to.</typeparam>
420+
/// <typeparam name="TResult">The type <paramref name="selector"/> returns.</typeparam>
421+
/// <param name="query">The query to project.</param>
422+
/// <param name="selector">Produces the projected value for each mapped row. It runs once per row, in row order, only while a terminal is reading the rows.</param>
423+
/// <returns>A deferred query of the projected rows. Every terminal in <see cref="MappedQueryExtensions"/> works on it, and so does <c>Select</c> again.</returns>
424+
/// <exception cref="ArgumentNullException"><paramref name="query"/> or <paramref name="selector"/> is <see langword="null"/>.</exception>
425+
/// <remarks>
426+
/// <para>
427+
/// This call executes nothing and does not run <paramref name="selector"/>. The command runs once for each terminal called on the returned query, exactly as it does on <paramref name="query"/>, so a method can return the projected query and let each caller pick the terminal (<c>ToListAsync</c> or <c>FirstOrDefaultAsync</c>, for example). A query read by two terminals executes the command twice.
428+
/// </para>
429+
/// <para>
430+
/// The projection is built on <see cref="IMappedQuery{T}.Read(Action{IEnumerable{T}})"/> and <see cref="IMappedQuery{T}.ReadAsync(Func{IAsyncEnumerable{T}, CancellationToken, ValueTask}, CancellationToken)"/>, so how <paramref name="query"/> opens and releases the connection, reads through later result sets and honors <c>SingleResult()</c> and cancellation is unchanged. <c>Skip</c> and <c>Take</c> apply to the rows of <paramref name="query"/>, before the selector runs: call them before <c>Select</c>. A terminal that stops early, such as <c>FirstOrDefault</c>, runs <paramref name="selector"/> only for the rows it reads.
431+
/// </para>
432+
/// <para>
433+
/// An exception thrown by <paramref name="selector"/> propagates to the caller of the terminal, and the reader and the connection are released as they are when a handler throws. A projection of a projection reads through one reader.
434+
/// </para>
435+
/// </remarks>
436+
/// <example>
437+
/// <code>
438+
/// static IMappedQuery&lt;CustomerName&gt; Names(IDbConnectionFactory&lt;SqlConnection&gt; factory)
439+
/// => factory
440+
/// .Command("SELECT Id, Name FROM Customers")
441+
/// .Map&lt;Customer&gt;()
442+
/// .Select(c => new CustomerName(c.Id, c.Name));
443+
///
444+
/// List&lt;CustomerName&gt; all = await Names(factory).ToListAsync(cancellationToken);
445+
/// CustomerName? first = await Names(factory).FirstOrDefaultAsync(cancellationToken);
446+
/// </code>
447+
/// </example>
448+
/// <seealso cref="IMappedQuery{T}"/>
449+
public static IMappedQuery<TResult> Select<T, TResult>(
450+
this IMappedQuery<T> query,
451+
Func<T, TResult> selector)
452+
{
453+
if (query is null) throw new ArgumentNullException(nameof(query));
454+
if (selector is null) throw new ArgumentNullException(nameof(selector));
455+
Contract.EndContractBlock();
456+
457+
return new ProjectedQuery<T, TResult>(query, selector);
458+
}
415459
}

‎Source/Core/ProjectedQuery.cs‎

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
namespace Open.Database.Extensions;
2+
3+
// What MappedQueryExtensions.Select returns: a lazy projection of another
4+
// query. It holds the source and the selector and runs nothing itself.
5+
// Each terminal hands the handler a stream of the source's rows, projected one
6+
// at a time as the handler enumerates it, so a projection of a projection
7+
// still reads through one reader.
8+
// A caller sees only IMappedQuery<T>, so this type stays internal.
9+
sealed class ProjectedQuery<TSource, T>(
10+
IMappedQuery<TSource> source,
11+
Func<TSource, T> selector)
12+
: IMappedQuery<T>
13+
{
14+
public void Read(Action<IEnumerable<T>> handler)
15+
{
16+
if (handler is null) throw new ArgumentNullException(nameof(handler));
17+
Contract.EndContractBlock();
18+
19+
source.Read(rows => handler(Project(rows, selector)));
20+
}
21+
22+
public TResult Read<TResult>(Func<IEnumerable<T>, TResult> handler)
23+
{
24+
if (handler is null) throw new ArgumentNullException(nameof(handler));
25+
Contract.EndContractBlock();
26+
27+
return source.Read(rows => handler(Project(rows, selector)));
28+
}
29+
30+
public ValueTask ReadAsync(
31+
Func<IAsyncEnumerable<T>, CancellationToken, ValueTask> handler,
32+
CancellationToken cancellationToken)
33+
{
34+
if (handler is null) throw new ArgumentNullException(nameof(handler));
35+
Contract.EndContractBlock();
36+
37+
return source.ReadAsync(
38+
(rows, token) => handler(ProjectAsync(rows, selector, token), token),
39+
cancellationToken);
40+
}
41+
42+
public ValueTask<TResult> ReadAsync<TResult>(
43+
Func<IAsyncEnumerable<T>, CancellationToken, ValueTask<TResult>> handler,
44+
CancellationToken cancellationToken)
45+
{
46+
if (handler is null) throw new ArgumentNullException(nameof(handler));
47+
Contract.EndContractBlock();
48+
49+
return source.ReadAsync(
50+
(rows, token) => handler(ProjectAsync(rows, selector, token), token),
51+
cancellationToken);
52+
}
53+
54+
// The foreach disposes the source's enumerator when this one is disposed,
55+
// so a handler that stops early still releases the reader.
56+
static IEnumerable<T> Project(
57+
IEnumerable<TSource> rows,
58+
Func<TSource, T> selector)
59+
{
60+
foreach (TSource row in rows)
61+
{
62+
yield return selector(row);
63+
}
64+
}
65+
66+
static async IAsyncEnumerable<T> ProjectAsync(
67+
IAsyncEnumerable<TSource> rows,
68+
Func<TSource, T> selector,
69+
[EnumeratorCancellation] CancellationToken cancellationToken)
70+
{
71+
await foreach (TSource row in rows
72+
.WithCancellation(cancellationToken)
73+
.ConfigureAwait(false))
74+
{
75+
yield return selector(row);
76+
}
77+
}
78+
}

‎Source/Core/PublicAPI.Unshipped.txt‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -189,5 +189,6 @@ static Open.Database.Extensions.ConnectionExtensions.UsingAsync<TConnection>(thi
189189
Open.Database.Extensions.ExpressiveDbCommandBase<TConnection, TCommand, TReader, TDbType, TThis>.RetrieveAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask<Open.Database.Extensions.Core.QueryResultQueue<object![]!>!>
190190
Open.Database.Extensions.ExpressiveDbCommandBase<TConnection, TCommand, TReader, TDbType, TThis>.RetrieveAsync(System.Collections.Generic.IEnumerable<int>! ordinals, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask<Open.Database.Extensions.Core.QueryResultQueue<object![]!>!>
191191
Open.Database.Extensions.ExpressiveDbCommandBase<TConnection, TCommand, TReader, TDbType, TThis>.RetrieveAsync(System.Collections.Generic.IEnumerable<string!>! columnNames, bool normalizeColumnOrder = false, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask<Open.Database.Extensions.Core.QueryResultQueue<object![]!>!>
192+
static Open.Database.Extensions.MappedQueryExtensions.Select<T, TResult>(this Open.Database.Extensions.IMappedQuery<T>! query, System.Func<T, TResult>! selector) -> Open.Database.Extensions.IMappedQuery<TResult>!
192193
Open.Database.Extensions.RowMap<T>.Convert<TColumn, TMember>(string! member, string! column, System.Func<TColumn, TMember>! convert) -> Open.Database.Extensions.RowMap<T>!
193194
Open.Database.Extensions.RowMap<T>.Convert<TColumn, TMember>(string! member, System.Func<TColumn, TMember>! convert) -> Open.Database.Extensions.RowMap<T>!

0 commit comments

Comments
 (0)