diff --git a/Source/Core/Capture.cs b/Source/Core/Capture.cs
index 98e8d8fe..17c77705 100644
--- a/Source/Core/Capture.cs
+++ b/Source/Core/Capture.cs
@@ -408,24 +408,14 @@ sealed class CaptureSet : CaptureHolder
/// The new capture.
/// when it is attached on a
/// mapped query.
- /// Whether the command is a stored
- /// procedure.
/// The new set.
- /// The capture reads the return
- /// code of a command that is not a stored procedure, or reads what another
- /// capture reads.
+ /// The capture reads what
+ /// another capture reads.
public static CaptureSet With(
CaptureSet? set,
ICaptureSource source,
- bool onQuery,
- bool isProcedure)
+ bool onQuery)
{
- if (source.ReadsReturn && !isProcedure)
- {
- throw new InvalidOperationException(
- CaptureMessages.NotProcedure(source));
- }
-
if (set is null) return new([source], onQuery);
string noun = onQuery ? "query" : "command";
@@ -435,9 +425,67 @@ public static CaptureSet With(
return new([.. set.Sources, source], onQuery || set.OnQuery);
}
+ ///
+ /// 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.
+ ///
+ /// The command's captures.
+ /// The query's own captures.
+ /// A set of the command's sources, then the query's own.
+ /// A capture of the command
+ /// and one of the query read the same output or the return code: the
+ /// command got its capture after the query was made.
+ public static CaptureSet Combine(CaptureSet command, CaptureSet own)
+ {
+ foreach (ICaptureSource first in command.Sources)
+ {
+ foreach (ICaptureSource second in own.Sources)
+ ThrowIfSameOwner(first, second, "query");
+ }
+
+ return new([.. command.Sources, .. own.Sources], onQuery: true);
+ }
+
+ ///
+ /// The last set made by , with the command's set
+ /// it was made for.
+ ///
+ sealed class Combination(CaptureSet command, CaptureSet result)
+ {
+ public readonly CaptureSet Command = command;
+
+ public readonly CaptureSet Result = result;
+ }
+
+ Combination? _combined;
+
+ ///
+ /// Gets what a run fills: the command's captures as they are now,
+ /// combined with these (see ).
+ ///
+ ///
+ /// The last answer is kept for the command's set it was made for, so the
+ /// calls of one run (a stream and its reader, say) get the same set.
+ ///
+ /// The command's captures now.
+ /// The set the run claims.
+ /// See
+ /// .
+ public CaptureSet CombinedWith(CaptureSet command)
+ {
+ Combination? last = Volatile.Read(ref _combined);
+ if (last is not null && ReferenceEquals(last.Command, command))
+ return last.Result;
+
+ // Two threads may both combine: the sets are the same.
+ var made = new Combination(command, Combine(command, this));
+ Volatile.Write(ref _combined, made);
+ return made.Result;
+ }
+
// One owner per output and per return code: a model reads every output, so
// it shares them with no other capture.
- static void ThrowIfSameOwner(
+ public static void ThrowIfSameOwner(
ICaptureSource first,
ICaptureSource second,
string noun)
@@ -983,4 +1031,18 @@ public static string NotFromCommand(ICaptureSource source, Type reader)
+ $"this query reads from {reader.Name}, which cannot. "
+ "Build it from an expressive command, "
+ "or read the outputs with ExecuteOutputAsync.";
+
+ public static string ReplacedReader(string display, Type command)
+ => $"{display} reads through the library's reader, "
+ + $"which {command.Name} replaces by re-implementing IExecuteReader, "
+ + "so the outputs would never be read. "
+ + "Capture on a command that does not re-implement IExecuteReader, "
+ + "or read the outputs with ExecuteOutputAsync.";
+
+ public static string ReplacementUnknown(Type command, string reason)
+ => $"Could not tell whether {command.Name} re-implements "
+ + $"IExecuteReader, which a capture needs to know ({reason}). "
+ + "Read the outputs with ExecuteOutputAsync, "
+ + "or capture on a command type that can be examined "
+ + "(reflection on its interfaces must be allowed).";
}
diff --git a/Source/Core/ExpressiveCommand.cs b/Source/Core/ExpressiveCommand.cs
index b898fb01..88034c81 100644
--- a/Source/Core/ExpressiveCommand.cs
+++ b/Source/Core/ExpressiveCommand.cs
@@ -135,4 +135,11 @@ protected override void AddParams(IDbCommand command)
else if (p.NullDbType is { } nullType) np.DbType = nullType; // a NULL carries no type, so give it the argument's
}
}
+
+ ///
+ /// Gets whether this is exactly , which a capture
+ /// needs no lookup for.
+ ///
+ internal override bool IsLibraryCommand
+ => GetType() == typeof(ExpressiveCommand);
}
diff --git a/Source/Core/ExpressiveCommandBase.Capture.cs b/Source/Core/ExpressiveCommandBase.Capture.cs
index 76ddd539..4d9fb0f7 100644
--- a/Source/Core/ExpressiveCommandBase.Capture.cs
+++ b/Source/Core/ExpressiveCommandBase.Capture.cs
@@ -17,9 +17,12 @@ interface ICaptureRunner
/// .
CaptureSet? Captures { get; }
- /// Gets whether the command is a stored procedure, which has a
- /// return code.
- bool IsProcedure { get; }
+ /// Gets whether the command's type re-implements
+ /// , which a capture cannot read
+ /// through.
+ /// The type could not be
+ /// examined.
+ bool ReplacesReader { get; }
/// Executes a reader on the command, filling the given
/// captures.
@@ -97,6 +100,8 @@ public TThis CaptureOutput(out DbCapture output)
///
///
+ ///
public TThis CaptureOutput(string name, out DbCapture value)
{
@@ -114,6 +119,8 @@ public TThis CaptureOutput(string name, out DbCapture value)
///
///
+ ///
public TThis CaptureOutput(
string name,
@@ -137,6 +144,8 @@ public TThis CaptureOutput(
///
///
+ ///
public TThis CaptureOutputDecimal(
string name,
@@ -173,14 +182,24 @@ void Attach(ICaptureSource source)
=> _captures = CaptureSet.With(
_captures,
source,
- onQuery: false,
- Type == CommandType.StoredProcedure);
+ onQuery: false);
CaptureSet? ICaptureRunner.Captures
=> _captures;
- bool ICaptureRunner.IsProcedure
- => Type == CommandType.StoredProcedure;
+ ///
+ /// Gets whether this is exactly one of the library's own command types,
+ /// which never re-implement the reader, so a capture needs no lookup.
+ ///
+ ///
+ /// Overridden by each concrete library command as an exact type test
+ /// (those types are not sealed, and a subclass is looked up).
+ ///
+ internal virtual bool IsLibraryCommand
+ => false;
+
+ bool ICaptureRunner.ReplacesReader
+ => !IsLibraryCommand && ReaderReplacement.Of(GetType());
ValueTask ICaptureRunner.ExecuteReaderAsync(
CaptureHolder captures,
@@ -234,8 +253,8 @@ async ValueTask ExecuteCapturedAsync(
"ExecuteOutputAsync refuses a command that carries a capture "
+ "at its call.");
- // The kind was checked at the capture call; the command's type can
- // change after it.
+ // Checked here, not at the capture call: the command's type can be
+ // set after a capture is added.
if (run.Set.ReadsReturn && Type != CommandType.StoredProcedure)
{
throw run.Set.NotProcedure();
diff --git a/Source/Core/ExpressiveCommandBase.Output.cs b/Source/Core/ExpressiveCommandBase.Output.cs
index fa7b5fae..8ec985a3 100644
--- a/Source/Core/ExpressiveCommandBase.Output.cs
+++ b/Source/Core/ExpressiveCommandBase.Output.cs
@@ -95,7 +95,7 @@ static async (cmd, _, run) =>
/// and reads one output parameter, converted to .
///
///
- ///
+ ///
///
///
///
@@ -220,7 +220,7 @@ static async ValueTask NotNullAsync(string name, ValueTask va
///
///
///
- ///
+ ///
///
///
///
@@ -411,7 +411,15 @@ void ResolveOutputs(OutputRun run, NameSet? names)
continue;
}
- resolved[i] = (member.Exact ? real!.Find(member.Name)?.Real : real!.Match(member.Name, Command, member.Display))
+ 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);
}
@@ -425,7 +433,9 @@ void ResolveOutputs(OutputRun run, NameSet? names)
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. "
- + "Name each member's parameter with [Column(\"name\")], or remove one of them.");
+ + (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."));
}
}
diff --git a/Source/Core/ExpressiveCommandBase.cs b/Source/Core/ExpressiveCommandBase.cs
index f8386fa0..5009f7c3 100644
--- a/Source/Core/ExpressiveCommandBase.cs
+++ b/Source/Core/ExpressiveCommandBase.cs
@@ -396,6 +396,10 @@ protected TThis AddParam(Param param)
/// A you pass always wins.
/// The overloads have no type to use:
/// pass a database type.
+ /// A passed as the value, as in
+ /// AddParam("@id", DbType.Int32) on a command whose database type
+ /// is not (the SQL Server commands), is a value, and
+ /// is sent as one: pass the database type as the third argument.
///
/// is .
/// is empty or white space.
@@ -1947,6 +1951,13 @@ ValueTask IExecuteReader.ExecuteReaderAsync(Func
/// .
///
///
+ ///
+ /// At the call, before anything runs and not in the returned task:
+ /// is a model, which cannot hold the return code.
+ /// Use int (or int?, long, an enum), or read it with
+ /// a ReturnValue member of an output model
+ /// (ExecuteOutputAsync<TOut>()).
+ ///
///
public ValueTask ExecuteReturnAsync(
CancellationToken cancellationToken = default)
diff --git a/Source/Core/ExpressiveDbCommand.cs b/Source/Core/ExpressiveDbCommand.cs
index f216c92d..07ff69c9 100644
--- a/Source/Core/ExpressiveDbCommand.cs
+++ b/Source/Core/ExpressiveDbCommand.cs
@@ -148,4 +148,11 @@ protected override void AddParams(DbCommand command)
else if (p.NullDbType is { } nullType) np.DbType = nullType; // a NULL carries no type, so give it the argument's
}
}
+
+ ///
+ /// Gets whether this is exactly , which a capture
+ /// needs no lookup for.
+ ///
+ internal override bool IsLibraryCommand
+ => GetType() == typeof(ExpressiveDbCommand);
}
diff --git a/Source/Core/MappedQuery.Capture.cs b/Source/Core/MappedQuery.Capture.cs
index 19c3c7b0..b4fd321c 100644
--- a/Source/Core/MappedQuery.Capture.cs
+++ b/Source/Core/MappedQuery.Capture.cs
@@ -16,7 +16,18 @@ readonly partial struct MappedQueryCore
// CancelOnEarlyStop(). Without a capture it costs a type check of the
// command and a field read.
CaptureHolder? Captured()
- => _captures ?? (_command as ICaptureRunner)?.Captures;
+ {
+ if (_captures is not CaptureSet own)
+ {
+ return _captures ?? (_command as ICaptureRunner)?.Captures;
+ }
+
+ // The command's captures as they are now, then the query's own: a
+ // capture added to the command after the query was made is filled too.
+ return _command is ICaptureRunner { Captures: { } command }
+ ? own.CombinedWith(command)
+ : own;
+ }
///
/// Gets the run a stream or a buffer claimed, or .
@@ -29,11 +40,15 @@ public CaptureRun? CapturedRun
///
/// The capture, its arguments checked.
/// A copy of the query that carries the capture.
- /// A default value, a capture
- /// of the return code of a command that is not a stored procedure, or a
+ /// A default value, or a
/// capture that reads what another one reads.
+ /// The command's type could not
+ /// be examined for a re-implemented reader (see
+ /// ).
/// The query does not read from an
- /// expressive command.
+ /// expressive command, or the command's type re-implements
+ /// , which a capture cannot read
+ /// through.
public MappedQueryCore WithCapture(ICaptureSource source)
{
EnsureCommand();
@@ -47,12 +62,27 @@ public MappedQueryCore WithCapture(ICaptureSource source)
throw new NotSupportedException(
CaptureMessages.NotFromCommand(source, _command!.GetType()));
}
+ if (runner.ReplacesReader)
+ {
+ throw new NotSupportedException(
+ CaptureMessages.ReplacedReader(
+ source.Display,
+ _command!.GetType()));
+ }
+
+ // The query keeps only its own. A run takes the command's captures as
+ // they are then, first, so the query and the command share the first
+ // capture and one run claims them. A conflict with what the command
+ // has now is refused here, without storing it.
+ if (runner.Captures is { } current)
+ {
+ foreach (ICaptureSource other in current.Sources)
+ CaptureSet.ThrowIfSameOwner(other, source, "query");
+ }
- // Appended to the command's, so the query and the command share the
- // first capture, and one run claims them.
CaptureSet captures = CaptureSet.With(
- _captures as CaptureSet ?? runner.Captures,
- source, onQuery: true, runner.IsProcedure);
+ _captures as CaptureSet,
+ source, onQuery: true);
return new(
_command, _call, _source,
_skip, _take, Options, Config, captures);
@@ -137,6 +167,8 @@ public MappedQuery CaptureOutput(out DbCapture output)
///
///
+ ///
public MappedQuery CaptureOutput(
string name,
@@ -156,6 +188,8 @@ public MappedQuery CaptureOutput(
///
///
+ ///
public MappedQuery CaptureOutput(
string name,
@@ -179,6 +213,8 @@ public MappedQuery CaptureOutput(
///
///
+ ///
public MappedQuery CaptureOutputDecimal(
string name,
diff --git a/Source/Core/MappedQuery.cs b/Source/Core/MappedQuery.cs
index 05865a93..67c034cc 100644
--- a/Source/Core/MappedQuery.cs
+++ b/Source/Core/MappedQuery.cs
@@ -495,15 +495,56 @@ TResult ExecuteReader(TState state, FuncRuns the asynchronous reader function on the call, held as it is, or on the command.
// With captures (the query's or its command's), the command's own reader
// path fills them (only a command can be given them: see WithCapture).
- // It is taken even when a subclass re-implements IExecuteReader, so the
- // claim and the completion never depend on that override.
+ // A command that re-implements IExecuteReader is refused here, when a
+ // mapped query over it runs with captures: a capture made on the command,
+ // not the query, is not checked at a capture call, and the command's own
+ // terminals do not use the re-implemented reader. Its own reader would
+ // skip the output parameters. The refusal is the task's exception, and
+ // completes every capture.
ValueTask ExecuteReaderAsync(TState state, Func> transform, CommandBehavior behavior, CancellationToken token)
- => Captured() is { } captures
- ? ((ICaptureRunner)_command!).ExecuteReaderAsync(
- captures, state, transform, behavior, token)
- : _call.IsBound
+ {
+ if (Captured() is not { } captures)
+ {
+ return _call.IsBound
? _call.RunAsync(state, transform, behavior, token)
: Command.ExecuteReaderAsync(state, transform, behavior, token);
+ }
+
+ var runner = (ICaptureRunner)_command!;
+ Exception? refusal = ReaderRefusal(runner, captures, token);
+ return refusal is null
+ ? runner.ExecuteReaderAsync(
+ captures, state, transform, behavior, token)
+ : new ValueTask(Task.FromException(refusal));
+ }
+
+ // The exception that refuses a captured run on a command that replaces its
+ // reader, or null. A type that cannot be examined is refused too.
+ Exception? ReaderRefusal(
+ ICaptureRunner runner,
+ CaptureHolder captures,
+ CancellationToken token)
+ {
+ Exception refusal;
+ try
+ {
+ if (!runner.ReplacesReader)
+ {
+ return null;
+ }
+
+ refusal = new InvalidOperationException(
+ CaptureMessages.ReplacedReader(
+ captures.Set.Displays,
+ _command!.GetType()));
+ }
+ catch (InvalidOperationException ex)
+ {
+ refusal = ex;
+ }
+
+ return captures.Refuse(refusal, token);
+ }
///
/// Runs an execution that opted in with CancelOnEarlyStop().
diff --git a/Source/Core/NameSet.cs b/Source/Core/NameSet.cs
index 26795a07..fe5005c0 100644
--- a/Source/Core/NameSet.cs
+++ b/Source/Core/NameSet.cs
@@ -25,6 +25,9 @@ sealed class NameSet
// One write lock: a match is written once, then only read, and a lock per processor would be most of what a set takes.
readonly ConcurrentDictionary _matches = new(concurrencyLevel: 1, capacity: 4, StringComparer.Ordinal);
+ /// The real name each given name matched, by the name as the caller gave it (see ).
+ readonly ConcurrentDictionary _nameMatches = new(concurrencyLevel: 1, capacity: 4, StringComparer.Ordinal);
+
/// Initializes a new instance from the names as the provider reported them (a leading @ is fine); never the default array, but may be empty.
/// The names.
/// Where a procedure's set is kept (see ).
@@ -104,6 +107,33 @@ public int GetHashCode(string obj)
return entries.TryGetValue(name, out Entry? found) ? found : null;
}
+ ///
+ /// The real name that a name given as it is stands for, or when it matches none: the way an argument of AddParam matches, from one candidate that is the name itself.
+ ///
+ ///
+ /// The four tiers, exact first, a lower tier only when no higher one matches.
+ /// The answer is remembered apart from , which is keyed by argument text.
+ /// An ambiguity throws and is not remembered.
+ ///
+ /// The name as the caller gave it, with or without its @.
+ /// The procedure's name or the command text, for the message of an ambiguity.
+ /// What matches, for the message of an ambiguity.
+ /// What to do about an ambiguity.
+ /// The real name, or when the name matches none.
+ /// The name fits more than one parameter equally well.
+ public string? MatchName(string name, string procedure, string subject, string fix)
+ {
+ if (_nameMatches.TryGetValue(name, out string? remembered)) return remembered;
+
+ string bare = name.Length > 0 && name[0] == '@' ? name[1..] : name;
+
+ // Two threads may both match and store: the answer is the same.
+ string? found = ParameterNames.MatchBareAs([bare], Names, BareNames, name, procedure, subject, fix);
+ if (_nameMatches.Count < MaxMatches) _nameMatches[name] = found;
+
+ return found;
+ }
+
Dictionary BuildEntries()
{
var entries = new Dictionary(Names.Length, BareComparer.Instance);
diff --git a/Source/Core/Output.docs.xml b/Source/Core/Output.docs.xml
index 9c57c81f..7dc4c543 100644
--- a/Source/Core/Output.docs.xml
+++ b/Source/Core/Output.docs.xml
@@ -42,13 +42,21 @@
is empty, white space or a bare @.
-
+
- names the parameter exactly, with or without its @ and in any case.
+ is matched to a parameter the way the name of AddParam is, with or without its @: exactly, else ignoring case, else ignoring case and underscores, else after one common prefix such as p_ is removed from the declared name; a lower rule applies only when no higher one matches.
+ A name that matches two parameters by the same rule throws: pass the exact name.
A value added under the same name makes it .
+
+
+ The name of the output parameter, with or without its @, matched the way the name of AddParam is.
+ Two captures that match one parameter only through a looser rule fail the run; the same name, ignoring case, fails at the call.
+
+
+
A parameter added with a null value is sent as too,
@@ -148,15 +156,13 @@
At the call: cannot be read from output parameters
(a single value, or a type with no member to set);
- or a ReturnValue member reads the return code of a command that is not a stored procedure;
or another capture reads the same outputs (a model reads them all: use one model capture, or named captures only)
- or the return code (remove one).
+ or the return code (remove one) (for a capture added to the command after the query was made, when the terminal or stream is called).
The type the value converts to, as Map<T>() converts a single column.
- The name of the output parameter, with or without its @ and in any case.
The capture: await it after the terminal.
is .
is empty, white space or a bare @.
@@ -169,7 +175,6 @@
, which throws on NULL, or a of it, which reads NULL as .
- The name of the output parameter, with or without its @ and in any case.
The number of digits its SQL type declares, from 1 to 38.
The number of those digits after the decimal point, from 0 to .
The capture: await it after the terminal.
@@ -185,7 +190,6 @@
- The name of the output parameter, with or without its @ and in any case.
The number of digits its SQL type declares, from 1 to 38.
The number of those digits after the decimal point, from 0 to .
The capture: await it after the terminal; NULL is .
@@ -201,7 +205,7 @@
The type the return code converts to: , a nullable or wider integer, or an enum.
The capture: await it after the terminal.
- At the call: is a model; or the command is not a stored procedure, which has no return code;
+ At the call: is a model;
or another capture reads the return code.
@@ -209,6 +213,9 @@
The command, which carries the capture; its next async terminal fills it.
+
+ A capture of the return code (CaptureReturn, or a model with a ReturnValue member) is refused when the run starts if the command is not a stored procedure, which has no return code: the type can be set after the capture, so the run, not the call, decides.
+
The capture adds its output parameters when the terminal runs the command, and is complete when the terminal's task is.
A query that Map made from this command uses the command's captures too; the first run, by either route, fills them.
@@ -217,6 +224,10 @@
A command that carries a capture runs once, with an async terminal only:
a synchronous terminal, ExecuteAsync(command => …) and ExecuteOutputAsync throw,
and so does a second run, which needs a new command with a new capture.
+ A command whose type re-implements IExecuteReader cannot carry a capture, which reads through the library's reader.
+ A capture on the command is refused when a mapped query over it runs: that run throws (and completes the capture with it) before anything is executed.
+ The command's own terminals do not use the re-implemented reader.
+ Read the outputs with ExecuteOutputAsync instead.
@@ -225,11 +236,16 @@
A copy of the query that carries the capture; its async terminal fills it.
- The capture belongs to the copy, which also shares any capture on its command, and is complete when the terminal's task is.
+ A capture of the return code is refused when the run starts if the command is not a stored procedure.
+ The capture belongs to the copy, which also fills every capture its command has when the run starts, including one added to the command after this call; the first run fills them.
+ A stream or a buffer takes the command's captures when it is made: a capture added to the command after that is not part of its run.
+ The capture is complete when the terminal's task is.
A stream's capture completes when its enumerator is disposed: await it after the loop.
A loop that stops early (a ) still fills it, since the read is closed, not canceled.
That stop waits for the server to finish sending the response, which closing the reader reads through;
- the stall timeout does not bound that wait.
+ the stall timeout does not bound that wait, so a response that is slow or large keeps the loop's exit waiting.
+ A token the caller passed (to the call, the enumerator or the command) still cancels the read, and the capture is then canceled.
+ To stop without waiting, do not capture on a stream that may stop early; read the outputs with ExecuteOutputAsync instead.
A query that carries a capture runs once, with an async terminal only:
@@ -238,7 +254,7 @@
one from a DbQuery definition throws.
- The query is not built from an expressive command.
+ The query is not built from an expressive command, or its command re-implements IExecuteReader (thrown at the call).
diff --git a/Source/Core/OutputLayout.cs b/Source/Core/OutputLayout.cs
index b5dfb68b..f657ffd6 100644
--- a/Source/Core/OutputLayout.cs
+++ b/Source/Core/OutputLayout.cs
@@ -12,7 +12,7 @@ sealed class OutputMember
{
/// Initializes a member that is sent as an output parameter.
/// The member's name, its [Column] name, or the name the caller gave.
- /// when names the parameter exactly ([Column], the named form).
+ /// when names the parameter exactly ([Column]); matches it through the tiers (the named form, and a member without [Column]).
/// What the model's map reads the value as: the member's [Column] name, else its name.
/// How the parameter is sent.
/// The member for the messages: Model.Member, or The output parameter 'name'.
@@ -84,7 +84,7 @@ public OutputMember(OutputMember member, string display, OutputForm form)
/// The member for the messages: Model.Member, or The output parameter 'name' in the named form.
public readonly string Display;
- /// Whether names the parameter exactly, with or without its @ and in any case, never through the tiers.
+ /// Whether names the parameter exactly ([Column]), with or without its @ and in any case; otherwise the name is matched in the four tiers like the name of AddParam.
public readonly bool Exact;
/// What the model's map reads the value as.
@@ -539,7 +539,7 @@ public static OutputLayout Get(
return new(
new OutputMember(
name,
- exact: true,
+ exact: false,
name,
wire,
display,
@@ -610,7 +610,7 @@ public static OutputLayout Shaped(
return new(
new OutputMember(
name,
- exact: true,
+ exact: false,
name,
new OutputWire(DbType.Decimal, 0, precision, scale),
display,
diff --git a/Source/Core/ParameterNames.cs b/Source/Core/ParameterNames.cs
index 8fab9fad..f4299332 100644
--- a/Source/Core/ParameterNames.cs
+++ b/Source/Core/ParameterNames.cs
@@ -303,11 +303,19 @@ static bool ClosesAt(string s, int open, int close)
/// The text of the argument, for the message of an ambiguity.
/// The procedure's name, for the message of an ambiguity.
/// What matches, for the message of an ambiguity; names the argument.
- internal static string? MatchBareAs(ImmutableArray candidates, ImmutableArray parameterNames, ImmutableArray bareNames, string expression, string procedure, string? subject)
+ /// What to do about an ambiguity, ending its message; advises [Column] on the subject, or an explicit AddParam name.
+ internal static string? MatchBareAs(
+ ImmutableArray candidates,
+ ImmutableArray parameterNames,
+ ImmutableArray bareNames,
+ string expression,
+ string procedure,
+ string? subject,
+ string? fix = null)
{
foreach (string candidate in candidates)
{
- if (Find(expression, procedure, candidate, parameterNames, bareNames, subject) is { } found) return found;
+ if (Find(expression, procedure, candidate, parameterNames, bareNames, subject, fix) is { } found) return found;
}
return null;
@@ -327,7 +335,7 @@ static bool ClosesAt(string s, int open, int close)
_ => "ignoring case and underscores once one parameter prefix (p_, in_, i_, prm_, par_, v_ or a lone p) is removed from the real name",
};
- static string? Find(string expression, string procedure, string candidate, ImmutableArray parameterNames, ImmutableArray bareNames, string? subject)
+ static string? Find(string expression, string procedure, string candidate, ImmutableArray parameterNames, ImmutableArray bareNames, string? subject, string? fix = null)
{
// Tier 1: exact. Tier 2: ignoring case. Tier 3: ignoring case and underscores. Tier 4: the same without one common parameter prefix.
for (int tier = 1; tier <= 4; tier++)
@@ -342,7 +350,7 @@ static bool ClosesAt(string s, int open, int close)
throw new InvalidOperationException(
$"{subject ?? $"The argument '{expression}'"} matches both '{found}' and '{real}' of '{procedure}'. "
+ $"Its candidate name '{candidate}' fits each of them {TierText(tier)}. "
- + $"The procedure declares: {string.Join(", ", parameterNames)}. {(subject is null ? "Name the parameter explicitly: AddParam(\"name\", value)." : $"Name its parameter exactly with [Column(\"name\")] on {subject}.")}");
+ + $"The procedure declares: {string.Join(", ", parameterNames)}. {fix ?? (subject is null ? "Name the parameter explicitly: AddParam(\"name\", value)." : $"Name its parameter exactly with [Column(\"name\")] on {subject}.")}");
}
found = real;
diff --git a/Source/Core/ReaderReplacement.cs b/Source/Core/ReaderReplacement.cs
new file mode 100644
index 00000000..d2c189d0
--- /dev/null
+++ b/Source/Core/ReaderReplacement.cs
@@ -0,0 +1,81 @@
+namespace Open.Database.Extensions;
+
+// Whether a command type re-implements IExecuteReader, which a capture cannot
+// allow: a captured run reads through the library's own reader, so a type that
+// replaces that reader would be skipped silently. The answer is a property of
+// the type, found once with reflection and kept in a table that does not hold
+// the type alive. Only a captured run asks; an uncaptured call never does.
+static class ReaderReplacement
+{
+ // The two answers, as reference values, which the table needs.
+ static readonly object Replaced = new();
+ static readonly object Kept = new();
+
+ static readonly ConditionalWeakTable Answers = new();
+ static readonly ConditionalWeakTable> Lookups = new();
+
+ /// Gets how many times the type was looked up with
+ /// reflection.
+ /// The command type.
+ /// The count: one per successful lookup, so one after the first
+ /// captured run of a type that is not a library command; a failed
+ /// lookup is retried and counted again.
+ public static int LookupCount(Type type)
+ => Lookups.TryGetValue(type, out StrongBox? count)
+ ? Volatile.Read(ref count.Value)
+ : 0;
+
+ /// Gets whether the type re-implements
+ /// .
+ /// The command type.
+ /// if any method that implements the
+ /// interface, or an interface that extends it, is declared by a type other
+ /// than the library's command bases.
+ /// The lookup failed; the
+ /// failure is not cached, so the next call looks again.
+ public static bool Of(Type type)
+ => ReferenceEquals(Answers.GetValue(type, Detect), Replaced);
+
+ static object Detect(Type type)
+ {
+ StrongBox count = Lookups.GetOrCreateValue(type);
+ Interlocked.Increment(ref count.Value);
+
+ try
+ {
+ foreach (Type face in type.GetInterfaces())
+ {
+ if (!typeof(IExecuteReader).IsAssignableFrom(face))
+ {
+ continue;
+ }
+
+ InterfaceMapping map = type.GetInterfaceMap(face);
+ foreach (MethodInfo target in map.TargetMethods)
+ {
+ if (!IsLibraryBase(target.DeclaringType))
+ {
+ return Replaced;
+ }
+ }
+ }
+
+ return Kept;
+ }
+ catch (Exception ex)
+ {
+ throw new InvalidOperationException(
+ CaptureMessages.ReplacementUnknown(type, ex.Message),
+ ex);
+ }
+ }
+
+ // A plain command maps to the constructed base, never the open
+ // definition; a database command re-lists IExecuteReaderAsync, so it may
+ // map to either base.
+ static bool IsLibraryBase(Type? declaring)
+ => declaring is { IsGenericType: true }
+ && declaring.GetGenericTypeDefinition() is { } definition
+ && (definition == typeof(ExpressiveCommandBase<,,,,>)
+ || definition == typeof(ExpressiveDbCommandBase<,,,,>));
+}
diff --git a/Source/MSSqlClient/ExpressiveSqlCommand.cs b/Source/MSSqlClient/ExpressiveSqlCommand.cs
index fec8ee3e..d358747c 100644
--- a/Source/MSSqlClient/ExpressiveSqlCommand.cs
+++ b/Source/MSSqlClient/ExpressiveSqlCommand.cs
@@ -208,4 +208,11 @@ static async Task> ReadNamesAsync(SqlDataReader reader, C
while (await reader.ReadAsync(cancellationToken).ConfigureAwait(false)) names.Add(reader.GetString(0));
return names.ToImmutable();
}
+
+ ///
+ /// Gets whether this is exactly , which a capture
+ /// needs no lookup for.
+ ///
+ internal override bool IsLibraryCommand
+ => GetType() == typeof(ExpressiveSqlCommand);
}
diff --git a/Source/SqlClient/ExpressiveSqlCommand.cs b/Source/SqlClient/ExpressiveSqlCommand.cs
index 8a755967..b591bd89 100644
--- a/Source/SqlClient/ExpressiveSqlCommand.cs
+++ b/Source/SqlClient/ExpressiveSqlCommand.cs
@@ -196,4 +196,11 @@ static async Task> ReadNamesAsync(SqlDataReader reader, C
while (await reader.ReadAsync(cancellationToken).ConfigureAwait(false)) names.Add(reader.GetString(0));
return names.ToImmutable();
}
+
+ ///
+ /// Gets whether this is exactly , which a capture
+ /// needs no lookup for.
+ ///
+ internal override bool IsLibraryCommand
+ => GetType() == typeof(ExpressiveSqlCommand);
}
diff --git a/Tests/Open.Database.Extensions.Core.Tests/AllocationQuickWinTests.cs b/Tests/Open.Database.Extensions.Core.Tests/AllocationQuickWinTests.cs
index 52065eff..7061c394 100644
--- a/Tests/Open.Database.Extensions.Core.Tests/AllocationQuickWinTests.cs
+++ b/Tests/Open.Database.Extensions.Core.Tests/AllocationQuickWinTests.cs
@@ -256,12 +256,12 @@ public static void ToDictionary_ANullMapping_ThrowsArgumentNull()
.GetMethod("BareNames", BindingFlags.Static | BindingFlags.NonPublic)!
.CreateDelegate, ImmutableArray>>();
- static readonly Func, ImmutableArray, ImmutableArray, string, string, string?, string?> MatchBare = ParameterNamesType
+ static readonly Func, ImmutableArray, ImmutableArray, string, string, string?, string?, string?> MatchBare = ParameterNamesType
.GetMethod("MatchBareAs", BindingFlags.Static | BindingFlags.NonPublic)!
- .CreateDelegate, ImmutableArray, ImmutableArray, string, string, string?, string?>>();
+ .CreateDelegate, ImmutableArray, ImmutableArray, string, string, string?, string?, string?>>();
// The expression and the procedure only feed the message of an ambiguity; they cost nothing when there is none.
- static string? Match(ImmutableArray candidates, ImmutableArray parameterNames) => MatchBare(candidates, parameterNames, BareNames(parameterNames), "argument", "dbo.procedure", null);
+ static string? Match(ImmutableArray candidates, ImmutableArray parameterNames) => MatchBare(candidates, parameterNames, BareNames(parameterNames), "argument", "dbo.procedure", null, null);
static readonly ImmutableArray RealNames =
[
diff --git a/Tests/Open.Database.Extensions.Core.Tests/CaptureLibraryCommandTests.cs b/Tests/Open.Database.Extensions.Core.Tests/CaptureLibraryCommandTests.cs
new file mode 100644
index 00000000..df73a8e3
--- /dev/null
+++ b/Tests/Open.Database.Extensions.Core.Tests/CaptureLibraryCommandTests.cs
@@ -0,0 +1,41 @@
+extern alias mssql;
+
+#nullable enable
+
+namespace Open.Database.Extensions.Tests;
+
+// The library's own SQL Server commands are decided without a lookup, as the
+// base commands are: the exact type test is in each assembly.
+[ExcludeFromCodeCoverage]
+public static class CaptureLibraryCommandTests
+{
+ public sealed record Row(int Id);
+
+ // A query capture checks the command's type at the call, so nothing is
+ // opened or run.
+ [Fact]
+ public static void TheSqlCommands_NeedNoLookup_ForACapture()
+ {
+#pragma warning disable CS0618 // System.Data.SqlClient is obsolete; it is one of the two packages under test
+ using var legacy = new System.Data.SqlClient.SqlConnection();
+ _ = new ExpressiveSqlCommand(legacy, CommandType.StoredProcedure, "p")
+ .Map()
+ .CaptureOutput("total", out _);
+ using var connection = new Microsoft.Data.SqlClient.SqlConnection();
+ _ = new mssql::Open.Database.Extensions.ExpressiveSqlCommand(
+ connection,
+ CommandType.StoredProcedure,
+ "p")
+ .Map()
+ .CaptureOutput("total", out _);
+
+ Assert.Equal(
+ 0,
+ ReaderReplacement.LookupCount(typeof(ExpressiveSqlCommand)));
+#pragma warning restore CS0618
+ Assert.Equal(
+ 0,
+ ReaderReplacement.LookupCount(
+ typeof(mssql::Open.Database.Extensions.ExpressiveSqlCommand)));
+ }
+}
diff --git a/Tests/Open.Database.Extensions.Core.Tests/CaptureLocalDbTests.cs b/Tests/Open.Database.Extensions.Core.Tests/CaptureLocalDbTests.cs
index a8fed985..da5fb494 100644
--- a/Tests/Open.Database.Extensions.Core.Tests/CaptureLocalDbTests.cs
+++ b/Tests/Open.Database.Extensions.Core.Tests/CaptureLocalDbTests.cs
@@ -135,6 +135,31 @@ static async Task TakeOne(IAsyncEnumerable items)
}
}
+ // The loop's exit waits for the rest of the response: the output is set
+ // after 50000 rows, so it arrives only because closing the reader read
+ // them all. (The fake provider cannot tell: it does not read.)
+ [Fact]
+ public static async Task ABreak_AfterOneRow_StillFillsIt_BecauseTheRestIsRead()
+ {
+ LocalDbFixture.SkipUnlessAvailable();
+ using LocalDbFixture.Scratch procedure = Procedure(
+ "@total int output",
+ ManyRows + " set @total = 42;");
+ await using SqlConnection connection = await OpenAsync();
+ MappedQuery query = connection
+ .StoredProcedure("dbo." + procedure.Name)
+ .Map()
+ .CaptureOutput("total", out DbCapture total);
+
+ await foreach (Row row in query.ToPooledStream(Token))
+ {
+ Assert.Equal(1, row.Id);
+ break;
+ }
+
+ Assert.Equal(42, await total);
+ }
+
[Fact]
public static async Task ALaterError_FaultsIt_WithTheProvidersError()
{
@@ -214,6 +239,71 @@ public static async Task AModel_WithADecimal_AndTheNamedDecimal()
Assert.Equal(2, await count);
}
+ [Fact]
+ public static async Task ANamedCapture_FindsItsParameter_ThroughTheTiers()
+ {
+ LocalDbFixture.SkipUnlessAvailable();
+ using LocalDbFixture.Scratch procedure = Procedure(
+ "@total_count int output",
+ "select n as Id from (values (1), (2)) v(n); set @total_count = 2;");
+ await using SqlConnection connection = await OpenAsync();
+
+ List rows = await connection.StoredProcedure("dbo." + procedure.Name)
+ .CaptureOutput("totalCount", out DbCapture total)
+ .Map()
+ .ToListAsync(Token);
+
+ Assert.Equal(2, rows.Count);
+ Assert.Equal(2, await total);
+ }
+
+ [Fact]
+ public static async Task TwoNamedCaptures_OnOneParameter_FailTheRun()
+ {
+ LocalDbFixture.SkipUnlessAvailable();
+ using LocalDbFixture.Scratch procedure = Procedure(
+ "@total_count int output",
+ "select n as Id from (values (1), (2)) v(n); set @total_count = 2;");
+ await using SqlConnection connection = await OpenAsync();
+
+ // The call compares the names as written, so only the run finds the collision.
+ var query = connection.StoredProcedure("dbo." + procedure.Name)
+ .CaptureOutput("total_count", out DbCapture first)
+ .CaptureOutput("totalCount", out DbCapture second)
+ .Map();
+
+ var ex = await Assert.ThrowsAsync(async () => await query.ToListAsync(Token));
+ Assert.Contains("both resolve to the output parameter", ex.Message);
+ Assert.Contains("Name one of them exactly", ex.Message);
+ await Assert.ThrowsAsync(async () => await first);
+ await Assert.ThrowsAsync(async () => await second);
+ }
+
+ // The named form finds @p_total by the common-prefix rule (the fourth
+ // tier), on a capture and on ExecuteOutputAsync.
+ [Fact]
+ public static async Task ANamedCapture_FindsAPrefixedParameter()
+ {
+ LocalDbFixture.SkipUnlessAvailable();
+ using LocalDbFixture.Scratch procedure = Procedure(
+ "@p_total int output",
+ "select n as Id from (values (1), (2)) v(n); set @p_total = 2;");
+ await using SqlConnection connection = await OpenAsync();
+ string name = "dbo." + procedure.Name;
+
+ List rows = await connection.StoredProcedure(name)
+ .CaptureOutput("total", out DbCapture total)
+ .Map()
+ .ToListAsync(Token);
+
+ Assert.Equal(2, rows.Count);
+ Assert.Equal(2, await total);
+ Assert.Equal(
+ 2,
+ await connection.StoredProcedure(name)
+ .ExecuteOutputAsync("total", Token));
+ }
+
// A text command's @name OUTPUT marker.
[Fact]
public static async Task ATextCommand_FillsItThroughItsMarker()
diff --git a/Tests/Open.Database.Extensions.Core.Tests/CaptureStreamTests.cs b/Tests/Open.Database.Extensions.Core.Tests/CaptureStreamTests.cs
index 1724fbad..b434ed45 100644
--- a/Tests/Open.Database.Extensions.Core.Tests/CaptureStreamTests.cs
+++ b/Tests/Open.Database.Extensions.Core.Tests/CaptureStreamTests.cs
@@ -76,14 +76,19 @@ public static async Task AStall_FaultsIt_WithTheTimeout(int bufferSize)
IAsyncEnumerable rows = Query(c, out DbCapture total)
.StreamBuffered(TimeSpan.FromMilliseconds(50), bufferSize, Token);
- await Assert.ThrowsAsync(async () =>
+ var thrown = await Assert.ThrowsAsync(async () =>
{
await foreach (Row _ in rows)
{
await Task.Delay(400, Token);
}
});
- await Assert.ThrowsAsync(async () => await total);
+
+ // The capture faults with the loop's own exception: same type and
+ // message.
+ var captured = await Assert.ThrowsAsync(
+ async () => await total);
+ Assert.Equal(thrown.Message, captured.Message);
}
[Theory]
@@ -566,8 +571,8 @@ public static async Task ACanceledToken_ThrowsAtTheCall_AndArmsNothing()
// ---- a command that re-implements its reader -------------------------
- // Its own reader function never adds the outputs: a captured run takes
- // the command's own reader path, so the capture is claimed and filled.
+ // A captured run reads through the library's reader, so a command type
+ // that replaces it is refused, never bypassed.
sealed class OwnReaderCommand(CaptureConnection connection)
: ExpressiveCommand(
() => connection,
@@ -593,52 +598,186 @@ async ValueTask
}
}
+ sealed class PlainCommand(CaptureConnection connection)
+ : ExpressiveCommand(
+ () => connection,
+ CommandType.StoredProcedure,
+ "p");
+
+ sealed class PlainDbCommand(CaptureConnection connection)
+ : ExpressiveDbCommand(
+ () => connection,
+ CommandType.StoredProcedure,
+ "p");
+
+ const string Replaced = "re-implementing IExecuteReader";
+
+ static MappedQuery OnCommand(
+ OwnReaderCommand command,
+ out DbCapture total)
+ => command.CaptureOutput("total", out total)
+ .Map();
+
[Fact]
- public static async Task ACommandThatReimplementsItsReader_StillFillsIt()
+ public static void AQueryCapture_OnAReimplementingCommand_IsRefusedAtTheCall()
{
var c = new CaptureConnection(("total", 9));
var command = new OwnReaderCommand(c);
+ MappedQuery query = command.Map();
- List rows = await command.CaptureOutput(
- "total",
- out DbCapture total)
- .Map()
- .ToListAsync(Token);
-
- Assert.Equal(3, rows.Count);
- Assert.Equal(9, await total);
+ var ex = Assert.Throws(
+ () => query.CaptureOutput("total", out _));
+ Contains(
+ ex,
+ nameof(OwnReaderCommand),
+ Replaced,
+ "read the outputs with ExecuteOutputAsync");
+ Assert.Throws(
+ () => query.CaptureReturn(out _));
+ Assert.Throws(
+ () => query.Skip(1).CaptureOutput("total", out _));
Assert.Equal(0, command.OwnReads);
+ Assert.Equal(0, c.Executed);
+ }
- // Without a capture, its own reader runs as before.
- var plain = new OwnReaderCommand(c);
- Assert.Single(await plain.Map()
- .ToListAsync(Token));
- Assert.Equal(1, plain.OwnReads);
+ public static TheoryData RefusedTerminals
+ => new(
+ "ToListAsync", "AnyAsync", "SingleResult", "AsObjectArrays",
+ "Stream", "ToPooledBuffer",
+ "ToChannelReader", "AsSourceBlock", "ToTargetBlock");
+
+ // The command's capture reaches the one choke of the mapped query, at the
+ // first read of each terminal, and refuses there.
+ [Theory]
+ [MemberData(nameof(RefusedTerminals))]
+ public static async Task ACommandCapture_OnAReimplementingCommand_IsRefusedAtTheRun(
+ string terminal)
+ {
+ var c = new CaptureConnection(("total", 9));
+ var command = new OwnReaderCommand(c);
+ DbCapture total;
+ var forever = Timeout.InfiniteTimeSpan;
+
+ Func run;
+ switch (terminal)
+ {
+ case "ToListAsync":
+ {
+ MappedQuery query = OnCommand(command, out total);
+ run = async () => await query.ToListAsync(Token);
+ break;
+ }
+ case "Stream":
+ {
+ MappedQuery query = OnCommand(command, out total);
+ run = async () =>
+ {
+ await foreach (Row _ in query.Stream(forever, Token)) { }
+ };
+ break;
+ }
+ case "ToPooledBuffer":
+ {
+ MappedQuery query = OnCommand(command, out total);
+ run = async () =>
+ {
+ using PooledBuffer buffer = query.ToPooledBuffer(Token);
+ await foreach (Row _ in buffer.AsAsyncEnumerable(Token)) { }
+ };
+ break;
+ }
+ case "ToChannelReader":
+ {
+ MappedQuery query = OnCommand(command, out total);
+ ChannelReader reader = query.ToChannelReader(Token);
+ run = async () =>
+ {
+ await foreach (Row _ in reader.ReadAllAsync(Token)) { }
+ };
+ break;
+ }
+ case "AsSourceBlock":
+ {
+ MappedQuery query = OnCommand(command, out total);
+ IReceivableSourceBlock block = query.AsSourceBlock(Token);
+ run = async () => await block.Completion;
+ break;
+ }
+ case "ToTargetBlock":
+ {
+ MappedQuery query = OnCommand(command, out total);
+ var block = new BufferBlock();
+ run = async () => await query.ToTargetBlock(block, Token);
+ break;
+ }
+ case "AnyAsync":
+ {
+ MappedQuery query = OnCommand(command, out total);
+ run = async () => await query.AnyAsync(Token);
+ break;
+ }
+ case "AsObjectArrays":
+ {
+ command.CaptureOutput("total", out total);
+ run = async () =>
+ await command.AsObjectArrays().ToListAsync(Token);
+ break;
+ }
+ default:
+ {
+ command.CaptureOutput("total", out total);
+ run = async () => await command.SingleResult()
+ .Map()
+ .ToListAsync(Token);
+ break;
+ }
+ }
+
+ var ex = await Assert.ThrowsAsync(run);
+ Contains(
+ ex,
+ nameof(OwnReaderCommand),
+ Replaced,
+ "read the outputs with ExecuteOutputAsync");
+
+ // Never pending: the capture completed with the same refusal.
+ Assert.True(total.AsTask().IsFaulted);
+ Assert.Same(
+ ex,
+ await Assert.ThrowsAsync(
+ async () => await total));
+ Assert.Equal(0, command.OwnReads);
+ Assert.Equal(0, c.Executed);
}
+ // CancelOnEarlyStop is refused before the reader is asked, so its own
+ // message holds; the run is still refused.
[Fact]
- public static async Task ACommandThatReimplementsItsReader_OnAQueryCapture()
+ public static async Task ACommandCapture_WithCancelOnEarlyStop_KeepsItsOwnMessage()
{
var c = new CaptureConnection(("total", 9));
var command = new OwnReaderCommand(c);
+ MappedQuery query = OnCommand(command, out DbCapture total)
+ .CancelOnEarlyStop();
- List rows = await command.Map()
- .CaptureOutput("total", out DbCapture total)
- .ToListAsync(Token);
-
- Assert.Equal(3, rows.Count);
- Assert.Equal(9, await total);
+ var ex = await Assert.ThrowsAsync(
+ async () => await query.ToListAsync(Token));
+ Contains(ex, "cannot be used with CancelOnEarlyStop()");
+ Assert.Same(
+ ex,
+ await Assert.ThrowsAsync(
+ async () => await total));
Assert.Equal(0, command.OwnReads);
+ Assert.Equal(0, c.Executed);
}
- // The synchronous path is refused before its own reader is asked.
+ // The synchronous refusal comes first, so it keeps its message.
[Fact]
- public static void ACommandThatReimplementsItsReader_RefusesSync()
+ public static void ACommandCapture_OnAReimplementingCommand_RefusesSync()
{
var c = new CaptureConnection(("total", 9));
var command = new OwnReaderCommand(c);
- MappedQuery query = command.Map()
- .CaptureOutput("total", out DbCapture total);
+ MappedQuery query = OnCommand(command, out DbCapture total);
Contains(
Assert.Throws(() => query.ToList()),
@@ -651,6 +790,97 @@ public static void ACommandThatReimplementsItsReader_RefusesSync()
"has not started");
}
+ // Without a capture, its own reader runs as before.
+ [Fact]
+ public static async Task AReimplementingCommand_WithoutACapture_RunsItsOwnReader()
+ {
+ var c = new CaptureConnection(("total", 9));
+ var plain = new OwnReaderCommand(c);
+
+ Assert.Single(await plain.Map()
+ .ToListAsync(Token));
+ Assert.Equal(1, plain.OwnReads);
+ }
+
+ // The way out the docs give a re-implementing command: it reads the
+ // outputs through the library, not through its own reader.
+ [Fact]
+ public static async Task AReimplementingCommand_ReadsItsOutputs_WithExecuteOutputAsync()
+ {
+ var c = new CaptureConnection(("total", 9));
+ var command = new OwnReaderCommand(c);
+
+ Assert.Equal(
+ 9,
+ await command.ExecuteOutputAsync("total", Token));
+ Assert.Equal(0, command.OwnReads);
+ Assert.Equal(1, c.Executed);
+ }
+
+ [Fact]
+ public static async Task APlainSubclass_FillsItsCapture_OnBothForms()
+ {
+ var c = new CaptureConnection(("total", 9));
+
+ List onCommand = await new PlainCommand(c)
+ .CaptureOutput("total", out DbCapture first)
+ .Map()
+ .ToListAsync(Token);
+ Assert.Equal(3, onCommand.Count);
+ Assert.Equal(9, await first);
+
+ List onQuery = await new PlainCommand(c)
+ .Map()
+ .CaptureOutput("total", out DbCapture second)
+ .ToListAsync(Token);
+ Assert.Equal(3, onQuery.Count);
+ Assert.Equal(9, await second);
+
+ List onDbCommand = await new PlainDbCommand(c)
+ .CaptureOutput("total", out DbCapture third)
+ .Map()
+ .ToListAsync(Token);
+ Assert.Equal(3, onDbCommand.Count);
+ Assert.Equal(9, await third);
+
+ List onDbQuery = await new PlainDbCommand(c)
+ .Map()
+ .CaptureOutput("total", out DbCapture fourth)
+ .ToListAsync(Token);
+ Assert.Equal(3, onDbQuery.Count);
+ Assert.Equal(9, await fourth);
+
+ // One lookup per type, however many captured runs.
+ Assert.Equal(1, ReaderReplacement.LookupCount(typeof(PlainCommand)));
+ Assert.Equal(1, ReaderReplacement.LookupCount(typeof(PlainDbCommand)));
+ }
+
+ // The library's own command types are decided without a lookup.
+ [Fact]
+ public static async Task ALibraryCommand_WithACapture_NeedsNoLookup()
+ {
+ var c = new CaptureConnection(("total", 9));
+
+ await new ExpressiveCommand(() => c, CommandType.StoredProcedure, "p")
+ .CaptureOutput("total", out DbCapture first)
+ .Map()
+ .ToListAsync(Token);
+ Assert.Equal(9, await first);
+
+ await new ExpressiveDbCommand(() => c, CommandType.StoredProcedure, "p")
+ .Map()
+ .CaptureOutput("total", out DbCapture second)
+ .ToListAsync(Token);
+ Assert.Equal(9, await second);
+
+ Assert.Equal(
+ 0,
+ ReaderReplacement.LookupCount(typeof(ExpressiveCommand)));
+ Assert.Equal(
+ 0,
+ ReaderReplacement.LookupCount(typeof(ExpressiveDbCommand)));
+ }
+
// ---- an argument guard -----------------------------------------------
// The guard throws before anything is armed (decision 9): the capture
diff --git a/Tests/Open.Database.Extensions.Core.Tests/CaptureTests.cs b/Tests/Open.Database.Extensions.Core.Tests/CaptureTests.cs
index 9a5477ad..6007687f 100644
--- a/Tests/Open.Database.Extensions.Core.Tests/CaptureTests.cs
+++ b/Tests/Open.Database.Extensions.Core.Tests/CaptureTests.cs
@@ -366,26 +366,16 @@ public static void EachOutput_HasOneOwner_CheckedAtTheCall()
}
[Fact]
- public static void TheReturnCode_NeedsAStoredProcedure_AndAnInteger()
+ public static void TheReturnCode_NeedsAnInteger()
{
var c = new CaptureConnection();
- Contains(
- Assert.Throws(() => c
- .Command("select 1")
- .CaptureReturn(out DbCapture _)),
- "CaptureReturn needs a stored procedure",
- "StoredProcedure(…)");
- Contains(
- Assert.Throws(() => c
- .Command("select 1")
- .CaptureOutput(out DbCapture _)),
- "the ReturnValue member of Touched, which needs a stored procedure");
Contains(
Assert.Throws(() => c
.StoredProcedure("p")
.CaptureReturn(out DbCapture _)),
- "CaptureReturn cannot hold it");
+ "CaptureReturn cannot hold it",
+ "Use CaptureReturn");
}
[Fact]
@@ -991,4 +981,224 @@ await Assert.ThrowsAsync(
"the query never ran");
Assert.Equal(0, c.Executed);
}
+
+ // ---- a capture added to the command after the query was made ----------
+
+ [Theory]
+ [InlineData(false, false)]
+ [InlineData(false, true)]
+ [InlineData(true, false)]
+ [InlineData(true, true)]
+ public static async Task ACommandCapture_AddedAfterMap_IsFilledToo(
+ bool commandFirst,
+ bool stream)
+ {
+ var c = new CaptureConnection(("total", 9), ("count", 4));
+ var command = c.StoredProcedure("p");
+ DbCapture total;
+ DbCapture count;
+ MappedQuery query;
+ if (commandFirst)
+ {
+ command.CaptureOutput("count", out count);
+ query = command.Map()
+ .CaptureOutput("total", out total);
+ }
+ else
+ {
+ query = command.Map()
+ .CaptureOutput("total", out total);
+ command.CaptureOutput("count", out count);
+ }
+
+ if (stream)
+ {
+ await foreach (Row _ in query.ToPooledStream(Token)) { }
+ }
+ else
+ {
+ await query.ToListAsync(Token);
+ }
+
+ Assert.Equal(9, await total);
+ Assert.Equal(4, await count);
+ Assert.Equal(1, c.Executed);
+
+ // One run: a second is refused.
+ await Assert.ThrowsAsync(
+ async () => await query.ToListAsync(Token));
+ }
+
+ [Fact]
+ public static async Task ALateCommandCapture_ThatConflicts_ThrowsAtTheTerminal()
+ {
+ var c = new CaptureConnection(("total", 9));
+ var command = c.StoredProcedure("p");
+ MappedQuery query = command.Map()
+ .CaptureOutput("total", out DbCapture own);
+ command.CaptureOutput("total", out DbCapture late);
+
+ Contains(
+ await Assert.ThrowsAsync(
+ async () => await query.ToListAsync(Token)),
+ "reads output parameter @total twice",
+ "Capture each parameter once");
+ Assert.Equal(0, c.Executed);
+
+ // Nothing was armed: each capture says it has not started.
+ foreach (DbCapture capture in (DbCapture[])[own, late])
+ {
+ Contains(
+ Assert.Throws(
+ () => { _ = capture.AsTask(); }),
+ "has not started");
+ }
+ }
+
+ [Fact]
+ public static void ALateCommandCapture_ThatConflicts_ThrowsAtASyncTerminal()
+ {
+ var c = new CaptureConnection(("total", 9));
+ var command = c.StoredProcedure("p");
+ MappedQuery query = command.Map()
+ .CaptureOutput("total", out DbCapture _);
+ command.CaptureOutput("total", out DbCapture _);
+
+ Contains(
+ Assert.Throws(() => query.ToList()),
+ "reads output parameter @total twice");
+ Assert.Equal(0, c.Executed);
+ }
+
+ [Fact]
+ public static void ALateCommandCapture_ThatConflicts_ThrowsAtAStreamCall()
+ {
+ var c = new CaptureConnection(("total", 9));
+ var command = c.StoredProcedure("p");
+ MappedQuery query = command.Map()
+ .CaptureOutput("total", out DbCapture _);
+ command.CaptureOutput("total", out DbCapture _);
+
+ Contains(
+ Assert.Throws(
+ () => query.ToPooledStream(Token)),
+ "reads output parameter @total twice",
+ "Capture each parameter once");
+ Assert.Equal(0, c.Executed);
+ }
+
+ // A stream or a buffer takes the command's captures when it is made: one
+ // added to the command after that is not part of its run.
+ [Theory]
+ [InlineData(false)]
+ [InlineData(true)]
+ public static async Task ACommandCapture_AddedAfterTheStreamIsMade_IsNotFilled(
+ bool buffer)
+ {
+ var c = new CaptureConnection(("total", 9), ("count", 4));
+ var command = c.StoredProcedure("p");
+ MappedQuery query = command.Map()
+ .CaptureOutput("total", out DbCapture total);
+
+ if (buffer)
+ {
+ using PooledBuffer made = query.ToPooledBuffer(Token);
+ command.CaptureOutput("count", out DbCapture late);
+ _ = await made.Items;
+ AssertNotFilled(c, late);
+ }
+ else
+ {
+ IAsyncEnumerable rows = query.ToPooledStream(Token);
+ command.CaptureOutput("count", out DbCapture late);
+ await foreach (Row _ in rows) { }
+ AssertNotFilled(c, late);
+ }
+
+ Assert.Equal(9, await total);
+ }
+
+ static void AssertNotFilled(CaptureConnection c, DbCapture late)
+ {
+ Assert.DoesNotContain(
+ c.Last!.All,
+ static p => p.ParameterName == "count");
+ Contains(
+ Assert.Throws(
+ () => { _ = late.AsTask(); }),
+ "has not started");
+ }
+
+ // ---- the return code: the run decides, the command's type can change ----
+
+ [Fact]
+ public static async Task ACommandTypeSetAfterCaptureReturn_IsHonored()
+ {
+ var c = new CaptureConnection(("", 7));
+ var command = c.Command("p")
+ .CaptureReturn(out DbCapture code);
+
+ command.Type = CommandType.StoredProcedure;
+ await command.ExecuteNonQueryAsync(Token);
+
+ Assert.Equal(7, await code);
+ }
+
+ [Fact]
+ public static async Task AReturnCode_OnATextCommand_IsRefusedAtTheRun()
+ {
+ var c = new CaptureConnection(("", 7));
+ var command = c.Command("select 1")
+ .CaptureReturn(out DbCapture code);
+
+ Contains(
+ await Assert.ThrowsAsync(
+ async () => await command.ExecuteNonQueryAsync(Token)),
+ "CaptureReturn needs a stored procedure",
+ "StoredProcedure(…)");
+ Contains(
+ await Assert.ThrowsAsync