Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
90 changes: 76 additions & 14 deletions Source/Core/Capture.cs
Original file line number Diff line number Diff line change
Expand Up @@ -408,24 +408,14 @@ sealed class CaptureSet : CaptureHolder
/// <param name="source">The new capture.</param>
/// <param name="onQuery"><see langword="true"/> when it is attached on a
/// mapped query.</param>
/// <param name="isProcedure">Whether the command is a stored
/// procedure.</param>
/// <returns>The new set.</returns>
/// <exception cref="InvalidOperationException">The capture reads the return
/// code of a command that is not a stored procedure, or reads what another
/// capture reads.</exception>
/// <exception cref="InvalidOperationException">The capture reads what
/// another capture reads.</exception>
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";
Expand All @@ -435,9 +425,67 @@ public static CaptureSet With(
return new([.. set.Sources, source], onQuery || set.OnQuery);
}

/// <summary>
/// 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.
/// </summary>
/// <param name="command">The command's captures.</param>
/// <param name="own">The query's own captures.</param>
/// <returns>A set of the command's sources, then the query's own.</returns>
/// <exception cref="InvalidOperationException">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.</exception>
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);
}

/// <summary>
/// The last set made by <see cref="CombinedWith"/>, with the command's set
/// it was made for.
/// </summary>
sealed class Combination(CaptureSet command, CaptureSet result)
{
public readonly CaptureSet Command = command;

public readonly CaptureSet Result = result;
}

Combination? _combined;

/// <summary>
/// Gets what a run fills: the command's captures as they are now,
/// combined with these (see <see cref="Combine"/>).
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
/// <param name="command">The command's captures now.</param>
/// <returns>The set the run claims.</returns>
/// <exception cref="InvalidOperationException">See
/// <see cref="Combine"/>.</exception>
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)
Expand Down Expand Up @@ -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).";
}
7 changes: 7 additions & 0 deletions Source/Core/ExpressiveCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
}

/// <summary>
/// Gets whether this is exactly <see cref="ExpressiveCommand"/>, which a capture
/// needs no lookup for.
/// </summary>
internal override bool IsLibraryCommand
=> GetType() == typeof(ExpressiveCommand);
}
37 changes: 28 additions & 9 deletions Source/Core/ExpressiveCommandBase.Capture.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,12 @@ interface ICaptureRunner
/// <see langword="null"/>.</summary>
CaptureSet? Captures { get; }

/// <summary>Gets whether the command is a stored procedure, which has a
/// return code.</summary>
bool IsProcedure { get; }
/// <summary>Gets whether the command's type re-implements
/// <see cref="IExecuteReader"/>, which a capture cannot read
/// through.</summary>
/// <exception cref="InvalidOperationException">The type could not be
/// examined.</exception>
bool ReplacesReader { get; }

