Skip to content
Merged
23 changes: 6 additions & 17 deletions Source/Core/BoundCall.cs
Original file line number Diff line number Diff line change
Expand Up @@ -339,8 +339,8 @@ public static ValueTask<TOut> ExecuteOutputAsync<TOut>(
call.Call.Params, cancellationToken);

/// <summary>
/// Runs the write and returns the stored procedure's return code, converted
/// to <typeparamref name="T"/>.
/// Runs the write and returns its return code, converted to
/// <typeparamref name="T"/>.
/// </summary>
/// <remarks>
/// <include file="Output.docs.xml" path="docs/members[@name='def-return']/*" />
Expand All @@ -349,27 +349,20 @@ public static ValueTask<TOut> ExecuteOutputAsync<TOut>(
/// <param name="call">The bound call.</param>
/// <include file="Mapped.docs.xml" path="docs/members[@name='token-call']/*" />
/// <returns>A task that represents the asynchronous operation; its result is the return code.</returns>
/// <exception cref="InvalidOperationException">Before any connection is used: <typeparamref name="T"/> is a model, the call's definition is text (it has no return code), <paramref name="call"/> is a <see langword="default"/> value, or a capture on the call reads the return code too.</exception>
/// <exception cref="InvalidOperationException">Before any connection is used: <typeparamref name="T"/> is a model, <paramref name="call"/> is a <see langword="default"/> value, or a capture on the call reads the return code too.</exception>
/// <exception cref="OperationCanceledException"><paramref name="cancellationToken"/> is canceled.</exception>
public static ValueTask<T> ExecuteReturnAsync<T>(
this BoundCall<NonQueryKind> call,
CancellationToken cancellationToken = default)
{
// All checked at the call, before a task exists or a connection is used.
ReturnCode<T>.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.
call.Captures?.ThrowIfReturnBeside(cancellationToken);

return DbQueryRunner.ReturnAsync<T>(
definition,
call.Call.Definition,
call.Call.SourceCore,
call.Call.Params,
call.Captures,
Expand All @@ -378,15 +371,11 @@ public static ValueTask<T> ExecuteReturnAsync<T>(

// ---- 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.
// Returns the call with one more capture, checked at the call.
static BoundCall<TKind> WithCapture<TKind>(
BoundCall<TKind> call,
ICaptureSource source)
=> new(
call.Call,
CaptureSet.WithOnDefinition(
call.Captures, source, call.Call.Definition.Kind));
=> new(call.Call, CaptureSet.WithOnQuery(call.Captures, source));

// The call with the capture, and the capture's handle for the caller.
static BoundCall<TKind> WithCapture<TKind, TValue>(
Expand Down
63 changes: 0 additions & 63 deletions Source/Core/Capture.cs
Original file line number Diff line number Diff line change
Expand Up @@ -463,37 +463,6 @@ CaptureSet Added(ICaptureSource source)
return new([.. Sources, source], OnQuery);
}

/// <summary>
/// Returns the captures of a definition's call with one more, as
/// <see cref="WithOnQuery"/> does.
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
/// <param name="set">The captures so far, or
/// <see langword="null"/>.</param>
/// <param name="source">The new capture.</param>
/// <param name="kind">The definition's kind.</param>
/// <returns>The new set.</returns>
/// <exception cref="InvalidOperationException">The capture reads the
/// return code of a definition that is not a stored procedure, or reads
/// what another capture reads.</exception>
public static CaptureSet WithOnDefinition(
CaptureSet? set,
ICaptureSource source,
CommandType kind)
{
if (source.ReadsReturn && kind != CommandType.StoredProcedure)
{
throw new InvalidOperationException(
CaptureMessages.NotProcedure(source));
}

return WithOnQuery(set, source);
}

/// <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.
Expand Down Expand Up @@ -622,12 +591,6 @@ public override Exception Refuse(
return exception;
}

/// <summary>Makes the exception for a capture that reads the return code of
/// a command that is not a stored procedure.</summary>
/// <returns>The exception.</returns>
public InvalidOperationException NotProcedure()
=> new(CaptureMessages.NotProcedure(ReturnReader!));

/// <summary>Refuses a call that reads the return code itself when a capture
/// reads it too: the capture is completed with the refusal.</summary>
/// <param name="cancellationToken">The token that governs the call.</param>
Expand Down Expand Up @@ -1027,18 +990,6 @@ public const string ToListInstead
public const string ExecuteNonQueryInstead
= "ExecuteNonQueryAsync instead of ExecuteNonQuery";

/// <summary>
/// Why a text command cannot give a return code, in the messages that
/// need a stored procedure.
/// </summary>
public const string NoReturnCodeInText
= "a text command has no return code, "
+ "and the provider would report 0. ";

/// <summary>The fix of a message that needs a stored procedure.</summary>
public const string CallByName
= "Call the procedure by name with StoredProcedure(…), ";

/// <summary>The last resort of a message about a capture.</summary>
public const string OrRemoveTheCapture
= "or remove the capture.";
Expand Down Expand Up @@ -1127,20 +1078,6 @@ public static string CancelOnEarlyStop(CaptureSet set)
+ "a canceled command does not give its output parameters. "
+ "Remove CancelOnEarlyStop(), or remove the capture.";

public static string NotProcedure(ICaptureSource source)
=> source.Kind == CaptureKind.Return
? $"{source.Display} needs a stored procedure: "
+ NoReturnCodeInText
+ CallByName
+ OrRemoveTheCapture
: $"{source.Display} reads the return code into the ReturnValue "
+ $"member of {source.Model}, "
+ "which needs a stored procedure: "
+ NoReturnCodeInText
+ CallByName
+ "or give the member [Column(\"name\")] to read an output "
+ "parameter instead.";

public static string NotDelivered(ICaptureSource source)
=> (source.Kind == CaptureKind.Return
? $"The return code of {source.Display} was never delivered"
Expand Down
28 changes: 28 additions & 0 deletions Source/Core/Compatibility/DictionaryTryAdd.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
#if NETSTANDARD2_0
namespace System.Collections.Generic;

// Polyfill for Dictionary<TKey, TValue>.TryAdd, which is in-box from
// netstandard2.1. On every other target framework this file is not compiled,
// so the in-box instance method is the one that is called.
internal static class DictionaryTryAddExtensions
{
/// <summary>
/// Adds the key and value if the key is not in the dictionary yet.
/// </summary>
/// <returns><see langword="true"/> if the pair was added; <see langword="false"/> if the key was already there, in which case the dictionary is unchanged.</returns>
public static bool TryAdd<TKey, TValue>(
this Dictionary<TKey, TValue> dictionary,
TKey key,
TValue value)
where TKey : notnull
{
if (dictionary.ContainsKey(key))
{
return false;
}

dictionary.Add(key, value);
return true;
}
}
#endif
4 changes: 0 additions & 4 deletions Source/Core/Core/RowMap.cs
Original file line number Diff line number Diff line change
Expand Up @@ -910,11 +910,7 @@ ValueMappingException OrderMismatch(Slot slot, string expected, string found)
if (filled[p] || _named[p] || _slots[p].ColumnName is not null || _slots[p].NotMapped) continue;

index ??= new(_columns.Length, new IgnoreCaseAndUnderscores());
#if NETSTANDARD2_0
if (!index.ContainsKey(name)) index.Add(name, p);
#else
index.TryAdd(name, p);
#endif
}

return index;
Expand Down
4 changes: 2 additions & 2 deletions Source/Core/DbNonQuery.cs
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ public DbNonQuery<TParams> Params<TParams>()
/// <typeparam name="TOut">The model the outputs are read into.</typeparam>
/// <returns>The definition, to be run with <c>ExecuteOutputAsync</c>.</returns>
/// <exception cref="InvalidOperationException">
/// <typeparamref name="TOut"/> has no member to read, is a single value, has a <see cref="decimal"/> member without its type name, or reads the return code of a text definition.
/// <typeparamref name="TOut"/> has no member to read, is a single value, or has a <see cref="decimal"/> member without its type name.
/// The message names the definition and the model.
/// </exception>
public OutputDbNonQuery<TOut> Output<TOut>()
Expand Down Expand Up @@ -248,7 +248,7 @@ public BoundParams<NonQueryKind, TParams> Using<TConnection>(
/// <typeparam name="TOut">The model the outputs are read into.</typeparam>
/// <returns>The definition, to be run with <c>ExecuteOutputAsync</c>.</returns>
/// <exception cref="InvalidOperationException">
/// <typeparamref name="TOut"/> has no member to read, is a single value, has a <see cref="decimal"/> member without its type name, or reads the return code of a text definition.
/// <typeparamref name="TOut"/> has no member to read, is a single value, or has a <see cref="decimal"/> member without its type name.
/// The message names the definition and the model.
/// </exception>
public OutputDbNonQuery<TParams, TOut> Output<TOut>()
Expand Down
4 changes: 2 additions & 2 deletions Source/Core/ExpressiveCommandBase.Capture.cs
Original file line number Diff line number Diff line change
Expand Up @@ -234,9 +234,9 @@ async ValueTask<TResult> ExecuteCapturedAsync<TState, TResult>(

// 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)
if (run.Set.ReadsReturn)
{
throw run.Set.NotProcedure();
ThrowIfNoReturnCode();
}

return await ExecutePlainAsync(
Expand Down
41 changes: 25 additions & 16 deletions Source/Core/ExpressiveCommandBase.Output.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,9 @@ public abstract partial class ExpressiveCommandBase<TConnection, TCommand, TRead
/// </para>
/// <include file="Output.docs.xml" path="docs/members[@name='out-null-input']/*" />
/// <para>
/// A member named <c>ReturnValue</c> reads a stored procedure's return code.
/// A member named <c>ReturnValue</c> reads the return code.
/// </para>
/// <include file="Output.docs.xml" path="docs/members[@name='return-text']/*" />
/// <include file="Output.docs.xml" path="docs/members[@name='out-return-name']/*" />
/// <include file="Output.docs.xml" path="docs/members[@name='out-decimal-column']/*" />
/// <para>
Expand All @@ -44,8 +45,8 @@ public abstract partial class ExpressiveCommandBase<TConnection, TCommand, TRead
/// <exception cref="InvalidOperationException">
/// <para>
/// Before anything runs: <typeparamref name="TOut"/> has no member to read, is a single value, has a <see cref="decimal"/> member without its type name or a member of a type
/// that has no database type, or reads the return code of a command that is not a stored procedure.
/// Before the command executes: a member matches no parameter, two match one, or the procedure declares a parameter a <c>ReturnValue</c> member would also match.
/// that has no database type.
/// Before the command executes: a member matches no parameter, two match one, or the procedure or text declares a parameter a <c>ReturnValue</c> member would also match.
/// </para>
/// <include file="Output.docs.xml" path="docs/members[@name='out-not-delivered']/*" />
/// <include file="Output.docs.xml" path="docs/members[@name='out-metadata']/*" />
Expand All @@ -59,9 +60,12 @@ public ValueTask<TOut> ExecuteOutputAsync<TOut>(
CancellationToken cancellationToken = default)
{
OutputLayout layout = OutputLayout<TOut>.Get();
if (layout.HasReturnValue) ThrowUnlessProcedure(layout);

RefuseBesideCaptures("ExecuteOutputAsync<{0}>()", layout.Model);
if (layout.HasReturnValue)
{
ThrowIfNoReturnCode();
}

// Thrown synchronously, not through the returned task.
CancellationToken.ThrowIfCancellationRequested();
Expand Down Expand Up @@ -336,23 +340,28 @@ static bool ReadsOutputs<TState>(TState state)
&& ((OutputRun)(object)state!).Layout.HasOutputParameter;

/// <summary>
/// Throws when a model reads the return code of a command that is not a stored procedure.
/// Throws when this command, run by its provider package, has no return code to read.
/// </summary>
/// <param name="layout">The model's layout.</param>
/// <exception cref="InvalidOperationException">The command is not a stored procedure.</exception>
void ThrowUnlessProcedure(OutputLayout layout)
/// <remarks>
/// Called before anything runs by each call that reads the return code. Does nothing here: the provider reports what ADO.NET reports for the command's type.
/// </remarks>
/// <exception cref="InvalidOperationException">The provider package refuses a return code on this command.</exception>
internal virtual void ThrowIfNoReturnCode()
{
if (Type == CommandType.StoredProcedure) return;
}

string display = OutputLayout.ReturnValue;
foreach (OutputMember member in layout.Members)
// A call that is not itself a capture's run: a capture on the command
// completes with the refusal, as it does for any refusal at the call.
void ThrowIfNoReturnCodeAtCall()
{
try
{
if (member.IsReturnValue) display = member.Display;
ThrowIfNoReturnCode();
}
catch (InvalidOperationException ex) when (_captures is { } captures)
{
throw captures.Refuse(ex);
}

throw new InvalidOperationException(
$"{display} reads a stored procedure's return code, but the command is not a stored procedure (it is {Type}), and a command of another type has no return code to read: the provider reports 0. "
+ "Set CommandType.StoredProcedure to call a procedure, or read an output parameter (declared @name OUTPUT in the text) into a member of another name.");
}

// The matching and the adding of the output parameters are one path for
Expand Down
11 changes: 7 additions & 4 deletions Source/Core/ExpressiveCommandBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1571,6 +1571,9 @@ void IExecuteCommandSync.Execute(Action<IDbCommand> action)
T IExecuteCommandSync.Execute<T>(Func<IDbCommand, T> transform)
=> Execute(transform);

void IExecuteCommandSync.ThrowIfNoReturnCode()
=> ThrowIfNoReturnCodeAtCall();

ValueTask IExecuteCommand.ExecuteAsync(Func<IDbCommand, ValueTask> handler)
=> ExecuteAsync(handler);

Expand Down Expand Up @@ -1984,6 +1987,7 @@ ValueTask<T> IExecuteReader.ExecuteReaderAsync<T>(Func<IDataReader, ValueTask<T>
// A capture of the return code and this would read it twice: refused,
// and the capture completed with the refusal.
_captures?.ThrowIfReturnBeside(cancellationToken);
ThrowIfNoReturnCodeAtCall();

// Thrown synchronously, not through the returned task:
// both tokens are checked before anything is linked (a capture on the
Expand Down Expand Up @@ -2023,10 +2027,9 @@ public ValueTask<T> ExecuteReturnAsync<T>(
{
// A model cannot hold the return code: thrown at the call, before anything runs.
ReturnCode<T>.ThrowUnlessScalar();
return ReturnAsync<T>(cancellationToken);
return ReturnAsync<T>(ExecuteReturnAsync(cancellationToken));
}

async ValueTask<T> ReturnAsync<T>(CancellationToken cancellationToken)
=> RowMap<T>.ConvertScalar(
await ExecuteReturnAsync(cancellationToken).ConfigureAwait(false));
static async ValueTask<T> ReturnAsync<T>(ValueTask<object?> run)
=> RowMap<T>.ConvertScalar(await run.ConfigureAwait(false));
}
24 changes: 21 additions & 3 deletions Source/Core/Extensions/DataRecord.cs
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,9 @@ static IEnumerable<object> EnumerateValuesFromOrdinalsCore(IDataRecord record, i
/// <returns>An enumerable of mappings, where each name is the column's actual name in the record.</returns>
/// <remarks>
/// Use <see cref="OrdinalMapping(IDataRecord, IEnumerable{string})"/> or <see cref="GetOrdinalMapping(IDataRecord, IEnumerable{string}, bool)"/> instead when a missing column should be an error.
/// <para>
/// A name that more than one column has gets the first of those columns, as <see cref="IDataRecord.GetOrdinal(string)"/> does. Alias the column in SQL to read another.
/// </para>
/// </remarks>
/// <exception cref="ArgumentNullException"><paramref name="record"/> or <paramref name="columnNames"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentException">A requested name is <see langword="null"/>, empty, or white space. It can be thrown when the result is enumerated rather than when this method is called.</exception>
Expand All @@ -260,20 +263,35 @@ public static IEnumerable<ColumnOrdinal> MatchingOrdinals(this IDataRecord recor
if (sort)
{
var requested = new HashSet<string>(requestedNames, StringComparer.OrdinalIgnoreCase);
// Return the actual columns, in record order, whose names were requested.
return actual.Where(m => requested.Contains(m.Name));
// Return the first actual column, in record order, of each requested name.
return FirstColumnOfEachRequestedName(actual, requested);
}
else
{
// Map actual columns case-insensitively so the requested order can be preserved.
// The first column of a name stays; a later column of the same name is skipped.
var actualColumns = new Dictionary<string, ColumnOrdinal>(StringComparer.OrdinalIgnoreCase);
foreach (ColumnOrdinal m in actual)
actualColumns[m.Name] = m;
actualColumns.TryAdd(m.Name, m);
return requestedNames
.Where(actualColumns.ContainsKey)
.Select(c => actualColumns[c]);
}

static IEnumerable<ColumnOrdinal> FirstColumnOfEachRequestedName(
IEnumerable<ColumnOrdinal> actual,
HashSet<string> requested)
{
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (ColumnOrdinal m in actual)
{
if (requested.Contains(m.Name) && seen.Add(m.Name))
{
yield return m;
}
}
}

static IEnumerable<string> ValidateColumnNames(IEnumerable<string> names)
{
foreach (string c in names)
Expand Down
5 changes: 1 addition & 4 deletions Source/Core/MappedQuery.Capture.cs
Original file line number Diff line number Diff line change
Expand Up @@ -60,15 +60,12 @@ public MappedQueryCore<T> WithCapture(ICaptureSource source)
EnsureCommand();
if (_call.IsBound)
{
// 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));
CaptureSet.WithOnQuery(_captures as CaptureSet, source));
}

if (_command is not ICaptureRunner runner)
Expand Down
Loading