Skip to content

Commit 2a391a6

Browse files
Output parameters on stored definitions, and captures on their calls (#300)
Stored definitions can declare and read output parameters, captures work on the calls of a stored definition, and a capture takes its parameter's name from its variable. Builds on #297. ## Outputs on a definition A `DbNonQuery` definition declares what it reads back, once, where it is stored: ```csharp static readonly OutputDbNonQuery<AddPostResult> AddPost = DbNonQuery.Procedure("[dbo].[AddPost]") .Output<AddPostResult>(); var result = await AddPost.Using(Blog) .AddParam(post) .ExecuteOutputAsync(cancellationToken); ``` - `Output<TOut>()` reads a model. `Output<T>(name)` and `Output<T>(name, precision, scale)` read one value, and `OutputDecimal(name, precision, scale)` reads a nullable decimal. All four also work on the typed-parameters form, `DbNonQuery.Procedure(...).Params<TParams>()`. - The outputs are checked when the definition is declared. Every message names the definition and the model, and gives the fix. - A bound write has `ExecuteReturnAsync<T>()` for the return code. It is refused at the call on a text definition, because a text definition has no return code. - A definition matches and adds its outputs through the same code as the commands, so the rules are the same. Named outputs match the way `AddParam` names do: exact, ignoring case, ignoring case and underscores, then without a common prefix. - A definition's call that reads output parameters is checked against the procedure's parameter metadata before the run, as a command's call is (#298). It reads the metadata itself, so the check does not depend on a command having called the procedure first. - A definition's outputs are part of its equality, compared by value: two definitions of one procedure that read different outputs are different, and so are their calls. ## Captures on a definition's calls A capture is per call, after `Using` and the parameters, and never on the stored definition: ```csharp var rows = await PagePosts.Using(Blog) .AddParam(page) .CaptureOutput(out DbCapture<int> total) .ToListAsync(cancellationToken); var count = await total; ``` - **Where captures work:** on a query made from a `DbQuery` definition (every terminal, stream, buffer, Channel and Dataflow form), and on bound write and scalar calls. A call made from `Output` has no capture members, so a capture there is a compile error. - **Order:** a capture before or after `AddParam` gives the same call. - **Single use:** a kept or branched call that carries a capture runs once; a second run throws. - **Captures on the return code:** - `CaptureReturn` on a text definition is refused at the call. - `ExecuteReturnAsync` refuses a capture that also reads the return code, and runs beside a capture that reads only outputs. - **Runner:** a definition's call fills its captures through its own runner. The runner claims the captures when the terminal is called, copies the outputs before the command is disposed, and completes every capture on every exit. - **Cost of a call without captures:** a bound call carries one more reference, which is `null` without a capture. It is copied on each `AddParam`, and each terminal tests it once. Equality includes it by reference, and a call without one hashes as before. ## The capture name comes from the variable `CaptureOutput(out DbCapture<int> total)` reads `@total`. The name can also be passed last: `CaptureOutput(out DbCapture<int> x, "total")`. - The compiler supplies the variable's text. The last identifier is taken from it: a declaration, a local, `this.total`, `state.total`, `arr[0].Total`. A typed name follows the same rule: `$` and `#` are allowed, and one leading `@` or `:` is dropped. - A discard, an element access, an empty name, or a missing compiler text is refused with the fix. - The name is matched the way `AddParam` names are, over the name as written and without an `m_` or `s_` field prefix. A text that is not one plain name is worked out once and cached weakly. - A model capture ignores the name. If a model member matches nothing, the message says the name was not used and gives both fixes. - `CaptureOutput(out DbCapture<decimal> x, precision, scale, name)` replaces the generic shape overload, so a wrong type with a shape does not compile. `CaptureOutputDecimal` keeps the nullable form. - The name-first capture forms added earlier in this release cycle are removed. They were never in a published release. ## Docs and samples - The output samples lead with the definition form: a `static readonly` field, then the per-call chain. The ad hoc command form follows. - New samples cover: - typed parameters with outputs; - a definition's return code; - a model capture; - write and scalar captures; - a pooled stream; - the ways a capture takes its name. - The samples run against procedures in tempdb when LocalDB is available, and the sample checks verify what they return. - The expressive commands article, the release notes and the what's new page describe both features. ## Tests - **Definitions:** declaration checks and messages; the same results as a command for the same procedure; typed parameters; the return code; the metadata checks on a definition and on a capture on its call. - **Captures through a definition:** every terminal, stream and buffer; Channel and Dataflow; a synchronous terminal (refused); `CancelOnEarlyStop()`; single use; before or after `AddParam`. - **Capture names:** the name rules on a fake provider and on SQL Server. An output named after an input parameter is now refused before the run, from the procedure's metadata. - **Compile tests:** in-memory, on every C# language version the repo tests. They prove that a capture on an `Output` call does not compile, that a wrong type with a decimal shape does not compile, and that `out var` with a shape infers `DbCapture<decimal>`. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> 🤖 Generated with [Claude Code](https://claude.com/claude-code)
1 parent eb30290 commit 2a391a6

36 files changed

Lines changed: 5194 additions & 793 deletions

‎Source/Core/BoundCall.cs‎

Lines changed: 284 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,13 @@ namespace Open.Database.Extensions;
1111
/// </summary>
1212
public readonly struct NonQueryKind;
1313

14+
/// <summary>
15+
/// Marks a chain that writes and reads output parameters: it ends in
16+
/// <c>ExecuteOutputAsync</c>.
17+
/// </summary>
18+
/// <typeparam name="TOut">What the outputs are read as.</typeparam>
19+
public readonly struct OutputKind<TOut>;
20+
1421
/// <summary>
1522
/// A scalar query or a write bound to where its connections come from, with
1623
/// the values added so far.
@@ -27,7 +34,16 @@ namespace Open.Database.Extensions;
2734
/// </typeparam>
2835
public readonly struct BoundCall<TKind> : IEquatable<BoundCall<TKind>>
2936
{
30-
internal BoundCall(DbQueryCall call) => Call = call;
37+
internal BoundCall(DbQueryCall call, CaptureSet? captures = null)
38+
{
39+
Call = call;
40+
Captures = captures;
41+
}
42+
43+
// The captures the call carries, or null. Added by the capture extensions
44+
// of BoundCallExtensions after Using and the parameters, and carried by
45+
// every AddParam; compared by reference.
46+
internal CaptureSet? Captures { get; }
3147

3248
// The same value a rows query holds: the definition, the source and the
3349
// values.
@@ -39,26 +55,27 @@ namespace Open.Database.Extensions;
3955
/// <inheritdoc cref="DbQueryUsing.AddParams{T}(T)"/>
4056
public BoundCall<TKind> AddParams<TValues>(TValues values)
4157
where TValues : notnull
42-
=> new(Call.AddParams(values));
58+
=> new(Call.AddParams(values), Captures);
4359

4460
/// <inheritdoc cref="DbQueryUsing.AddParam{T}(string, T)"/>
4561
public BoundCall<TKind> AddParam<TValue>(string name, TValue value)
46-
=> new(Call.AddParam(name, value));
62+
=> new(Call.AddParam(name, value), Captures);
4763

4864
/// <inheritdoc cref="DbQueryUsing.AddParam(string, string?)"/>
4965
public BoundCall<TKind> AddParam(string name, string? value)
50-
=> new(Call.AddParam(name, value));
66+
=> new(Call.AddParam(name, value), Captures);
5167

5268
/// <inheritdoc cref="DbQueryUsing.AddParam{T}(T, string?)"/>
5369
[OverloadResolutionPriority(-1)]
5470
public BoundCall<TKind> AddParam<TValue>(
5571
TValue value,
5672
[CallerArgumentExpression(nameof(value))] string? expression = null)
57-
=> new(Call.AddParam(value, expression));
73+
=> new(Call.AddParam(value, expression), Captures);
5874

5975
/// <inheritdoc />
6076
public bool Equals(BoundCall<TKind> other)
61-
=> Call.Equals(other.Call);
77+
=> Call.Equals(other.Call)
78+
&& ReferenceEquals(Captures, other.Captures);
6279

6380
/// <inheritdoc />
6481
public override bool Equals(object? obj)
@@ -83,7 +100,12 @@ public override int GetHashCode()
83100
{
84101
unchecked
85102
{
86-
return Call.GetHashCode() * 31 + typeof(TKind).GetHashCode();
103+
int hash = Call.GetHashCode() * 31 + typeof(TKind).GetHashCode();
104+
105+
// Without a capture the hash is what it always was.
106+
return Captures is null
107+
? hash
108+
: hash * 31 + RuntimeHelpers.GetHashCode(Captures);
87109
}
88110
}
89111
}
@@ -262,11 +284,13 @@ public static class BoundCallExtensions
262284
public static ValueTask<T> ExecuteScalarAsync<T>(
263285
this BoundCall<ScalarKind<T>> call,
264286
CancellationToken cancellationToken = default)
265-
=> DbQueryRunner.ScalarAsync<T>(
266-
call.Call.Definition,
267-
call.Call.SourceCore,
268-
call.Call.Params,
269-
cancellationToken);
287+
=> call.Captures is { } captures
288+
? DbQueryRunner.ScalarCapturedAsync<T>(
289+
call.Call.Definition, call.Call.SourceCore, call.Call.Params,
290+
captures, cancellationToken)
291+
: DbQueryRunner.ScalarAsync<T>(
292+
call.Call.Definition, call.Call.SourceCore,
293+
call.Call.Params, cancellationToken);
270294

271295
/// <summary>Runs the write and returns the number of rows affected.</summary>
272296
/// <remarks>
@@ -282,9 +306,255 @@ public static ValueTask<T> ExecuteScalarAsync<T>(
282306
public static ValueTask<int> ExecuteNonQueryAsync(
283307
this BoundCall<NonQueryKind> call,
284308
CancellationToken cancellationToken = default)
285-
=> DbQueryRunner.NonQueryAsync(
286-
call.Call.Definition,
309+
=> call.Captures is { } captures
310+
? DbQueryRunner.NonQueryCapturedAsync(
311+
call.Call.Definition, call.Call.SourceCore, call.Call.Params,
312+
captures, cancellationToken)
313+
: DbQueryRunner.NonQueryAsync(
314+
call.Call.Definition, call.Call.SourceCore,
315+
call.Call.Params, cancellationToken);
316+
317+
/// <summary>
318+
/// Runs the write and reads its output parameters (and return code) as the
319+
/// definition declared with <c>Output</c>.
320+
/// </summary>
321+
/// <remarks>
322+
/// <include file="Output.docs.xml" path="docs/members[@name='def-run']/*" />
323+
/// </remarks>
324+
/// <typeparam name="TOut">What the outputs are read as.</typeparam>
325+
/// <param name="call">The bound call.</param>
326+
/// <include file="Mapped.docs.xml" path="docs/members[@name='token-call']/*" />
327+
/// <returns>A task that represents the asynchronous operation; its result is the model, or the one value.</returns>
328+
/// <exception cref="InvalidOperationException">Before the command executes: an output matches no parameter, or two match one, or <paramref name="call"/> is a <see langword="default"/> value, which is bound to nothing.</exception>
329+
/// <exception cref="InvalidOperationException">
330+
/// <include file="Output.docs.xml" path="docs/members[@name='out-metadata']/*" />
331+
/// </exception>
332+
/// <exception cref="ValueMappingException">A value does not convert, or is NULL and the type does not take it.</exception>
333+
/// <exception cref="OperationCanceledException"><paramref name="cancellationToken"/> is canceled.</exception>
334+
public static ValueTask<TOut> ExecuteOutputAsync<TOut>(
335+
this BoundCall<OutputKind<TOut>> call,
336+
CancellationToken cancellationToken = default)
337+
=> DbQueryRunner.OutputAsync<TOut>(
338+
call.Call.Definition, call.Call.SourceCore,
339+
call.Call.Params, cancellationToken);
340+
341+
/// <summary>
342+
/// Runs the write and returns the stored procedure's return code, converted
343+
/// to <typeparamref name="T"/>.
344+
/// </summary>
345+
/// <remarks>
346+
/// <include file="Output.docs.xml" path="docs/members[@name='def-return']/*" />
347+
/// </remarks>
348+
/// <typeparam name="T">The type of the return code: a single value such as <see cref="int"/>.</typeparam>
349+
/// <param name="call">The bound call.</param>
350+
/// <include file="Mapped.docs.xml" path="docs/members[@name='token-call']/*" />
351+
/// <returns>A task that represents the asynchronous operation; its result is the return code.</returns>
352+
/// <exception cref="InvalidOperationException">Before any connection is used: <typeparamref name="T"/> is a model, the call's definition is text (it has no return code), <paramref name="call"/> is a <see langword="default"/> value, or a capture on the call reads the return code too.</exception>
353+
/// <exception cref="OperationCanceledException"><paramref name="cancellationToken"/> is canceled.</exception>
354+
public static ValueTask<T> ExecuteReturnAsync<T>(
355+
this BoundCall<NonQueryKind> call,
356+
CancellationToken cancellationToken = default)
357+
{
358+
// All checked at the call, before a task exists or a connection is used.
359+
ReturnCode<T>.ThrowUnlessScalar();
360+
DbQuery definition = call.Call.Definition;
361+
if (definition.Kind != CommandType.StoredProcedure)
362+
{
363+
throw new InvalidOperationException(
364+
$"ExecuteReturnAsync<{Shape.TypeName(typeof(T))}>() reads a stored procedure's return code, but this call's definition is {OutputDefinitions.Describe(definition)}, and a text definition has no return code: the provider reports 0. "
365+
+ "Declare the definition with DbNonQuery.Procedure(name) to read the return code.");
366+
}
367+
368+
// A capture of the return code and this would read it twice.
369+
if (call.Captures?.ReturnReader is { } returnReader)
370+
{
371+
throw call.Captures.Refuse(
372+
new InvalidOperationException(
373+
CaptureMessages.ReturnBeside(returnReader)),
374+
cancellationToken);
375+
}
376+
377+
return DbQueryRunner.ReturnAsync<T>(
378+
definition,
287379
call.Call.SourceCore,
288380
call.Call.Params,
381+
call.Captures,
289382
cancellationToken);
383+
}
384+
385+
// ---- captures: per kind, so a call made from Output has none ----
386+
387+
// Returns the call with one more capture, checked at the call. A
388+
// definition's kind never changes, so the return code is checked here.
389+
static BoundCall<TKind> WithCapture<TKind>(
390+
BoundCall<TKind> call,
391+
ICaptureSource source)
392+
=> new(
393+
call.Call,
394+
CaptureSet.WithOnDefinition(
395+
call.Captures, source, call.Call.Definition.Kind));
396+
397+
/// <summary>
398+
/// Reads the output parameters into a <typeparamref name="TOut"/> when the
399+
/// write runs: a model by its members, or one value by the name of the
400+
/// variable.
401+
/// </summary>
402+
/// <include file="Output.docs.xml" path="docs/members[@name='capture-model']/*" />
403+
/// <include file="Output.docs.xml" path="docs/members[@name='out-name-param']/*" />
404+
/// <include file="Output.docs.xml" path="docs/members[@name='capture-call']/*" />
405+
/// <param name="call">The bound write.</param>
406+
public static BoundCall<NonQueryKind> CaptureOutput<TOut>(
407+
this BoundCall<NonQueryKind> call,
408+
out DbCapture<TOut> output,
409+
[CallerArgumentExpression(nameof(output))] string? name = null)
410+
{
411+
CaptureSource<TOut> source = Captures.Output<TOut>(name);
412+
BoundCall<NonQueryKind> captured = WithCapture(call, source);
413+
output = new(source);
414+
return captured;
415+
}
416+
417+
/// <summary>
418+
/// Reads one <see cref="decimal"/> output parameter of the given precision
419+
/// and scale when the write runs. A NULL faults the capture;
420+
/// <c>CaptureOutputDecimal</c> reads it as <see langword="null"/>.
421+
/// </summary>
422+
/// <include file="Output.docs.xml" path="docs/members[@name='capture-decimal']/*" />
423+
/// <include file="Output.docs.xml" path="docs/members[@name='out-name-param']/*" />
424+
/// <include file="Output.docs.xml" path="docs/members[@name='capture-call']/*" />
425+
/// <param name="call">The bound write.</param>
426+
public static BoundCall<NonQueryKind> CaptureOutput(
427+
this BoundCall<NonQueryKind> call,
428+
out DbCapture<decimal> value,
429+
byte precision,
430+
byte scale,
431+
[CallerArgumentExpression(nameof(value))] string? name = null)
432+
{
433+
CaptureSource<decimal> source = Captures.Shaped(name, precision, scale);
434+
BoundCall<NonQueryKind> captured = WithCapture(call, source);
435+
value = new(source);
436+
return captured;
437+
}
438+
439+
/// <summary>
440+
/// Reads one <see cref="decimal"/> output parameter of the given precision
441+
/// and scale when the write runs.
442+
/// </summary>
443+
/// <include file="Output.docs.xml" path="docs/members[@name='capture-decimal']/*" />
444+
/// <include file="Output.docs.xml" path="docs/members[@name='out-name-param']/*" />
445+
/// <include file="Output.docs.xml" path="docs/members[@name='capture-call']/*" />
446+
/// <param name="call">The bound write.</param>
447+
public static BoundCall<NonQueryKind> CaptureOutputDecimal(
448+
this BoundCall<NonQueryKind> call,
449+
out DbCapture<decimal?> value,
450+
byte precision,
451+
byte scale,
452+
[CallerArgumentExpression(nameof(value))] string? name = null)
453+
{
454+
CaptureSource<decimal?> source = Captures.Decimal(name, precision, scale);
455+
BoundCall<NonQueryKind> captured = WithCapture(call, source);
456+
value = new(source);
457+
return captured;
458+
}
459+
460+
/// <summary>
461+
/// Reads the stored procedure's return code, converted to
462+
/// <typeparamref name="TValue"/>, when the write runs.
463+
/// </summary>
464+
/// <include file="Output.docs.xml" path="docs/members[@name='capture-return']/*" />
465+
/// <include file="Output.docs.xml" path="docs/members[@name='capture-call']/*" />
466+
/// <param name="call">The bound write.</param>
467+
public static BoundCall<NonQueryKind> CaptureReturn<TValue>(
468+
this BoundCall<NonQueryKind> call,
469+
out DbCapture<TValue> returnCode)
470+
{
471+
CaptureSource<TValue> source = Captures.Return<TValue>();
472+
BoundCall<NonQueryKind> captured = WithCapture(call, source);
473+
returnCode = new(source);
474+
return captured;
475+
}
476+
477+
/// <summary>
478+
/// Reads the output parameters into a <typeparamref name="TOut"/> when the
479+
/// query runs: a model by its members, or one value by the name of the
480+
/// variable.
481+
/// </summary>
482+
/// <typeparam name="T">The type of the scalar, from the call.</typeparam>
483+
/// <include file="Output.docs.xml" path="docs/members[@name='capture-model']/*" />
484+
/// <include file="Output.docs.xml" path="docs/members[@name='out-name-param']/*" />
485+
/// <include file="Output.docs.xml" path="docs/members[@name='capture-call']/*" />
486+
/// <param name="call">The bound scalar query.</param>
487+
public static BoundCall<ScalarKind<T>> CaptureOutput<T, TOut>(
488+
this BoundCall<ScalarKind<T>> call,
489+
out DbCapture<TOut> output,
490+
[CallerArgumentExpression(nameof(output))] string? name = null)
491+
{
492+
CaptureSource<TOut> source = Captures.Output<TOut>(name);
493+
BoundCall<ScalarKind<T>> captured = WithCapture(call, source);
494+
output = new(source);
495+
return captured;
496+
}
497+
498+
/// <summary>
499+
/// Reads one <see cref="decimal"/> output parameter of the given precision
500+
/// and scale when the query runs. A NULL faults the capture;
501+
/// <c>CaptureOutputDecimal</c> reads it as <see langword="null"/>.
502+
/// </summary>
503+
/// <typeparam name="T">The type of the scalar, from the call.</typeparam>
504+
/// <include file="Output.docs.xml" path="docs/members[@name='capture-decimal']/*" />
505+
/// <include file="Output.docs.xml" path="docs/members[@name='out-name-param']/*" />
506+
/// <include file="Output.docs.xml" path="docs/members[@name='capture-call']/*" />
507+
/// <param name="call">The bound scalar query.</param>
508+
public static BoundCall<ScalarKind<T>> CaptureOutput<T>(
509+
this BoundCall<ScalarKind<T>> call,
510+
out DbCapture<decimal> value,
511+
byte precision,
512+
byte scale,
513+
[CallerArgumentExpression(nameof(value))] string? name = null)
514+
{
515+
CaptureSource<decimal> source = Captures.Shaped(name, precision, scale);
516+
BoundCall<ScalarKind<T>> captured = WithCapture(call, source);
517+
value = new(source);
518+
return captured;
519+
}
520+
521+
/// <summary>
522+
/// Reads one <see cref="decimal"/> output parameter of the given precision
523+
/// and scale when the query runs.
524+
/// </summary>
525+
/// <typeparam name="T">The type of the scalar, from the call.</typeparam>
526+
/// <include file="Output.docs.xml" path="docs/members[@name='capture-decimal']/*" />
527+
/// <include file="Output.docs.xml" path="docs/members[@name='out-name-param']/*" />
528+
/// <include file="Output.docs.xml" path="docs/members[@name='capture-call']/*" />
529+
/// <param name="call">The bound scalar query.</param>
530+
public static BoundCall<ScalarKind<T>> CaptureOutputDecimal<T>(
531+
this BoundCall<ScalarKind<T>> call,
532+
out DbCapture<decimal?> value,
533+
byte precision,
534+
byte scale,
535+
[CallerArgumentExpression(nameof(value))] string? name = null)
536+
{
537+
CaptureSource<decimal?> source = Captures.Decimal(name, precision, scale);
538+
BoundCall<ScalarKind<T>> captured = WithCapture(call, source);
539+
value = new(source);
540+
return captured;
541+
}
542+
543+
/// <summary>
544+
/// Reads the stored procedure's return code, converted to
545+
/// <typeparamref name="TValue"/>, when the query runs.
546+
/// </summary>
547+
/// <typeparam name="T">The type of the scalar, from the call.</typeparam>
548+
/// <include file="Output.docs.xml" path="docs/members[@name='capture-return']/*" />
549+
/// <include file="Output.docs.xml" path="docs/members[@name='capture-call']/*" />
550+
/// <param name="call">The bound scalar query.</param>
551+
public static BoundCall<ScalarKind<T>> CaptureReturn<T, TValue>(
552+
this BoundCall<ScalarKind<T>> call,
553+
out DbCapture<TValue> returnCode)
554+
{
555+
CaptureSource<TValue> source = Captures.Return<TValue>();
556+
BoundCall<ScalarKind<T>> captured = WithCapture(call, source);
557+
returnCode = new(source);
558+
return captured;
559+
}
290560
}

0 commit comments

Comments
 (0)