Skip to content

Commit 8a44379

Browse files
Merge master (#124, lazy Select) into this branch
Conflicts: First/Single and Select are both added at the end of MappedQueryExtensions, so both are kept; the public-API list, the notes and the samples keep both sides. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2 parents 9b42181 + 0a6ef97 commit 8a44379

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>
@@ -712,4 +712,48 @@ public static ValueTask<T> SingleAsync<T>(this IMappedQuery<T> query, Cancellati
712712
async (items, token) => await items.SingleAsync(token).ConfigureAwait(false),
713713
cancellationToken);
714714
}
715+
716+
/// <summary>
717+
/// Projects each mapped row with <paramref name="selector"/>, lazily: nothing runs until a terminal of the returned query runs.
718+
/// </summary>
719+
/// <typeparam name="T">The type each row is mapped to.</typeparam>
720+
/// <typeparam name="TResult">The type <paramref name="selector"/> returns.</typeparam>
721+
/// <param name="query">The query to project.</param>
722+
/// <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>
723+
/// <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>
724+
/// <exception cref="ArgumentNullException"><paramref name="query"/> or <paramref name="selector"/> is <see langword="null"/>.</exception>
725+
/// <remarks>
726+
/// <para>
727+
/// 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.
728+
/// </para>
729+
/// <para>
730+
/// 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.
731+
/// </para>
732+
/// <para>
733+
/// 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.
734+
/// </para>
735+
/// </remarks>
736+
/// <example>
737+
/// <code>
738+
/// static IMappedQuery&lt;CustomerName&gt; Names(IDbConnectionFactory&lt;SqlConnection&gt; factory)
739+
/// => factory
740+
/// .Command("SELECT Id, Name FROM Customers")
741+
/// .Map&lt;Customer&gt;()
742+
/// .Select(c => new CustomerName(c.Id, c.Name));
743+
///
744+
/// List&lt;CustomerName&gt; all = await Names(factory).ToListAsync(cancellationToken);
745+
/// CustomerName? first = await Names(factory).FirstOrDefaultAsync(cancellationToken);
746+
/// </code>
747+
/// </example>
748+
/// <seealso cref="IMappedQuery{T}"/>
749+
public static IMappedQuery<TResult> Select<T, TResult>(
750+
this IMappedQuery<T> query,
751+
Func<T, TResult> selector)
752+
{
753+
if (query is null) throw new ArgumentNullException(nameof(query));
754+
if (selector is null) throw new ArgumentNullException(nameof(selector));
755+
Contract.EndContractBlock();
756+
757+
return new ProjectedQuery<T, TResult>(query, selector);
758+
}
715759
}

‎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,6 +189,7 @@ 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.MappedQuery<T>.First() -> T
193194
Open.Database.Extensions.MappedQuery<T>.FirstAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask<T>
194195
Open.Database.Extensions.MappedQuery<T>.Single() -> T

0 commit comments

Comments
 (0)