diff --git a/Source/Core/BoundCall.cs b/Source/Core/BoundCall.cs
index 332ae864..47044b1b 100644
--- a/Source/Core/BoundCall.cs
+++ b/Source/Core/BoundCall.cs
@@ -11,6 +11,13 @@ namespace Open.Database.Extensions;
///
public readonly struct NonQueryKind;
+///
+/// Marks a chain that writes and reads output parameters: it ends in
+/// ExecuteOutputAsync.
+///
+/// What the outputs are read as.
+public readonly struct OutputKind;
+
///
/// A scalar query or a write bound to where its connections come from, with
/// the values added so far.
@@ -27,7 +34,16 @@ namespace Open.Database.Extensions;
///
public readonly struct BoundCall : IEquatable>
{
- internal BoundCall(DbQueryCall call) => Call = call;
+ internal BoundCall(DbQueryCall call, CaptureSet? captures = null)
+ {
+ Call = call;
+ Captures = captures;
+ }
+
+ // The captures the call carries, or null. Added by the capture extensions
+ // of BoundCallExtensions after Using and the parameters, and carried by
+ // every AddParam; compared by reference.
+ internal CaptureSet? Captures { get; }
// The same value a rows query holds: the definition, the source and the
// values.
@@ -39,26 +55,27 @@ namespace Open.Database.Extensions;
///
public BoundCall AddParams(TValues values)
where TValues : notnull
- => new(Call.AddParams(values));
+ => new(Call.AddParams(values), Captures);
///
public BoundCall AddParam(string name, TValue value)
- => new(Call.AddParam(name, value));
+ => new(Call.AddParam(name, value), Captures);
///
public BoundCall AddParam(string name, string? value)
- => new(Call.AddParam(name, value));
+ => new(Call.AddParam(name, value), Captures);
///
[OverloadResolutionPriority(-1)]
public BoundCall AddParam(
TValue value,
[CallerArgumentExpression(nameof(value))] string? expression = null)
- => new(Call.AddParam(value, expression));
+ => new(Call.AddParam(value, expression), Captures);
///
public bool Equals(BoundCall other)
- => Call.Equals(other.Call);
+ => Call.Equals(other.Call)
+ && ReferenceEquals(Captures, other.Captures);
///
public override bool Equals(object? obj)
@@ -83,7 +100,12 @@ public override int GetHashCode()
{
unchecked
{
- return Call.GetHashCode() * 31 + typeof(TKind).GetHashCode();
+ int hash = Call.GetHashCode() * 31 + typeof(TKind).GetHashCode();
+
+ // Without a capture the hash is what it always was.
+ return Captures is null
+ ? hash
+ : hash * 31 + RuntimeHelpers.GetHashCode(Captures);
}
}
}
@@ -262,11 +284,13 @@ public static class BoundCallExtensions
public static ValueTask ExecuteScalarAsync(
this BoundCall> call,
CancellationToken cancellationToken = default)
- => DbQueryRunner.ScalarAsync(
- call.Call.Definition,
- call.Call.SourceCore,
- call.Call.Params,
- cancellationToken);
+ => call.Captures is { } captures
+ ? DbQueryRunner.ScalarCapturedAsync(
+ call.Call.Definition, call.Call.SourceCore, call.Call.Params,
+ captures, cancellationToken)
+ : DbQueryRunner.ScalarAsync(
+ call.Call.Definition, call.Call.SourceCore,
+ call.Call.Params, cancellationToken);
/// Runs the write and returns the number of rows affected.
///
@@ -282,9 +306,255 @@ public static ValueTask ExecuteScalarAsync(
public static ValueTask ExecuteNonQueryAsync(
this BoundCall call,
CancellationToken cancellationToken = default)
- => DbQueryRunner.NonQueryAsync(
- call.Call.Definition,
+ => call.Captures is { } captures
+ ? DbQueryRunner.NonQueryCapturedAsync(
+ call.Call.Definition, call.Call.SourceCore, call.Call.Params,
+ captures, cancellationToken)
+ : DbQueryRunner.NonQueryAsync(
+ call.Call.Definition, call.Call.SourceCore,
+ call.Call.Params, cancellationToken);
+
+ ///
+ /// Runs the write and reads its output parameters (and return code) as the
+ /// definition declared with Output.
+ ///
+ ///
+ ///
+ ///
+ /// What the outputs are read as.
+ /// The bound call.
+ ///
+ /// A task that represents the asynchronous operation; its result is the model, or the one value.
+ /// Before the command executes: an output matches no parameter, or two match one, or is a value, which is bound to nothing.
+ ///
+ ///
+ ///
+ /// A value does not convert, or is NULL and the type does not take it.
+ /// is canceled.
+ public static ValueTask ExecuteOutputAsync(
+ this BoundCall> call,
+ CancellationToken cancellationToken = default)
+ => DbQueryRunner.OutputAsync(
+ call.Call.Definition, call.Call.SourceCore,
+ call.Call.Params, cancellationToken);
+
+ ///
+ /// Runs the write and returns the stored procedure's return code, converted
+ /// to .
+ ///
+ ///
+ ///
+ ///
+ /// The type of the return code: a single value such as .
+ /// The bound call.
+ ///
+ /// A task that represents the asynchronous operation; its result is the return code.
+ /// Before any connection is used: is a model, the call's definition is text (it has no return code), is a value, or a capture on the call reads the return code too.
+ /// is canceled.
+ public static ValueTask ExecuteReturnAsync(
+ this BoundCall call,
+ CancellationToken cancellationToken = default)
+ {
+ // All checked at the call, before a task exists or a connection is used.
+ ReturnCode.ThrowUnlessScalar();
+ DbQuery definition = call.Call.Definition;
+ if (definition.Kind != CommandType.StoredProcedure)
+ {
+ throw new InvalidOperationException(
+ $"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. "
+ + "Declare the definition with DbNonQuery.Procedure(name) to read the return code.");
+ }
+
+ // A capture of the return code and this would read it twice.
+ if (call.Captures?.ReturnReader is { } returnReader)
+ {
+ throw call.Captures.Refuse(
+ new InvalidOperationException(
+ CaptureMessages.ReturnBeside(returnReader)),
+ cancellationToken);
+ }
+
+ return DbQueryRunner.ReturnAsync(
+ definition,
call.Call.SourceCore,
call.Call.Params,
+ call.Captures,
cancellationToken);
+ }
+
+ // ---- captures: per kind, so a call made from Output has none ----
+
+ // Returns the call with one more capture, checked at the call. A
+ // definition's kind never changes, so the return code is checked here.
+ static BoundCall WithCapture(
+ BoundCall call,
+ ICaptureSource source)
+ => new(
+ call.Call,
+ CaptureSet.WithOnDefinition(
+ call.Captures, source, call.Call.Definition.Kind));
+
+ ///
+ /// Reads the output parameters into a when the
+ /// write runs: a model by its members, or one value by the name of the
+ /// variable.
+ ///
+ ///
+ ///
+ ///
+ /// The bound write.
+ public static BoundCall CaptureOutput(
+ this BoundCall call,
+ out DbCapture output,
+ [CallerArgumentExpression(nameof(output))] string? name = null)
+ {
+ CaptureSource source = Captures.Output(name);
+ BoundCall captured = WithCapture(call, source);
+ output = new(source);
+ return captured;
+ }
+
+ ///
+ /// Reads one output parameter of the given precision
+ /// and scale when the write runs. A NULL faults the capture;
+ /// CaptureOutputDecimal reads it as .
+ ///
+ ///
+ ///
+ ///
+ /// The bound write.
+ public static BoundCall CaptureOutput(
+ this BoundCall call,
+ out DbCapture value,
+ byte precision,
+ byte scale,
+ [CallerArgumentExpression(nameof(value))] string? name = null)
+ {
+ CaptureSource source = Captures.Shaped(name, precision, scale);
+ BoundCall captured = WithCapture(call, source);
+ value = new(source);
+ return captured;
+ }
+
+ ///
+ /// Reads one output parameter of the given precision
+ /// and scale when the write runs.
+ ///
+ ///
+ ///
+ ///
+ /// The bound write.
+ public static BoundCall CaptureOutputDecimal(
+ this BoundCall call,
+ out DbCapture value,
+ byte precision,
+ byte scale,
+ [CallerArgumentExpression(nameof(value))] string? name = null)
+ {
+ CaptureSource source = Captures.Decimal(name, precision, scale);
+ BoundCall captured = WithCapture(call, source);
+ value = new(source);
+ return captured;
+ }
+
+ ///
+ /// Reads the stored procedure's return code, converted to
+ /// , when the write runs.
+ ///
+ ///
+ ///
+ /// The bound write.
+ public static BoundCall CaptureReturn(
+ this BoundCall call,
+ out DbCapture returnCode)
+ {
+ CaptureSource source = Captures.Return();
+ BoundCall captured = WithCapture(call, source);
+ returnCode = new(source);
+ return captured;
+ }
+
+ ///
+ /// Reads the output parameters into a when the
+ /// query runs: a model by its members, or one value by the name of the
+ /// variable.
+ ///
+ /// The type of the scalar, from the call.
+ ///
+ ///
+ ///
+ /// The bound scalar query.
+ public static BoundCall> CaptureOutput(
+ this BoundCall> call,
+ out DbCapture output,
+ [CallerArgumentExpression(nameof(output))] string? name = null)
+ {
+ CaptureSource source = Captures.Output(name);
+ BoundCall> captured = WithCapture(call, source);
+ output = new(source);
+ return captured;
+ }
+
+ ///
+ /// Reads one output parameter of the given precision
+ /// and scale when the query runs. A NULL faults the capture;
+ /// CaptureOutputDecimal reads it as .
+ ///
+ /// The type of the scalar, from the call.
+ ///
+ ///
+ ///
+ /// The bound scalar query.
+ public static BoundCall> CaptureOutput(
+ this BoundCall> call,
+ out DbCapture value,
+ byte precision,
+ byte scale,
+ [CallerArgumentExpression(nameof(value))] string? name = null)
+ {
+ CaptureSource source = Captures.Shaped(name, precision, scale);
+ BoundCall> captured = WithCapture(call, source);
+ value = new(source);
+ return captured;
+ }
+
+ ///
+ /// Reads one output parameter of the given precision
+ /// and scale when the query runs.
+ ///
+ /// The type of the scalar, from the call.
+ ///
+ ///
+ ///
+ /// The bound scalar query.
+ public static BoundCall> CaptureOutputDecimal(
+ this BoundCall> call,
+ out DbCapture value,
+ byte precision,
+ byte scale,
+ [CallerArgumentExpression(nameof(value))] string? name = null)
+ {
+ CaptureSource source = Captures.Decimal(name, precision, scale);
+ BoundCall> captured = WithCapture(call, source);
+ value = new(source);
+ return captured;
+ }
+
+ ///
+ /// Reads the stored procedure's return code, converted to
+ /// , when the query runs.
+ ///
+ /// The type of the scalar, from the call.
+ ///
+ ///
+ /// The bound scalar query.
+ public static BoundCall> CaptureReturn(
+ this BoundCall> call,
+ out DbCapture returnCode)
+ {
+ CaptureSource source = Captures.Return();
+ BoundCall> captured = WithCapture(call, source);
+ returnCode = new(source);
+ return captured;
+ }
}
diff --git a/Source/Core/Capture.cs b/Source/Core/Capture.cs
index 17c77705..2f6e0c07 100644
--- a/Source/Core/Capture.cs
+++ b/Source/Core/Capture.cs
@@ -5,10 +5,11 @@ namespace Open.Database.Extensions;
//
// A capture call makes one source (a TaskCompletionSource the run completes)
// and attaches it to the chain as a new, immutable CaptureSet: the sources so
-// far plus the new one, appended. The command holds its set in one field; a
-// mapped query holds its own in MappedQueryCore, and a query without one runs
-// on its command, which uses the command's set: Map() shares the command's
-// capture, and the first run by either route takes it.
+// far plus the new one. The command holds its set in one field; a mapped
+// query keeps only its own in MappedQueryCore, and a run combines them with
+// the command's current set, the command's first. A query without its own runs
+// on its command's set: Map() shares the command's capture, and the first
+// run by either route takes it. A query from a definition has no command.
//
// The claim (the arm) is a compare-exchange on the set's first source. A set
// only ever grows at its end, so two chain values that share a capture share
@@ -33,7 +34,7 @@ enum CaptureKind : byte
Model,
/// One output parameter by name:
- /// CaptureOutput<TValue>(name, …) and
+ /// CaptureOutput(out DbCapture<int> total) and
/// CaptureOutputDecimal.
Named,
@@ -215,20 +216,23 @@ public Task Started(bool awaiting)
///
/// The model type.
/// The model's layout.
-sealed class ModelCapture(OutputLayout layout)
+/// The name the capture was given, which a model does not use, or .
+sealed class ModelCapture(OutputLayout layout, string? receivedName)
: CaptureSource(
- $"CaptureOutput<{Shape.TypeName(typeof(TOut))}>",
+ $"CaptureOutput(out DbCapture<{Shape.TypeName(typeof(TOut))}>)",
CaptureKind.Model)
{
// The members named for the messages as members of this capture.
public override ImmutableArray Members { get; }
- = Named(layout);
+ = Named(layout, receivedName);
public override bool ReadsReturn => layout.HasReturnValue;
- static ImmutableArray Named(OutputLayout layout)
+ static ImmutableArray Named(
+ OutputLayout layout,
+ string? receivedName)
{
- string capture = $"CaptureOutput<{Shape.TypeName(typeof(TOut))}>";
+ string capture = $"CaptureOutput(out DbCapture<{Shape.TypeName(typeof(TOut))}>)";
var members = ImmutableArray.CreateBuilder(
layout.Members.Length);
foreach (OutputMember member in layout.Members)
@@ -236,7 +240,8 @@ static ImmutableArray Named(OutputLayout layout)
members.Add(new OutputMember(
member,
$"{member.Display} of {capture}",
- OutputForm.Capture));
+ OutputForm.Capture,
+ receivedName));
}
return members.MoveToImmutable();
@@ -425,6 +430,37 @@ public static CaptureSet With(
return new([.. set.Sources, source], onQuery || set.OnQuery);
}
+ ///
+ /// Returns the captures of a definition's call with one more, as
+ /// does.
+ ///
+ ///
+ /// A definition's kind never changes, so a capture of the return code is
+ /// checked here, at the call; a command's type can, so a command checks
+ /// it when the run starts.
+ ///
+ /// The captures so far, or
+ /// .
+ /// The new capture.
+ /// The definition's kind.
+ /// The new set.
+ /// The capture reads the
+ /// return code of a definition that is not a stored procedure, or reads
+ /// what another capture reads.
+ public static CaptureSet WithOnDefinition(
+ CaptureSet? set,
+ ICaptureSource source,
+ CommandType kind)
+ {
+ if (source.ReadsReturn && kind != CommandType.StoredProcedure)
+ {
+ throw new InvalidOperationException(
+ CaptureMessages.NotProcedure(source));
+ }
+
+ return With(set, source, onQuery: true);
+ }
+
///
/// Returns what a run of a query fills when the query has captures of its
/// own and its command has some too: the command's, then the query's.
@@ -798,83 +834,104 @@ static class Captures
{
/// Makes the capture of an output model.
/// The model type.
+ /// The name the capture was given, which a model
+ /// does not use, or .
/// The capture.
///
/// cannot be read from output parameters.
- public static CaptureSource Model()
- => new ModelCapture(OutputLayout.Get(OutputForm.Capture));
+ public static CaptureSource Model(string? receivedName = null)
+ => new ModelCapture(
+ OutputLayout.Get(OutputForm.Capture),
+ receivedName);
+
+ /// Makes the capture of an output model, or, when
+ /// is a single value, of the parameter its name
+ /// gives.
+ /// The model type, or the type of the value.
+ /// The text of the capture's name argument: the
+ /// variable's declaration, or what the caller typed. A model never derives
+ /// or refuses a name.
+ /// The capture.
+ /// A single value has no name in
+ /// .
+ public static CaptureSource Output(string? name)
+ => Shape.IsScalar(typeof(TOut))
+ ? Named(CaptureNames.From(name))
+ : Model(CaptureNames.TryFrom(name)?.Name);
/// Makes the capture of one output parameter by name.
/// The type of the value.
/// The parameter's name.
/// The capture.
- public static CaptureSource Named(string name)
+ public static CaptureSource Named(CaptureName name)
{
- OutputArguments.ThrowIfNoName(name, OutputForm.Capture);
- OutputLayout layout = OutputValue.Get(name, OutputForm.Capture);
+ OutputLayout layout = OutputValue.Get(
+ name.Name,
+ OutputForm.Capture,
+ name.Candidates);
return new NamedCapture(
layout,
- name,
+ name.Name,
layout.Members[0].Display);
}
- /// Makes the capture of one decimal output parameter, read as
- /// .
- /// , or a
- /// of it.
- /// The parameter's name.
+ /// Makes the capture of one decimal output parameter, read as a
+ /// .
+ /// The text of the capture's name argument.
/// The precision.
/// The scale.
/// The capture.
- public static CaptureSource Shaped(
- string name,
+ public static CaptureSource Shaped(
+ string? name,
byte precision,
byte scale)
{
- OutputArguments.ThrowIfNoName(name, OutputForm.Capture);
- OutputValue.ThrowUnlessDecimal(name, OutputForm.Capture);
- return Decimal(
- name,
+ CaptureName derived = CaptureNames.From(name);
+ return Decimal(
+ derived,
precision,
scale,
- $"CaptureOutput<{Shape.TypeName(typeof(TValue))}>"
- + $"(\"{name}\", {precision}, {scale})");
+ $"CaptureOutput(out DbCapture {derived.Name}, "
+ + $"{precision}, {scale})");
}
/// Makes the capture of one decimal output parameter, read as a
/// of .
- /// The parameter's name.
+ /// The text of the capture's name argument.
/// The precision.
/// The scale.
/// The capture.
public static CaptureSource Decimal(
- string name,
+ string? name,
byte precision,
byte scale)
{
- OutputArguments.ThrowIfNoName(name, OutputForm.Capture);
+ CaptureName derived = CaptureNames.From(name);
return Decimal(
- name,
+ derived,
precision,
scale,
- $"CaptureOutputDecimal(\"{name}\", {precision}, {scale})");
+ $"CaptureOutputDecimal(out DbCapture {derived.Name}, "
+ + $"{precision}, {scale})");
}
// The one implementation of both decimal forms.
static NamedCapture Decimal(
- string name,
+ CaptureName name,
byte precision,
byte scale,
string display)
{
OutputArguments.ThrowIfBadShape(
- name,
+ name.Name,
precision,
scale,
OutputForm.Capture);
return new NamedCapture(
- OutputValue.Shaped(name, precision, scale, display),
- name,
+ OutputValue.Shaped(
+ name.Name, precision, scale,
+ display, OutputForm.Capture, name.Candidates),
+ name.Name,
display);
}
@@ -1017,13 +1074,6 @@ public static string ReturnModel(string type)
+ "Use CaptureReturn (or int?, long, an enum), "
+ "or a ReturnValue member on the output model.";
- public static string NotFromDefinition(ICaptureSource source)
- => $"{source.Display} needs a query built from an expressive command "
- + "(connection.Command(…).Map()); "
- + "a query from a DbQuery definition cannot take a capture. "
- + "Build it from a command, "
- + "or read the outputs with ExecuteOutputAsync.";
-
public static string NotFromCommand(ICaptureSource source, Type reader)
=> $"{source.Display} needs a query built from an expressive command "
+ "(connection.Command(…).Map()), "
diff --git a/Source/Core/CaptureNames.cs b/Source/Core/CaptureNames.cs
new file mode 100644
index 00000000..19913c62
--- /dev/null
+++ b/Source/Core/CaptureNames.cs
@@ -0,0 +1,142 @@
+using System.Runtime.CompilerServices;
+
+namespace Open.Database.Extensions;
+
+///
+/// The name a capture reads, and the names it is matched by.
+///
+/// The name.
+sealed class CaptureName(string name)
+{
+ /// Gets the derived name.
+ public string Name { get; } = name;
+
+ ///
+ /// Gets the names the capture is matched by, most specific first: the name
+ /// as written, then without an m_ or s_ prefix
+ /// (m_total gives total). A leading underscore is left to the
+ /// matcher's underscore tier. The default value means only
+ /// .
+ ///
+ public ImmutableArray Candidates { get; } = Prefixed(name);
+
+ static ImmutableArray Prefixed(string name)
+ {
+ int prefix = ParameterNames.FieldPrefixLength(name, 0, name.Length);
+ return prefix < 2
+ ? default
+ : [name, name[prefix..]];
+ }
+}
+
+///
+/// Reads the name of an output parameter from the text of the capture's
+/// name argument: what the compiler supplies from the variable
+/// (DbCapture<int> total, this.total), or what the caller
+/// typed ("total"). One rule for both.
+///
+static class CaptureNames
+{
+ // Texts that are not one plain name are worked out once each. The table
+ // holds one entry per distinct such text, weakly: an entry is released with
+ // its text, so a typed text built at runtime adds entries until it is
+ // collected. A plain name has no entry.
+ static readonly ConditionalWeakTable Cache = new();
+
+ sealed class Parsed(CaptureName? name)
+ {
+ public CaptureName? Name { get; } = name;
+ }
+
+ ///
+ /// Gets the name the text gives.
+ ///
+ /// The text of the argument, or what was passed.
+ /// The name.
+ /// No name can be taken from the
+ /// text.
+ public static CaptureName From(string? text)
+ => TryFrom(text) ?? throw NoName(text);
+
+ ///
+ /// Gets the name the text gives, or when it gives
+ /// none.
+ ///
+ /// The text of the argument, or what was passed.
+ /// The name, or .
+ public static CaptureName? TryFrom(string? text)
+ {
+ if (string.IsNullOrWhiteSpace(text)) return null;
+
+ if (IsPlain(text!))
+ {
+ // A typed value: "$", "#" and the like are part of the name; one
+ // leading @ or : is dropped.
+ string plain = text![0] is '@' or ':' ? text[1..] : text;
+ return plain.Length == 0 || plain == "_"
+ ? null
+ : new CaptureName(plain);
+ }
+
+ return Cache
+ .GetValue(text!, static t => new Parsed(Derive(t)))
+ .Name;
+ }
+
+ // A plain name has none of the characters of a declaration or a chain.
+ static bool IsPlain(string text)
+ {
+ foreach (char c in text)
+ {
+ if (c is '.' or '[' or ']' or '(' or ')' or '<' or '>' or ','
+ || char.IsWhiteSpace(c))
+ {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ // The last identifier: the declared variable (after its type), a local,
+ // or the last member of a chain. A discard, an element access that ends the
+ // text, and anything that does not end in an identifier have none.
+ static CaptureName? Derive(string text)
+ {
+ int end = text.Length;
+ while (end > 0 && char.IsWhiteSpace(text[end - 1])) end--;
+
+ int start = end;
+ while (start > 0
+ && (char.IsLetterOrDigit(text[start - 1]) || text[start - 1] == '_'))
+ {
+ start--;
+ }
+
+ if (start == end || char.IsDigit(text[start])) return null;
+
+ string name = text[start..end];
+ return name == "_" ? null : new CaptureName(name);
+ }
+
+ // The argument is the capture's name, which the caller sees as the optional
+ // last argument of every capture call.
+ [SuppressMessage(
+ "Usage",
+ "CA2208:Instantiate argument exceptions correctly")]
+ static ArgumentException NoName(string? text)
+ => new(
+ (text is null
+ ? "The output parameter's name was not given: the compiler did "
+ + "not supply the variable's name (that needs a C# 10 compiler "
+ + "or newer, and a dynamic call gives none), or null was "
+ + "passed. "
+ : string.IsNullOrWhiteSpace(text)
+ ? "The output parameter's name is empty: the name passed last "
+ + "is empty or only white space. "
+ : $"Cannot take the output parameter's name from '{text}': a "
+ + "discard (_) and an element access (arr[0]) have no name. ")
+ + "Declare a variable named after the parameter, or pass the name "
+ + "last: CaptureOutput(out DbCapture x, \"total\").",
+ "name");
+}
diff --git a/Source/Core/DbNonQuery.cs b/Source/Core/DbNonQuery.cs
index e712ce1a..bfeaaa07 100644
--- a/Source/Core/DbNonQuery.cs
+++ b/Source/Core/DbNonQuery.cs
@@ -26,7 +26,10 @@ namespace Open.Database.Extensions;
/// For rows use , and for one value
/// .
/// The connection is opened late and released as releases
-/// it. Output and return parameters are not supported.
+/// it.
+/// Outputs are read by (a model) or
+/// (one value), and the return code by
+/// ExecuteReturnAsync on the bound call.
///
///
public sealed class DbNonQuery : IEquatable
@@ -58,6 +61,76 @@ public DbNonQuery Params()
where TParams : struct, IEquatable
=> new(_definition.Params());
+ ///
+ /// Declares that the definition reads its output parameters and return code
+ /// into a .
+ ///
+ ///
+ ///
+ ///
+ /// The model the outputs are read into.
+ /// The definition, to be run with ExecuteOutputAsync.
+ ///
+ /// has no member to read, is a single value, has a member without its type name, or reads the return code of a text definition.
+ /// The message names the definition and the model.
+ ///
+ public OutputDbNonQuery Output()
+ => new(OutputDefinitions.Model(_definition));
+
+ ///
+ /// Declares that the definition reads one output parameter, converted to
+ /// .
+ ///
+ ///
+ ///
+ ///
+ /// The type of the value.
+ ///
+ /// The definition, to be run with ExecuteOutputAsync.
+ /// is not a single value, is a , or has no database type.
+ public OutputDbNonQuery Output(string name)
+ => new(OutputDefinitions.Named(_definition, name));
+
+ ///
+ /// Declares that the definition reads one output
+ /// parameter of the given precision and scale, converted to
+ /// .
+ ///
+ ///
+ ///
+ ///
+ /// , or a of it.
+ ///
+ /// The precision, from 1 to 38.
+ /// The scale, up to the precision.
+ /// The definition, to be run with ExecuteOutputAsync.
+ /// is not a .
+ /// The precision or the scale is not a decimal's.
+ public OutputDbNonQuery Output(
+ string name,
+ byte precision,
+ byte scale)
+ => new(OutputDefinitions.Shaped(_definition, name, precision, scale));
+
+ ///
+ /// Declares that the definition reads one output
+ /// parameter of the given precision and scale, as a
+ /// of .
+ ///
+ ///
+ ///
+ ///
+ ///
+ /// The precision, from 1 to 38.
+ /// The scale, up to the precision.
+ /// The definition, to be run with ExecuteOutputAsync; NULL reads as .
+ /// The precision or the scale is not a decimal's.
+ public OutputDbNonQuery OutputDecimal(
+ string name,
+ byte precision,
+ byte scale)
+ => new(OutputDefinitions.Decimal(_definition, name, precision, scale));
+
///
/// The write, bound.
public BoundCall Using(DbConnection connection)
@@ -170,4 +243,74 @@ public BoundParams Using(
where TConnection : DbConnection
// DbQuery.Using throws ArgumentNullException for a null source.
=> new(_definition.Using(factory));
+
+ ///
+ /// Declares that the definition reads its output parameters and return code
+ /// into a .
+ ///
+ ///
+ ///
+ ///
+ /// The model the outputs are read into.
+ /// The definition, to be run with ExecuteOutputAsync.
+ ///
+ /// has no member to read, is a single value, has a member without its type name, or reads the return code of a text definition.
+ /// The message names the definition and the model.
+ ///
+ public OutputDbNonQuery Output()
+ => new(new DbQuery(OutputDefinitions.Model(_definition.Definition)));
+
+ ///
+ /// Declares that the definition reads one output parameter, converted to
+ /// .
+ ///
+ ///
+ ///
+ ///
+ /// The type of the value.
+ ///
+ /// The definition, to be run with ExecuteOutputAsync.
+ /// is not a single value, is a , or has no database type.
+ public OutputDbNonQuery Output(string name)
+ => new(new DbQuery(OutputDefinitions.Named(_definition.Definition, name)));
+
+ ///
+ /// Declares that the definition reads one output
+ /// parameter of the given precision and scale, converted to
+ /// .
+ ///
+ ///
+ ///
+ ///
+ /// , or a of it.
+ ///
+ /// The precision, from 1 to 38.
+ /// The scale, up to the precision.
+ /// The definition, to be run with ExecuteOutputAsync.
+ /// is not a .
+ /// The precision or the scale is not a decimal's.
+ public OutputDbNonQuery Output(
+ string name,
+ byte precision,
+ byte scale)
+ => new(new DbQuery(OutputDefinitions.Shaped(_definition.Definition, name, precision, scale)));
+
+ ///
+ /// Declares that the definition reads one output
+ /// parameter of the given precision and scale, as a
+ /// of .
+ ///
+ ///
+ ///
+ ///
+ ///
+ /// The precision, from 1 to 38.
+ /// The scale, up to the precision.
+ /// The definition, to be run with ExecuteOutputAsync; NULL reads as .
+ /// The precision or the scale is not a decimal's.
+ public OutputDbNonQuery OutputDecimal(
+ string name,
+ byte precision,
+ byte scale)
+ => new(new DbQuery(OutputDefinitions.Decimal(_definition.Definition, name, precision, scale)));
}
diff --git a/Source/Core/DbQuery.cs b/Source/Core/DbQuery.cs
index 84bd3b07..e747c402 100644
--- a/Source/Core/DbQuery.cs
+++ b/Source/Core/DbQuery.cs
@@ -37,14 +37,35 @@ namespace Open.Database.Extensions;
///
public sealed class DbQuery : IEquatable
{
- DbQuery(string text, CommandType kind, int timeout, NameSet? textNames)
+ DbQuery(
+ string text,
+ CommandType kind,
+ int timeout,
+ NameSet? textNames,
+ OutputLayout? output = null)
{
CommandText = text;
Kind = kind;
Timeout = timeout;
TextNames = textNames;
+ Output = output;
}
+ ///
+ /// Gets the output parameters a definition made by Output reads, or
+ /// .
+ ///
+ // Immutable and kept by the definition, so every call of it shares one.
+ // A model, a name and a precision and scale are judged when the definition
+ // is declared.
+ internal OutputLayout? Output { get; }
+
+ /// Returns the definition with the outputs it reads.
+ /// The outputs.
+ /// The new definition; this one is not changed.
+ internal DbQuery WithOutput(OutputLayout layout)
+ => new(CommandText, Kind, Timeout, TextNames, layout);
+
///
/// Gets the @name markers of a text definition, found once when it
/// is made; for a procedure.
@@ -180,7 +201,7 @@ static string Checked(string text, string paramName)
///
/// The new definition.
public DbQuery SetTimeout(ushort seconds)
- => new(CommandText, Kind, seconds, TextNames);
+ => new(CommandText, Kind, seconds, TextNames, Output);
///
/// Maps each row to a by column name (a single value such as
@@ -354,7 +375,8 @@ public bool Equals(DbQuery? other)
&& string.Equals(
CommandText,
other.CommandText,
- StringComparison.Ordinal));
+ StringComparison.Ordinal)
+ && OutputLayout.Same(Output, other.Output));
///
public override bool Equals(object? obj)
@@ -367,7 +389,12 @@ public override int GetHashCode()
{
int h = StringComparer.Ordinal.GetHashCode(CommandText);
h = h * 31 + (int)Kind;
- return h * 31 + Timeout;
+ h = h * 31 + Timeout;
+
+ // A definition without outputs hashes as before.
+ return Output is null
+ ? h
+ : h * 31 + OutputLayout.Hash(Output);
}
}
}
@@ -382,15 +409,16 @@ public override int GetHashCode()
public sealed class DbQuery
where TParams : struct, IEquatable
{
- readonly DbQuery _definition;
+ // The definition without the type of its values.
+ internal DbQuery Definition { get; }
- internal DbQuery(DbQuery definition) => _definition = definition;
+ internal DbQuery(DbQuery definition) => Definition = definition;
/// Maps each row to a by column name, and returns the mapped definition.
/// The type each row is mapped to.
/// The mapped definition, whose parameters are the struct.
public MappedDbQuery Map()
- => new(_definition.Map());
+ => new(Definition.Map());
/// Maps each row to a with a map the caller declared, and returns the mapped definition.
/// The type each row is mapped to.
@@ -399,7 +427,7 @@ public MappedDbQuery Map()
// A bare null does not compile here (it also fits the selector overload):
// write (RowMap?)null.
public MappedDbQuery Map(RowMap? map)
- => new(_definition.Map(map));
+ => new(Definition.Map(map));
/// Maps each row with a selector, and returns the mapped definition.
/// The type each row is mapped to.
@@ -408,17 +436,17 @@ public MappedDbQuery Map(RowMap? map)
/// is .
public MappedDbQuery Map(Func selector)
// DbQuery.Map throws ArgumentNullException for a null selector.
- => new(_definition.Map(selector));
+ => new(Definition.Map(selector));
///
/// The mapped definition, whose parameters are the struct.
public MappedDbQuery AsObjectArrays()
- => new(_definition.AsObjectArrays());
+ => new(Definition.AsObjectArrays());
///
/// The mapped definition, whose parameters are the struct.
public MappedDbQuery AsDictionaryRows()
- => new(_definition.AsDictionaryRows());
+ => new(Definition.AsDictionaryRows());
///
/// The scalar definition, whose parameters are the struct.
@@ -428,14 +456,14 @@ public ScalarDbQuery Scalar()
///
public DbQueryUsing Using(DbConnection connection)
=> new(
- _definition,
+ Definition,
connection ?? throw new ArgumentNullException(
nameof(connection)));
///
public DbQueryUsing Using(DbTransaction transaction)
=> new(
- _definition,
+ Definition,
transaction ?? throw new ArgumentNullException(
nameof(transaction)));
@@ -444,7 +472,7 @@ public DbQueryUsing Using(
IDbConnectionPool pool)
where TConnection : DbConnection
=> new(
- _definition,
+ Definition,
pool ?? throw new ArgumentNullException(
nameof(pool)));
@@ -453,7 +481,7 @@ public DbQueryUsing Using(
IDbConnectionFactory factory)
where TConnection : DbConnection
=> new(
- _definition,
+ Definition,
factory ?? throw new ArgumentNullException(
nameof(factory)));
}
diff --git a/Source/Core/DbQueryCall.cs b/Source/Core/DbQueryCall.cs
index a1a8112d..d6b87780 100644
--- a/Source/Core/DbQueryCall.cs
+++ b/Source/Core/DbQueryCall.cs
@@ -346,6 +346,17 @@ internal TResult Run(
transform,
behavior);
+ /// Runs the query with the given state and fills captures.
+ internal ValueTask RunCapturedAsync(
+ CaptureHolder captures,
+ TState state,
+ Func> transform,
+ CommandBehavior behavior,
+ CancellationToken cancellationToken)
+ => DbQueryRunner.RunCapturedAsync(
+ Definition, SourceCore, Params, captures,
+ state, transform, behavior, cancellationToken);
+
///
internal ValueTask RunAsync(
TState state,
diff --git a/Source/Core/DbQueryRunner.Output.cs b/Source/Core/DbQueryRunner.Output.cs
new file mode 100644
index 00000000..5f7f5e65
--- /dev/null
+++ b/Source/Core/DbQueryRunner.Output.cs
@@ -0,0 +1,447 @@
+namespace Open.Database.Extensions;
+
+// The runs of a definition's call that read output parameters: the outputs of
+// an Output() definition, and the captures of a call. A call without
+// either never comes here: it runs the methods of DbQueryRunner.cs, which are
+// untouched.
+static partial class DbQueryRunner
+{
+ ///
+ /// The layout of the return code of ExecuteReturnAsync<T>, per
+ /// type.
+ ///
+ /// The type of the return code.
+ static class ReturnOutput
+ {
+ public static readonly OutputLayout Layout = ReturnLayout(
+ $"ExecuteReturnAsync<{Shape.TypeName(typeof(T))}>()");
+ }
+
+ static OutputLayout ReturnLayout(string display)
+ => new(
+ display,
+ [new OutputMember(OutputLayout.ReturnValue, display, named: true)],
+ [0],
+ [OutputLayout.ReturnValue]);
+
+ // The captures' values one after another, then the return code.
+ static OutputLayout WithReturn(OutputLayout layout)
+ {
+ string display = "ExecuteReturnAsync<>()";
+ return new(
+ layout.Model,
+ layout.Members.Add(
+ new OutputMember(OutputLayout.ReturnValue, display, named: true)),
+ new int[layout.Members.Length + 1],
+ []);
+ }
+
+ // A call that reads an output parameter of a procedure is checked against
+ // the procedure's parameter metadata, as a command's call is: read once for
+ // a procedure's own set of names, then kept with it.
+ static ValueTask EnsureMetadataAsync(
+ DbConnection connection,
+ DbQuery definition,
+ NameSet? names,
+ OutputRun output,
+ CancellationToken cancellationToken)
+ => output.Layout.HasOutputParameter
+ && names is { Home: not null, Names.Length: > 0, Metadata: null }
+ ? ProcedureParameterMetadata.EnsureAsync(
+ connection,
+ definition.CommandText,
+ names,
+ cancellationToken)
+ : default;
+
+ // As Make, then the outputs: resolved with the names and added after the
+ // values, which a value of the same name turns into InputOutput.
+ static DbCommand MakeWithOutput(
+ DbConnection connection,
+ DbTransaction? transaction,
+ DbQuery definition,
+ ParamList call,
+ NameSet? names,
+ OutputRun output)
+ {
+ DbCommand command = connection.CreateCommand();
+ try
+ {
+ command.Transaction = transaction;
+ command.CommandText = definition.CommandText;
+ command.CommandType = definition.Kind;
+ if (definition.Timeout >= 0)
+ command.CommandTimeout = definition.Timeout;
+ call.BindAll(command, definition, names);
+ OutputBinding.Resolve(
+ output,
+ names,
+ definition.Kind,
+ definition.CommandText);
+ OutputBinding.Add(
+ command,
+ output,
+ new OutputBinding.CommandInputs(command));
+ return command;
+ }
+ catch
+ {
+ command.Dispose();
+ throw;
+ }
+ }
+
+ ///
+ /// Asynchronously runs the output model or the one named output of a
+ /// definition made by Output.
+ ///
+ /// The type read.
+ /// The definition, with its outputs.
+ /// The connection, transaction, pool or factory.
+ /// The bound parameters.
+ ///
+ /// A task that represents the asynchronous operation; its result is the value.
+ public static ValueTask OutputAsync(
+ DbQuery definition,
+ object source,
+ ParamList call,
+ CancellationToken cancellationToken)
+ {
+ OutputLayout layout = definition.Output
+ ?? throw new InvalidOperationException(
+ "This call's definition declares no outputs: make it with Output().");
+ return ExecuteWithOutputAsync(
+ definition, source, call,
+ new OutputRun(layout),
+ static (command, token) => command.ExecuteNonQueryAsync(token),
+ static (_, run) => run.Layout.Members[0].Named
+ ? Single(run)
+ : run.Map(),
+ cancellationToken);
+ }
+
+ // A decimal read as decimal (not decimal?) refuses NULL with the message of
+ // the declared form.
+ static T Single(OutputRun run)
+ {
+ object? value = run.Value(0);
+ return typeof(T) == typeof(decimal) && value is DBNull
+ ? throw OutputArguments.DecimalNull(
+ run.Layout.Members[0].Name,
+ OutputForm.Definition)
+ : run.Single();
+ }
+
+ ///
+ /// Asynchronously runs a write and reads the return code.
+ ///
+ /// The type of the return code.
+ /// The definition.
+ /// The connection, transaction, pool or factory.
+ /// The bound parameters.
+ ///
+ /// The captures beside it, or .
+ /// A task that represents the asynchronous operation; its result is the return code.
+ public static ValueTask ReturnAsync(
+ DbQuery definition,
+ object source,
+ ParamList call,
+ CaptureSet? captures,
+ CancellationToken cancellationToken)
+ => captures is null
+ ? ExecuteWithOutputAsync(
+ definition, source, call,
+ new OutputRun(ReturnOutput.Layout),
+ static (command, token) => command.ExecuteNonQueryAsync(token),
+ static (_, run) => run.Single(),
+ cancellationToken)
+ : CapturedAsync(
+ definition, source, call,
+ captures, WithReturn,
+ static (command, token) => command.ExecuteNonQueryAsync(token),
+ static (_, run) => RowMap.ConvertScalar(
+ run.Value(run.Layout.Members.Length - 1)),
+ cancellationToken);
+
+ /// Asynchronously runs a write that fills captures.
+ /// The definition.
+ /// The connection, transaction, pool or factory.
+ /// The bound parameters.
+ ///
+ /// The captures.
+ /// A task that represents the asynchronous operation; its result is the number of rows affected.
+ public static ValueTask NonQueryCapturedAsync(
+ DbQuery definition,
+ object source,
+ ParamList call,
+ CaptureSet captures,
+ CancellationToken cancellationToken)
+ => CapturedAsync(
+ definition, source, call,
+ captures, static layout => layout,
+ static (command, token) => command.ExecuteNonQueryAsync(token),
+ static (count, _) => count,
+ cancellationToken);
+
+ /// Asynchronously runs a scalar query that fills captures.
+ /// The type of the value.
+ /// The definition.
+ /// The connection, transaction, pool or factory.
+ /// The bound parameters.
+ /// The captures.
+ ///
+ /// A task that represents the asynchronous operation; its result is the value.
+ public static ValueTask ScalarCapturedAsync(
+ DbQuery definition,
+ object source,
+ ParamList call,
+ CaptureSet captures,
+ CancellationToken cancellationToken)
+ => CapturedAsync(
+ definition, source, call,
+ captures, static layout => layout,
+ static (command, token) => command.ExecuteScalarAsync(token),
+ static (value, _) => RowMap.ConvertScalar(
+ value,
+ nameof(BoundCallExtensions.ExecuteScalarAsync)),
+ cancellationToken);
+
+ // Claims the captures, runs, and completes every capture on every exit:
+ // the claim is the first statement, reached synchronously from the
+ // terminal. The layout function gives what the run reads: the captures'
+ // layout as is, or with the return code after it.
+ static async ValueTask CapturedAsync(
+ DbQuery definition,
+ object source,
+ ParamList call,
+ CaptureHolder captures,
+ Func layout,
+ Func> execute,
+ Func convert,
+ CancellationToken cancellationToken)
+ {
+ CaptureRun run = captures.Start(cancellationToken);
+ try
+ {
+ return await ExecuteWithOutputAsync(
+ definition, source, call,
+ new OutputRun(layout(run.Set.Layout)),
+ execute,
+ (value, output) =>
+ {
+ // The conversion of each capture happens once, there. The
+ // terminal's own conversion may still throw: the terminal
+ // throws, and the captures keep the values already
+ // delivered.
+ run.Deliver(output);
+ return convert(value, output);
+ },
+ cancellationToken)
+ .ConfigureAwait(false);
+ }
+ catch (Exception ex)
+ {
+ run.Fail(ex);
+ throw;
+ }
+ // A finally, not a dispose: whatever the run left pending is completed on
+ // every exit, which a dispose cannot express.
+ finally
+ {
+ run.Backstop();
+ }
+ }
+
+ // A scalar and a write that read outputs: the run of ExecuteAsync, with
+ // the outputs resolved and copied off the command before it is disposed.
+ static async ValueTask ExecuteWithOutputAsync(
+ DbQuery definition,
+ object source,
+ ParamList call,
+ OutputRun output,
+ Func> execute,
+ Func convert,
+ CancellationToken cancellationToken)
+ {
+ // Cancelled awaited tasks throw, so this does too.
+ cancellationToken.ThrowIfCancellationRequested();
+ output.Token = cancellationToken;
+
+ TValue value;
+ // The run is a block of its own, so everything is released at its end.
+ {
+ Lease lease = await Lease
+ .OpenAsync(source, cancellationToken)
+ .ConfigureAwait(false);
+ await using var leaseDisposal = lease.ConfigureAwait(false);
+ NameSet? names = null;
+ DbCommand built;
+ try
+ {
+ names = await ResolveAsync(
+ definition,
+ source,
+ lease.Connection,
+ cancellationToken)
+ .ConfigureAwait(false);
+ await EnsureMetadataAsync(
+ lease.Connection, definition, names, output,
+ cancellationToken)
+ .ConfigureAwait(false);
+ built = MakeWithOutput(
+ lease.Connection, lease.Transaction,
+ definition, call, names, output);
+ }
+ catch (Exception ex) when (ProcedureParameterNames.ForgetUnlessCanceled(names, ex))
+ {
+ throw;
+ }
+
+#if NETSTANDARD2_0
+ using DbCommand command = built;
+#else
+ DbCommand command = built;
+ await using var commandDisposal = command.ConfigureAwait(false);
+#endif
+ try
+ {
+ value = await execute(command, cancellationToken)
+ .ConfigureAwait(false);
+ output.Snapshot();
+ }
+ catch (DbException) when (ProcedureParameterNames.Forget(names))
+ {
+ throw;
+ }
+ }
+
+ return convert(value, output);
+ }
+
+ ///
+ /// Asynchronously runs the query of a definition's call, passes the reader
+ /// to a function and fills captures.
+ ///
+ /// The type of the state passed to the function.
+ /// The type of the result.
+ /// The definition.
+ /// The connection, transaction, pool or factory.
+ /// The bound parameters.
+ ///
+ /// The captures: a set to claim, or a run a stream or a buffer has claimed.
+ /// The state to pass to .
+ /// The function that reads the reader.
+ /// The behavior to run the reader with.
+ /// A task that represents the asynchronous operation; its result is the result of .
+ public static async ValueTask RunCapturedAsync(
+ DbQuery definition,
+ object source,
+ ParamList call,
+ CaptureHolder captures,
+ TState state,
+ Func> transform,
+ CommandBehavior behavior,
+ CancellationToken cancellationToken)
+ {
+ CaptureRun run = captures.Start(cancellationToken);
+ try
+ {
+ // Cancelled awaited tasks throw, so this does too.
+ cancellationToken.ThrowIfCancellationRequested();
+ var output = new OutputRun(run.Set.Layout)
+ {
+ Token = cancellationToken,
+ };
+
+ TResult result;
+ {
+ Lease lease = await Lease
+ .OpenAsync(source, cancellationToken)
+ .ConfigureAwait(false);
+ await using var leaseDisposal = lease.ConfigureAwait(false);
+ NameSet? names = null;
+ DbCommand built;
+ try
+ {
+ names = await ResolveAsync(
+ definition,
+ source,
+ lease.Connection,
+ cancellationToken)
+ .ConfigureAwait(false);
+ await EnsureMetadataAsync(
+ lease.Connection, definition, names, output,
+ cancellationToken)
+ .ConfigureAwait(false);
+ built = MakeWithOutput(
+ lease.Connection, lease.Transaction,
+ definition, call, names, output);
+ }
+ catch (Exception ex) when (ProcedureParameterNames.ForgetUnlessCanceled(names, ex))
+ {
+ throw;
+ }
+
+#if NETSTANDARD2_0
+ using DbCommand command = built;
+#else
+ DbCommand command = built;
+ await using var commandDisposal = command.ConfigureAwait(false);
+#endif
+ try
+ {
+ ReaderAbandon.ArmFor(transform, command);
+ CommandBehavior b = lease.Behavior(behavior);
+ try
+ {
+ // The reader is closed before the outputs are copied.
+ {
+#if NETSTANDARD2_0
+ using DbDataReader reader = await command
+ .ExecuteReaderAsync(b, cancellationToken)
+ .ConfigureAwait(false);
+#else
+ DbDataReader reader = await command
+ .ExecuteReaderAsync(b, cancellationToken)
+ .ConfigureAwait(false);
+ await using var readerDisposal = reader.ConfigureAwait(false);
+#endif
+ result = await transform(reader, state)
+ .ConfigureAwait(false);
+ }
+
+ output.Snapshot();
+ }
+ catch (OperationCanceledException) when (run.StoppedByConsumer)
+ {
+ // The consumer stopped early (a break, a dispose): the
+ // outputs are there because closing the reader drained
+ // the rest of the response, and the stream's own stop
+ // is not the caller's failure.
+ output.Snapshot();
+ run.Deliver(output);
+ throw;
+ }
+ }
+ catch (DbException) when (ProcedureParameterNames.Forget(names))
+ {
+ throw;
+ }
+ }
+
+ run.Deliver(output);
+ return result;
+ }
+ catch (Exception ex)
+ {
+ run.Fail(ex);
+ throw;
+ }
+ // A finally, not a dispose: whatever the run left pending is completed on
+ // every exit, which a dispose cannot express.
+ finally
+ {
+ run.Backstop();
+ }
+ }
+}
diff --git a/Source/Core/DbQueryRunner.cs b/Source/Core/DbQueryRunner.cs
index 55a47d76..f47ed595 100644
--- a/Source/Core/DbQueryRunner.cs
+++ b/Source/Core/DbQueryRunner.cs
@@ -12,7 +12,7 @@ namespace Open.Database.Extensions;
/// A connection of the caller's is closed again if the run opened it, and stays open if it was open;
/// one from a factory is disposed and one from a pool is given back (see ).
///
-static class DbQueryRunner
+static partial class DbQueryRunner
{
///
/// Makes the exception thrown when a default (unbound) value is used.
diff --git a/Source/Core/ExpressiveCommandBase.Capture.cs b/Source/Core/ExpressiveCommandBase.Capture.cs
index 4d9fb0f7..5dae398c 100644
--- a/Source/Core/ExpressiveCommandBase.Capture.cs
+++ b/Source/Core/ExpressiveCommandBase.Capture.cs
@@ -1,4 +1,5 @@
using System.Diagnostics;
+using System.Globalization;
namespace Open.Database.Extensions;
@@ -79,42 +80,28 @@ public abstract partial class ExpressiveCommandBase<
///
/// Reads the command's output parameters into a
- /// when the next terminal runs it.
+ /// when the next terminal runs it: a model by its members, or one value by
+ /// the name of the variable.
///
///
///
- public TThis CaptureOutput(out DbCapture output)
- {
- CaptureSource source = Captures.Model();
- Attach(source);
- output = new(source);
- return (TThis)this;
- }
-
- ///
- /// Reads one output parameter, converted to ,
- /// when the next terminal runs the command.
- ///
- ///
- ///
///
- public TThis CaptureOutput(string name, out DbCapture value)
+ public TThis CaptureOutput(
+ out DbCapture output,
+ [CallerArgumentExpression(nameof(output))] string? name = null)
{
- CaptureSource source = Captures.Named(name);
+ CaptureSource source = Captures.Output(name);
Attach(source);
- value = new(source);
+ output = new(source);
return (TThis)this;
}
///
/// Reads one output parameter of the given precision
- /// and scale, converted to , when the next
- /// terminal runs the command.
+ /// and scale when the next terminal runs the command.
///
///
@@ -122,16 +109,13 @@ public TThis CaptureOutput(string name, out DbCapture value)
/// path="docs/members[@name='out-name-param']/*" />
///
- public TThis CaptureOutput(
- string name,
+ public TThis CaptureOutput(
+ out DbCapture value,
byte precision,
byte scale,
- out DbCapture value)
+ [CallerArgumentExpression(nameof(value))] string? name = null)
{
- CaptureSource source = Captures.Shaped(
- name,
- precision,
- scale);
+ CaptureSource source = Captures.Shaped(name, precision, scale);
Attach(source);
value = new(source);
return (TThis)this;
@@ -148,15 +132,12 @@ public TThis CaptureOutput(
///
public TThis CaptureOutputDecimal(
- string name,
+ out DbCapture value,
byte precision,
byte scale,
- out DbCapture value)
+ [CallerArgumentExpression(nameof(value))] string? name = null)
{
- CaptureSource source = Captures.Decimal(
- name,
- precision,
- scale);
+ CaptureSource source = Captures.Decimal(name, precision, scale);
Attach(source);
value = new(source);
return (TThis)this;
@@ -334,14 +315,22 @@ static async ValueTask InvokeAsync(
/// Refuses ExecuteOutputAsync on a command that carries a capture:
/// two readers of one parameter set.
///
- /// The ExecuteOutputAsync form, for the
- /// message.
+ /// The ExecuteOutputAsync form, for the
+ /// message, with {0} where the model goes.
+ /// The model's type name, or the parameter's name in
+ /// the named form.
/// The command carries a
/// capture; the capture is completed with the same exception.
- void RefuseBesideCaptures(string call)
+ // The text is formatted only on the refusal: a call without a capture
+ // allocates nothing here.
+ void RefuseBesideCaptures(string callFormat, string model)
{
if (_captures is { } captures)
{
+ string call = string.Format(
+ CultureInfo.InvariantCulture,
+ callFormat,
+ model);
throw captures.Refuse(
new InvalidOperationException(
CaptureMessages.OutputBeside(captures, call)));
diff --git a/Source/Core/ExpressiveCommandBase.Output.cs b/Source/Core/ExpressiveCommandBase.Output.cs
index 32e1a7fd..0374d07f 100644
--- a/Source/Core/ExpressiveCommandBase.Output.cs
+++ b/Source/Core/ExpressiveCommandBase.Output.cs
@@ -70,7 +70,7 @@ public ValueTask ExecuteOutputAsync(
OutputLayout layout = OutputLayout.Get();
if (layout.HasReturnValue) ThrowUnlessProcedure(layout);
- RefuseBesideCaptures($"ExecuteOutputAsync<{layout.Model}>()");
+ RefuseBesideCaptures("ExecuteOutputAsync<{0}>()", layout.Model);
// Thrown synchronously, not through the returned task.
CancellationToken.ThrowIfCancellationRequested();
@@ -281,7 +281,7 @@ ValueTask RunNamedAsync(OutputLayout layout, CancellationToken cancellatio
{
// Before the cancel: a capture on the command is completed by the
// refusal.
- RefuseBesideCaptures($"ExecuteOutputAsync(\"{layout.Model}\")");
+ RefuseBesideCaptures("ExecuteOutputAsync(\"{0}\")", layout.Model);
// Thrown synchronously, not through the returned task.
CancellationToken.ThrowIfCancellationRequested();
@@ -364,289 +364,48 @@ void ThrowUnlessProcedure(OutputLayout layout)
+ "Set CommandType.StoredProcedure to call a procedure, or read an output parameter (declared @name OUTPUT in the text) into a member of another name.");
}
- ///
- /// Names the command for the messages: a procedure's name, or the command text.
- ///
- /// The name.
- string Where()
- => Type == CommandType.StoredProcedure
- ? Command
- : "the command text";
-
+ // The matching and the adding of the output parameters are one path for
+ // commands and for the calls of definitions: OutputBinding.
///
/// Resolves the parameter each output member stands for, while the call is built.
///
- ///
- /// It runs inside the build step, so a failure here forgets a procedure's kept names as any failure to build does.
- /// An output member merges with an input of the same name (see ); only two outputs can collide.
- ///
/// The call's output parameters.
/// The names of the procedure or of the text's markers, or when they are not known.
- ///
- /// A member matches no parameter, two match one, or a declared parameter matches a ReturnValue member.
- ///
void ResolveOutputs(OutputRun run, NameSet? names)
- {
- OutputLayout layout = run.Layout;
-
- // A text that is not interned has no remembered set: its markers are read for this call.
- NameSet? real = names ?? (Type == CommandType.Text ? new NameSet(SqlTextParameters.Parse(Command)) : null);
- bool known = real is { Names.Length: > 0 };
- string where = Where();
- run.Where = where;
-
- var resolved = new string?[layout.Members.Length];
- for (int i = 0; i < resolved.Length; i++)
- {
- OutputMember member = layout.Members[i];
- if (member.IsReturnValue)
- {
- // Only a stored procedure gets here (checked at the call): no declared parameter may also answer to the name.
- // CaptureReturn asks for the return code itself, not by a
- // member's name, so nothing can be mistaken for it.
- if (!member.Named
- && known
- && real!.Match(
- OutputLayout.ReturnValue,
- Command,
- member.Display) is { } declared)
- {
- throw new InvalidOperationException(
- $"{member.Display} reads the return code, but {where} also declares the parameter '{declared}', which the name {OutputLayout.ReturnValue} matches, so it is unclear which one to read. "
- + $"To read that parameter, give the member [Column(\"{declared}\")]; to read the return code, rename the procedure's parameter.");
- }
-
- continue;
- }
-
- if (!known)
- {
- resolved[i] = member.Name;
- continue;
- }
-
- resolved[i] = (member.Exact
- ? real!.Find(member.Name)?.Real
- : member.Named
- ? real!.MatchName(
- member.Name,
- Command,
- member.Display,
- "Pass the exact parameter name, naming one of those two.")
- : real!.Match(member.Name, Command, member.Display))
- ?? throw NoOutputMatch(member, real.Names, where);
- }
-
- // Two members that resolve to one parameter would read the same value under two meanings.
- for (int i = 0; i < resolved.Length; i++)
- {
- if (resolved[i] is not { } first) continue;
- for (int j = i + 1; j < resolved.Length; j++)
- {
- if (resolved[j] is not { } second || !DbQueryBinding.SameName(first, second)) continue;
-
- throw new InvalidOperationException(
- $"{layout.Members[i].Display} and {layout.Members[j].Display} both resolve to the output parameter '{first}' of {where}, so one value would be read under two meanings. "
- + (layout.Members[i].Named || layout.Members[j].Named
- ? "Name one of them exactly as the parameter is declared (a name that matches exactly wins over one that matches only ignoring case or underscores), or drop one."
- : "Name each member's parameter with [Column(\"name\")], or remove one of them."));
- }
- }
-
- // Only a procedure's own set has metadata, and only once it was read.
- if (names is { Home: not null })
- {
- CheckMetadata(layout, resolved, names, where);
- }
-
- run.Names = resolved;
- }
-
- ///
- /// Checks the output members against what the database says about the parameters they resolved to, when it said.
- ///
- ///
- /// Only the exact mode IN counts; a mode that is anything else, or missing, does not (the metadata has no third state, because "not known" and "not mode IN" never differ in what the call does). A scale is compared only when it is known.
- ///
- /// The call's members.
- /// The parameter each member resolved to; for the return code.
- /// The procedure's set.
- /// The procedure, for the messages.
- ///
- /// A member reads a parameter whose mode is IN, or declares a scale lower than the procedure's.
- ///
- static void CheckMetadata(
- OutputLayout layout, string?[] resolved,
- NameSet names, string where)
- {
- if (names.Metadata is not { IsKnown: true } metadata) return;
-
- for (int i = 0; i < resolved.Length; i++)
- {
- OutputMember member = layout.Members[i];
- if (member.IsReturnValue
- || resolved[i] is not { } name
- || names.Find(name) is not { } entry)
- {
- continue;
- }
-
- if (metadata.IsModeIn(entry.Index))
- {
- throw new InvalidOperationException(
- $"{member.Display} reads '{entry.Real}' of {where} as an "
- + "output parameter, but the database reports that "
- + "parameter as an input parameter (mode IN), so the "
- + "call would be refused. Declare the parameter OUTPUT in the "
- + "procedure, or remove the member. If the procedure was "
- + "changed since it was first called, call again.");
- }
+ => OutputBinding.Resolve(run, names, Type, Command);
- int declared = metadata.Scale(entry.Index);
- if (member.Wire is { Type: DbType.Decimal, HasPrecision: true } wire
- && declared > wire.Scale)
- {
- string fix = member.Named
- ? $"Pass a scale of {declared} or more"
- : "Declare the member as [Column(TypeName = "
- + $"\"decimal({wire.Precision},{declared})\")] or higher";
-
- throw new InvalidOperationException(
- $"{member.Display} has the scale {wire.Scale}, but "
- + $"'{entry.Real}' of {where} has the scale {declared}, "
- + "so the value would be rounded to "
- + $"{wire.Scale} decimal places. {fix}, or declare the "
- + $"parameter in the procedure with the scale {wire.Scale}. "
- + "If the procedure was changed since it was first "
- + "called, call again.");
- }
- }
- }
-
- static InvalidOperationException NoOutputMatch(
- OutputMember member,
- ImmutableArray real,
- string where)
- {
- string declared = string.Join(", ", real);
- if (member.Named)
- {
- // A decimal reaches here through the form that takes a precision and scale; any other type through the plain named form.
- bool capture = member.Form == OutputForm.Capture;
- string call = member.Wire!.Type == DbType.Decimal
- ? capture
- ? "Pass one of those names to CaptureOutput(name, "
- + "precision, scale, out …) or CaptureOutputDecimal(name, "
- + "precision, scale, out …)"
- : "Pass one of those names to "
- + "ExecuteOutputAsync(name, precision, scale) "
- + "or ExecuteOutputDecimalAsync(name, precision, scale)"
- : capture
- ? "Pass one of those names to CaptureOutput(name, out …)"
- : "Pass one of those names to ExecuteOutputAsync(name)";
-
- return new(
- $"{member.Display} is not a parameter of {where}, which declares: {declared}. "
- + call + ", or add the parameter to the procedure (or its @name marker to the text).");
- }
-
- if (member.Exact)
- {
- return new(
- $"{member.Display} names its parameter '{member.Name}' with [Column], but {where} declares no parameter of that name (it declares: {declared}). "
- + "Change the [Column] name to one it declares, or add the parameter.");
- }
-
- return new(
- $"{member.Display} has no matching parameter on {where} (tried {string.Join(", ", ParameterNames.Candidates(member.Name))}; it declares: {declared}). "
- + $"Add a parameter named {member.Name} to {where}, or name the member's parameter with [Column(\"name\")].");
- }
-
- // The provider's parameters are already on the command. An output member whose parameter was given a value turns that
- // parameter into InputOutput (keeping a type the caller gave), so one name never yields two parameters.
///
/// Adds the call's output parameters to the command, or turns the matching input into one.
///
/// The command, with the provider's parameters.
/// The call's output parameters, resolved.
- /// The provider did not add a parameter that was sent.
void AddOutputs(TCommand command, OutputRun run)
- {
- Debug.Assert(run.Names is not null, "The build step resolves the names first.");
- OutputLayout layout = run.Layout;
- List? send = ActiveSendList;
- var parameters = new IDbDataParameter?[layout.Members.Length];
- bool[] pure = new bool[parameters.Length];
- for (int i = 0; i < parameters.Length; i++)
- {
- OutputMember member = layout.Members[i];
- if (member.IsReturnValue)
- {
- parameters[i] = command.AddReturnParameter();
- pure[i] = true;
- continue;
- }
-
- string name = run.Names![i]!;
- OutputWire wire = member.Wire!;
- if (Sent(send, name) is { } input)
- {
- IDbDataParameter parameter = Find(command, input.Name)
- ?? throw new InvalidOperationException(
- $"{member.Display} reads back the parameter '{input.Name}', which was given a value, but the command's provider did not add it to the command under that name, so there is nothing to read. "
- + "Give the value under the name the provider keeps (AddParam(\"name\", value)), or do not give it a value so it is sent as an output only.");
- parameter.Direction = ParameterDirection.InputOutput;
- if (!input.Type.HasValue) parameter.DbType = wire.Type;
- wire.Apply(parameter);
- parameters[i] = parameter;
- continue;
- }
-
- IDbDataParameter output = command.CreateParameter();
- output.ParameterName = name;
- output.Direction = ParameterDirection.Output;
- output.DbType = wire.Type;
- wire.Apply(output);
- command.Parameters.Add(output);
- parameters[i] = output;
- pure[i] = true;
- }
-
- run.Parameters = parameters;
- run.Pure = pure;
- }
+ => OutputBinding.Add(command, run, new SentInputs(ActiveSendList));
///
- /// Finds what is sent under a name, compared without the @ and ignoring case.
+ /// Finds an input among the values the command sends.
///
/// What the call sends, or .
- /// The name.
- /// The parameter sent under it, or .
- static Param? Sent(List? send, string name)
+ readonly struct SentInputs(List? send) : IInputLookup
{
- if (send is null) return null;
-
- foreach (Param p in send)
+ ///
+ public bool TryFind(string name, out string inputName, out bool typed)
{
- if (DbQueryBinding.SameName(p.Name, name)) return p;
- }
+ if (send is not null)
+ {
+ foreach (Param p in send)
+ {
+ if (!DbQueryBinding.SameName(p.Name, name)) continue;
- return null;
- }
+ inputName = p.Name;
+ typed = p.Type.HasValue;
+ return true;
+ }
+ }
- ///
- /// Finds the provider's parameter of a name, compared without the @ and ignoring case.
- ///
- /// The command.
- /// The name it was sent under.
- /// The parameter, or .
- static IDbDataParameter? Find(TCommand command, string name)
- {
- foreach (object? p in command.Parameters)
- {
- if (p is IDbDataParameter parameter && DbQueryBinding.SameName(parameter.ParameterName, name)) return parameter;
+ inputName = name;
+ typed = false;
+ return false;
}
-
- return null;
}
}
diff --git a/Source/Core/MappedQuery.Capture.cs b/Source/Core/MappedQuery.Capture.cs
index b4fd321c..f7be7da2 100644
--- a/Source/Core/MappedQuery.Capture.cs
+++ b/Source/Core/MappedQuery.Capture.cs
@@ -1,10 +1,12 @@
namespace Open.Database.Extensions;
-// The captures of a mapped query (see Capture.cs). A query holds its own
-// captures in MappedQueryCore, appended to its command's; a query without its
-// own runs on its command, which fills the command's. Every builder carries
-// them, and they are part of the equality by reference. The async run hands
-// them to the command (ICaptureRunner); a synchronous run refuses them.
+// The captures of a mapped query (see Capture.cs). A query keeps only its own
+// captures in MappedQueryCore; a run combines them with the command's current
+// ones, the command's first. A query without its own runs on its command,
+// which fills the command's; a query from a definition has no command and
+// fills only its own. Every builder carries them, and they are part of the
+// equality by reference. The async run hands them to the command
+// (ICaptureRunner); a synchronous run refuses them.
readonly partial struct MappedQueryCore
{
///
@@ -35,6 +37,10 @@ readonly partial struct MappedQueryCore
public CaptureRun? CapturedRun
=> _captures as CaptureRun;
+ // A query from a definition has no command, so no token of its own.
+ CancellationToken CommandToken
+ => _call.IsBound ? default : _command!.CancellationToken;
+
///
/// Returns the query with one more capture.
///
@@ -54,8 +60,15 @@ public MappedQueryCore WithCapture(ICaptureSource source)
EnsureCommand();
if (_call.IsBound)
{
- throw new NotSupportedException(
- CaptureMessages.NotFromDefinition(source));
+ // A definition's kind is immutable, so the return code is checked
+ // here; a command's type can change, so its check is at the run.
+ // A query from a definition has no command: its captures are its
+ // own, with nothing to combine and no reader to refuse.
+ return new(
+ null, _call, _source,
+ _skip, _take, Options, Config,
+ CaptureSet.WithOnDefinition(
+ _captures as CaptureSet, source, _call.Definition.Kind));
}
if (_command is not ICaptureRunner runner)
{
@@ -111,7 +124,7 @@ CaptureRun StreamRun(
CancellationToken cancellationToken)
{
var run = new CaptureRun(captures);
- run.Owners(cancellationToken, default, _command!.CancellationToken);
+ run.Owners(cancellationToken, default, CommandToken);
return run;
}
@@ -127,7 +140,7 @@ PooledBuffer CapturedBuffer(
CancellationToken cancellationToken)
{
CaptureRun run = captures.Claim(cancellationToken);
- run.Owners(cancellationToken, default, _command!.CancellationToken);
+ run.Owners(cancellationToken, default, CommandToken);
try
{
return new(WithRun(run), Config, cancellationToken);
@@ -146,44 +159,28 @@ public readonly partial record struct MappedQuery
{
///
/// Reads the command's output parameters into a
- /// when the query's terminal runs.
+ /// when the query's terminal runs: a model by its members, or one value by
+ /// the name of the variable.
///
///
///
- public MappedQuery CaptureOutput(out DbCapture output)
- {
- CaptureSource source = Captures.Model();
- MappedQuery captured = new(_core.WithCapture(source));
- output = new(source);
- return captured;
- }
-
- ///
- /// Reads one output parameter, converted to ,
- /// when the query's terminal runs.
- ///
- ///
- ///
///
- public MappedQuery CaptureOutput(
- string name,
- out DbCapture value)
+ public MappedQuery CaptureOutput(
+ out DbCapture output,
+ [CallerArgumentExpression(nameof(output))] string? name = null)
{
- CaptureSource source = Captures.Named(name);
+ CaptureSource source = Captures.Output(name);
MappedQuery captured = new(_core.WithCapture(source));
- value = new(source);
+ output = new(source);
return captured;
}
///
/// Reads one output parameter of the given precision
- /// and scale, converted to , when the query's
- /// terminal runs.
+ /// and scale when the query's terminal runs.
///
///
@@ -191,16 +188,13 @@ public MappedQuery CaptureOutput(
/// path="docs/members[@name='out-name-param']/*" />
///
- public MappedQuery CaptureOutput(
- string name,
+ public MappedQuery CaptureOutput(
+ out DbCapture value,
byte precision,
byte scale,
- out DbCapture value)
+ [CallerArgumentExpression(nameof(value))] string? name = null)
{
- CaptureSource source = Captures.Shaped(
- name,
- precision,
- scale);
+ CaptureSource source = Captures.Shaped(name, precision, scale);
MappedQuery captured = new(_core.WithCapture(source));
value = new(source);
return captured;
@@ -217,15 +211,12 @@ public MappedQuery CaptureOutput(
///
public MappedQuery CaptureOutputDecimal(
- string name,
+ out DbCapture value,
byte precision,
byte scale,
- out DbCapture value)
+ [CallerArgumentExpression(nameof(value))] string? name = null)
{
- CaptureSource source = Captures.Decimal(
- name,
- precision,
- scale);
+ CaptureSource source = Captures.Decimal(name, precision, scale);
MappedQuery captured = new(_core.WithCapture(source));
value = new(source);
return captured;
@@ -252,57 +243,40 @@ public MappedQuery CaptureReturn(
public readonly partial record struct MappedQueryWithSkip
{
///
+ /// cref="MappedQuery{T}.CaptureOutput{TOut}(out DbCapture{TOut}, string)"/>
public MappedQueryWithSkip CaptureOutput(
- out DbCapture output)
+ out DbCapture output,
+ [CallerArgumentExpression(nameof(output))] string? name = null)
{
- CaptureSource source = Captures.Model();
+ CaptureSource source = Captures.Output(name);
MappedQueryWithSkip captured = new(_core.WithCapture(source));
output = new(source);
return captured;
}
///
- public MappedQueryWithSkip CaptureOutput(
- string name,
- out DbCapture value)
- {
- CaptureSource source = Captures.Named(name);
- MappedQueryWithSkip captured = new(_core.WithCapture(source));
- value = new(source);
- return captured;
- }
-
- ///
- public MappedQueryWithSkip CaptureOutput(
- string name,
+ /// cref="MappedQuery{T}.CaptureOutput(out DbCapture{decimal}, byte, byte, string)"/>
+ public MappedQueryWithSkip CaptureOutput(
+ out DbCapture value,
byte precision,
byte scale,
- out DbCapture value)
+ [CallerArgumentExpression(nameof(value))] string? name = null)
{
- CaptureSource source = Captures.Shaped(
- name,
- precision,
- scale);
+ CaptureSource source = Captures.Shaped(name, precision, scale);
MappedQueryWithSkip captured = new(_core.WithCapture(source));
value = new(source);
return captured;
}
///
+ /// cref="MappedQuery{T}.CaptureOutputDecimal(out DbCapture{decimal?}, byte, byte, string)"/>
public MappedQueryWithSkip CaptureOutputDecimal(
- string name,
+ out DbCapture value,
byte precision,
byte scale,
- out DbCapture value)
+ [CallerArgumentExpression(nameof(value))] string? name = null)
{
- CaptureSource source = Captures.Decimal(
- name,
- precision,
- scale);
+ CaptureSource source = Captures.Decimal(name, precision, scale);
MappedQueryWithSkip captured = new(_core.WithCapture(source));
value = new(source);
return captured;
@@ -323,57 +297,40 @@ public MappedQueryWithSkip CaptureReturn(
public readonly partial record struct MappedQueryWithTake
{
///
+ /// cref="MappedQuery{T}.CaptureOutput{TOut}(out DbCapture{TOut}, string)"/>
public MappedQueryWithTake CaptureOutput(
- out DbCapture output)
+ out DbCapture output,
+ [CallerArgumentExpression(nameof(output))] string? name = null)
{
- CaptureSource source = Captures.Model();
+ CaptureSource source = Captures.Output(name);
MappedQueryWithTake captured = new(_core.WithCapture(source));
output = new(source);
return captured;
}
///
- public MappedQueryWithTake CaptureOutput(
- string name,
- out DbCapture value)
- {
- CaptureSource source = Captures.Named(name);
- MappedQueryWithTake