/// <summary>Executes a reader on the command, filling the given
/// captures.</summary>
Expand Down Expand Up @@ -97,6 +100,8 @@ public TThis CaptureOutput<TOut>(out DbCapture<TOut> output)
/// <include file="Output.docs.xml"
/// path="docs/members[@name='capture-named']/*" />
/// <include file="Output.docs.xml"
/// path="docs/members[@name='out-name-param']/*" />
/// <include file="Output.docs.xml"
/// path="docs/members[@name='capture-returns-command']/*" />
public TThis CaptureOutput<TValue>(string name, out DbCapture<TValue> value)
{
Expand All @@ -114,6 +119,8 @@ public TThis CaptureOutput<TValue>(string name, out DbCapture<TValue> value)
/// <include file="Output.docs.xml"
/// path="docs/members[@name='capture-shaped']/*" />
/// <include file="Output.docs.xml"
/// path="docs/members[@name='out-name-param']/*" />
/// <include file="Output.docs.xml"
/// path="docs/members[@name='capture-returns-command']/*" />
public TThis CaptureOutput<TValue>(
string name,
Expand All @@ -137,6 +144,8 @@ public TThis CaptureOutput<TValue>(
/// <include file="Output.docs.xml"
/// path="docs/members[@name='capture-decimal']/*" />
/// <include file="Output.docs.xml"
/// path="docs/members[@name='out-name-param']/*" />
/// <include file="Output.docs.xml"
/// path="docs/members[@name='capture-returns-command']/*" />
public TThis CaptureOutputDecimal(
string name,
Expand Down Expand Up @@ -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;
/// <summary>
/// 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.
/// </summary>
/// <remarks>
/// Overridden by each concrete library command as an exact type test
/// (those types are not sealed, and a subclass is looked up).
/// </remarks>
internal virtual bool IsLibraryCommand
=> false;

bool ICaptureRunner.ReplacesReader
=> !IsLibraryCommand && ReaderReplacement.Of(GetType());

ValueTask<TResult> ICaptureRunner.ExecuteReaderAsync<TState, TResult>(
CaptureHolder captures,
Expand Down Expand Up @@ -234,8 +253,8 @@ async ValueTask<TResult> ExecuteCapturedAsync<TState, TResult>(
"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();
Expand Down
18 changes: 14 additions & 4 deletions Source/Core/ExpressiveCommandBase.Output.cs
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ static async (cmd, _, run) =>
/// and reads one output parameter, converted to <typeparamref name="T"/>.
/// </summary>
/// <remarks>
/// <include file="Output.docs.xml" path="docs/members[@name='out-name-exact']/*" />
/// <include file="Output.docs.xml" path="docs/members[@name='out-name-rule']/*" />
/// <include file="Output.docs.xml" path="docs/members[@name='out-null-input']/*" />
/// <include file="Output.docs.xml" path="docs/members[@name='out-return-name']/*" />
/// <include file="Output.docs.xml" path="docs/members[@name='out-datetime']/*" />
Expand Down Expand Up @@ -220,7 +220,7 @@ static async ValueTask<decimal> NotNullAsync(string name, ValueTask<decimal?> va
/// </summary>
/// <remarks>
/// <include file="Output.docs.xml" path="docs/members[@name='out-decimal-why']/*" />
/// <include file="Output.docs.xml" path="docs/members[@name='out-name-exact']/*" />
/// <include file="Output.docs.xml" path="docs/members[@name='out-name-rule']/*" />
/// <include file="Output.docs.xml" path="docs/members[@name='out-null-input']/*" />
/// <include file="Output.docs.xml" path="docs/members[@name='out-return-name']/*" />
/// <include file="Output.docs.xml" path="docs/members[@name='out-decimal-choice']/*" />
Expand Down Expand Up @@ -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);
}

Expand All @@ -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."));
}
}

Expand Down
11 changes: 11 additions & 0 deletions Source/Core/ExpressiveCommandBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -396,6 +396,10 @@ protected TThis AddParam(Param param)
/// A <paramref name="type"/> you pass always wins.
/// The <see cref="object"/> overloads have no type to use:
/// pass a database type.
/// A <see cref="DbType"/> passed as the value, as in
/// <c>AddParam("@id", DbType.Int32)</c> on a command whose database type
/// is not <see cref="DbType"/> (the SQL Server commands), is a value, and
/// is sent as one: pass the database type as the third argument.
/// </remarks>
/// <exception cref="ArgumentNullException"><paramref name="name"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentException"><paramref name="name"/> is empty or white space.</exception>
Expand Down Expand Up @@ -1947,6 +1951,13 @@ ValueTask<T> IExecuteReader.ExecuteReaderAsync<T>(Func<IDataReader, ValueTask<T>
/// <typeparamref name="T"/>.
/// </summary>
/// <inheritdoc cref="SyncExpressiveExtensions.ExecuteReturn{T}(IExecuteCommand)"/>
/// <exception cref="InvalidOperationException">
/// At the call, before anything runs and not in the returned task:
/// <typeparamref name="T"/> is a model, which cannot hold the return code.
/// Use <c>int</c> (or <c>int?</c>, <c>long</c>, an enum), or read it with
/// a <c>ReturnValue</c> member of an output model
/// (<c>ExecuteOutputAsync&lt;TOut&gt;()</c>).
/// </exception>
/// <include file="Commands.docs.xml" path="docs/members[@name='token']/*" />
public ValueTask<T> ExecuteReturnAsync<T>(
CancellationToken cancellationToken = default)
Expand Down
7 changes: 7 additions & 0 deletions Source/Core/ExpressiveDbCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
}

/// <summary>
/// Gets whether this is exactly <see cref="ExpressiveDbCommand"/>, which a capture
/// needs no lookup for.
/// </summary>
internal override bool IsLibraryCommand
=> GetType() == typeof(ExpressiveDbCommand);
}
52 changes: 44 additions & 8 deletions Source/Core/MappedQuery.Capture.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,18 @@ readonly partial struct MappedQueryCore<T>
// 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;
}

/// <summary>
/// Gets the run a stream or a buffer claimed, or <see langword="null"/>.
Expand All @@ -29,11 +40,15 @@ public CaptureRun? CapturedRun
/// </summary>
/// <param name="source">The capture, its arguments checked.</param>
/// <returns>A copy of the query that carries the capture.</returns>
/// <exception cref="InvalidOperationException">A default value, a capture
/// of the return code of a command that is not a stored procedure, or a
/// <exception cref="InvalidOperationException">A default value, or a
/// capture that reads what another one reads.</exception>
/// <exception cref="InvalidOperationException">The command's type could not
/// be examined for a re-implemented reader (see
/// <see cref="ReaderReplacement.Of"/>).</exception>
/// <exception cref="NotSupportedException">The query does not read from an
/// expressive command.</exception>
/// expressive command, or the command's type re-implements
/// <see cref="IExecuteReader"/>, which a capture cannot read
/// through.</exception>
public MappedQueryCore<T> WithCapture(ICaptureSource source)
{
EnsureCommand();
Expand All @@ -47,12 +62,27 @@ public MappedQueryCore<T> 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);
Expand Down Expand Up @@ -137,6 +167,8 @@ public MappedQuery<T> CaptureOutput<TOut>(out DbCapture<TOut> output)
/// <include file="Output.docs.xml"
/// path="docs/members[@name='capture-named']/*" />
/// <include file="Output.docs.xml"
/// path="docs/members[@name='out-name-param']/*" />
/// <include file="Output.docs.xml"
/// path="docs/members[@name='capture-query']/*" />
public MappedQuery<T> CaptureOutput<TValue>(
string name,
Expand All @@ -156,6 +188,8 @@ public MappedQuery<T> CaptureOutput<TValue>(
/// <include file="Output.docs.xml"
/// path="docs/members[@name='capture-shaped']/*" />
/// <include file="Output.docs.xml"
/// path="docs/members[@name='out-name-param']/*" />
/// <include file="Output.docs.xml"
/// path="docs/members[@name='capture-query']/*" />
public MappedQuery<T> CaptureOutput<TValue>(
string name,
Expand All @@ -179,6 +213,8 @@ public MappedQuery<T> CaptureOutput<TValue>(
/// <include file="Output.docs.xml"
/// path="docs/members[@name='capture-decimal']/*" />
/// <include file="Output.docs.xml"
/// path="docs/members[@name='out-name-param']/*" />
/// <include file="Output.docs.xml"
/// path="docs/members[@name='capture-query']/*" />
public MappedQuery<T> CaptureOutputDecimal(
string name,
Expand Down
Loading
Loading