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
81 changes: 81 additions & 0 deletions Source/Core/ExpressiveCommandBase.Output.cs
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ public abstract partial class ExpressiveCommandBase<TConnection, TCommand, TRead
/// 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.
/// </para>
/// <include file="Output.docs.xml" path="docs/members[@name='out-not-delivered']/*" />
/// <include file="Output.docs.xml" path="docs/members[@name='out-metadata']/*" />
/// </exception>
/// <exception cref="ValueMappingException">
/// <para>A value does not convert to its member, or is NULL and the member does not take it.</para>
Expand Down Expand Up @@ -116,6 +117,7 @@ static async (cmd, _, run) =>
/// Before the command executes: the names are known and none is <paramref name="name"/>.
/// </para>
/// <include file="Output.docs.xml" path="docs/members[@name='out-not-delivered']/*" />
/// <include file="Output.docs.xml" path="docs/members[@name='out-metadata']/*" />
/// </exception>
/// <exception cref="ValueMappingException">
/// <para>The value does not convert to <typeparamref name="T"/>, or is NULL and <typeparamref name="T"/> is a non-nullable value type.</para>
Expand Down Expand Up @@ -157,6 +159,7 @@ public ValueTask<T> ExecuteOutputAsync<T>(
/// Before the command executes: the names are known and none is <paramref name="name"/>.
/// </para>
/// <include file="Output.docs.xml" path="docs/members[@name='out-not-delivered']/*" />
/// <include file="Output.docs.xml" path="docs/members[@name='out-metadata']/*" />
/// </exception>
/// <exception cref="ValueMappingException">
/// <para>The value does not convert to <typeparamref name="T"/>, or is NULL and <typeparamref name="T"/> is <see cref="decimal"/>.</para>
Expand Down Expand Up @@ -243,6 +246,7 @@ static async ValueTask<decimal> NotNullAsync(string name, ValueTask<decimal?> va
/// Before the command executes: the names are known and none is <paramref name="name"/>.
/// </para>
/// <include file="Output.docs.xml" path="docs/members[@name='out-not-delivered']/*" />
/// <include file="Output.docs.xml" path="docs/members[@name='out-metadata']/*" />
/// </exception>
/// <exception cref="ValueMappingException">
/// <para>The value does not convert to a <see cref="decimal"/>.</para>
Expand Down Expand Up @@ -330,6 +334,16 @@ ValueTask<TResult> RunOutputAsync<TResult>(
? (OutputRun)(object)state!
: null;

/// <summary>
/// Gets whether a call also needs what the database says about the parameters of a procedure: it reads at least one output parameter, not only the return code.
/// </summary>
/// <typeparam name="TState">The type of the state of the run.</typeparam>
/// <param name="state">The state of the run.</param>
/// <returns><see langword="true"/> for a call that reads an output parameter.</returns>
static bool ReadsOutputs<TState>(TState state)
=> typeof(TState) == typeof(OutputRun)
&& ((OutputRun)(object)state!).Layout.HasOutputParameter;

/// <summary>
/// Throws when a model reads the return code of a command that is not a stored procedure.
/// </summary>
Expand Down Expand Up @@ -439,9 +453,76 @@ void ResolveOutputs(OutputRun run, NameSet? names)
}
}

// 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;
}

/// <summary>
/// Checks the output members against what the database says about the parameters they resolved to, when it said.
/// </summary>
/// <remarks>
/// Only the exact mode <c>IN</c> counts; a mode that is anything else, or missing, does not (the metadata has no third state, because "not known" and "not mode <c>IN</c>" never differ in what the call does). A scale is compared only when it is known.
/// </remarks>
/// <param name="layout">The call's members.</param>
/// <param name="resolved">The parameter each member resolved to; <see langword="null"/> for the return code.</param>
/// <param name="names">The procedure's set.</param>
/// <param name="where">The procedure, for the messages.</param>
/// <exception cref="InvalidOperationException">
/// A member reads a parameter whose mode is <c>IN</c>, or declares a <see cref="decimal"/> scale lower than the procedure's.
/// </exception>
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.");
}

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<string> real,
Expand Down
88 changes: 84 additions & 4 deletions Source/Core/ExpressiveCommandBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -912,6 +912,86 @@ await GetProcedureParameterNamesAsync(
cancellationToken)
.ConfigureAwait(false));

/// <summary>
/// Asynchronously finds the names as <see cref="ResolveDerivedNamesAsync"/>
/// does, and for a procedure also reads (once) its parameter metadata, which
/// a call with output parameters checks before it runs.
/// </summary>
/// <param name="connection">An open connection to run the lookups on.</param>
/// <include file="Mapped.docs.xml" path="docs/members[@name='token-call']/*" />
/// <returns>
/// The set of names, or <see langword="null"/> when they are not known.
/// </returns>
ValueTask<NameSet?> ResolveDerivedNamesAndMetadataAsync(
TConnection connection,
CancellationToken cancellationToken)
{
if (Type == CommandType.StoredProcedure)
{
ProcedureKey key = ProcedureKey(connection);
return ProcedureParameterNames.Find(NameCacheOwner, key) is { } kept
? NeedsMetadata(kept)
? NamesWithMetadataAsync(connection, kept, cancellationToken)
: new(kept)
: ReadNamesAndMetadataAsync(connection, key, cancellationToken);
}

return ResolveDerivedNamesAsync(connection, cancellationToken);
}

/// <summary>
/// Asynchronously finds the names for a call: with the parameter metadata
/// when the call reads an output parameter (see
/// <see cref="ResolveDerivedNamesAndMetadataAsync"/>), otherwise the names
/// only (see <see cref="ResolveDerivedNamesAsync"/>).
/// </summary>
/// <typeparam name="TState">The type of the state of the run.</typeparam>
/// <param name="connection">An open connection to run the lookups on.</param>
/// <param name="state">The state of the run.</param>
/// <include file="Mapped.docs.xml" path="docs/members[@name='token-call']/*" />
/// <returns>
/// The set of names, or <see langword="null"/> when they are not known.
/// </returns>
// Not async: the one await stays in the run, which gains no field.
ValueTask<NameSet?> ResolveRunNamesAsync<TState>(
TConnection connection,
TState state,
CancellationToken cancellationToken)
=> ReadsOutputs(state)
? ResolveDerivedNamesAndMetadataAsync(connection, cancellationToken)
: ResolveDerivedNamesAsync(connection, cancellationToken);

async ValueTask<NameSet?> ReadNamesAndMetadataAsync(
TConnection connection,
ProcedureKey key,
CancellationToken cancellationToken)
{
NameSet? names = await ReadNamesAsync(connection, key, cancellationToken)
.ConfigureAwait(false);

return names is not null && NeedsMetadata(names)
? await NamesWithMetadataAsync(connection, names, cancellationToken)
.ConfigureAwait(false)
: names;
}

// Only a procedure's own set (a text's markers never have metadata), with
// names, that has not been asked yet.
static bool NeedsMetadata(NameSet names)
=> names is { Home: not null, Names.Length: > 0, Metadata: null };

async ValueTask<NameSet?> NamesWithMetadataAsync(
TConnection connection,
NameSet names,
CancellationToken cancellationToken)
{
await ProcedureParameterMetadata.EnsureAsync(
connection, Command, names, cancellationToken)
.ConfigureAwait(false);

return names;
}

NameSet? WrittenNames()
{
if (_params is not { Count: > 0 } || Type != CommandType.Text || Command is not { Length: > 0 } text) return null;
Expand Down Expand Up @@ -1311,9 +1391,8 @@ async ValueTask<TResult> ExecutePlainAsync<TState, TResult>(
// No local outlives the await, so the state machine gains no field.
if (_hasDerivedParams || typeof(TState) == typeof(OutputRun))
{
names = await ResolveDerivedNamesAsync(
single,
cancellationToken)
names = await ResolveRunNamesAsync(
single, state, cancellationToken)
.ConfigureAwait(false);
built = PrepareDerived(single, names, output: OutputOf(state));
}
Expand Down Expand Up @@ -1351,7 +1430,8 @@ async ValueTask<TResult> ExecutePlainAsync<TState, TResult>(
{
if (_hasDerivedParams || typeof(TState) == typeof(OutputRun))
{
leaseNames = await ResolveDerivedNamesAsync(lease.Connection, cancellationToken)
leaseNames = await ResolveRunNamesAsync(
lease.Connection, state, cancellationToken)
.ConfigureAwait(false);
leaseBuilt = PrepareDerived(lease.Connection, leaseNames, output: OutputOf(state));
}
Expand Down
25 changes: 24 additions & 1 deletion Source/Core/NameSet.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,8 @@ sealed class NameSet
/// <param name="names">The names.</param>
/// <param name="home">Where a procedure's set is kept (see <see cref="Home"/>).</param>
/// <param name="key">What it is kept under.</param>
// Everything is set here, before the set is published, and never changes.
// The names are set here, before the set is published, and never change;
// the only field written afterwards is the metadata (once).
internal NameSet(ImmutableArray<string> names, WeakReference<ProcedureParameterNames.Entries>? home = null, ProcedureKey key = default)
{
Debug.Assert(!names.IsDefault, "A set is made from names, not from 'not known'.");
Expand Down Expand Up @@ -89,6 +90,28 @@ public int GetHashCode(string obj)
}
}

/// <summary>What the database says about each parameter; <see langword="null"/> when it was not asked.</summary>
// Written at most once, and only by a call with output parameters (see
// ProcedureParameterMetadata): a set that was never asked for them holds nothing
// more. It lives and dies with the set, so the cap on the sets
// (ProcedureParameterNames) bounds it too, and there is no timer.
ParameterMetadata? _metadata;

/// <summary>
/// Gets what the database says about each parameter: <see langword="null"/> when it was not asked, <see cref="ParameterMetadata.Unknown"/> when it was asked and nothing is known.
/// </summary>
public ParameterMetadata? Metadata
=> Volatile.Read(ref _metadata);

/// <summary>
/// Keeps what the database said about each parameter, unless another call has kept its answer first.
/// </summary>
/// <param name="metadata">The metadata, aligned with <see cref="Names"/>.</param>
// Two threads may both ask; the first answer stays, and the answers are
// the same.
public void KeepMetadata(ParameterMetadata metadata)
=> Interlocked.CompareExchange(ref _metadata, metadata, null);

/// <summary>The entries by name, without the <c>@</c> and ignoring case; built when first asked, never changed.</summary>
Dictionary<string, Entry>? _entries;

Expand Down
22 changes: 22 additions & 0 deletions Source/Core/Output.docs.xml
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,16 @@
</para>
</members>

<members name="out-metadata">
<para>
When the call runs, before the command executes, and the procedure's parameter metadata is available:
a member reads a parameter whose mode the database reports as <c>IN</c> (an input parameter), or a <see cref="decimal"/> member declares a scale lower than the procedure's parameter has (the value would be rounded).
A higher scale passes, and no precision is checked.
Without the metadata (the provider has no <c>ProcedureParameters</c> schema collection, or it was refused) the call runs and the provider's own error applies.
If the procedure was changed since it was first called, call again.
</para>
</members>

<members name="out-after-run">
<para>
It is thrown after the command has run, so its effects have happened.
Expand Down Expand Up @@ -159,6 +169,9 @@
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) (for a capture added to the command after the query was made, when the terminal or stream is called).
</exception>
<exception cref="InvalidOperationException">
<include file="Output.docs.xml" path="docs/members[@name='out-metadata']/*" />
</exception>
</members>

<members name="capture-named">
Expand All @@ -171,6 +184,9 @@
which needs its precision and scale (use the form that takes them);
or another capture reads the same parameter.
</exception>
<exception cref="InvalidOperationException">
<include file="Output.docs.xml" path="docs/members[@name='out-metadata']/*" />
</exception>
</members>

<members name="capture-shaped">
Expand All @@ -187,6 +203,9 @@
At the call: <typeparamref name="TValue"/> is not <see cref="decimal"/> or a <see cref="Nullable{T}"/> of it;
or another capture reads the same parameter.
</exception>
<exception cref="InvalidOperationException">
<include file="Output.docs.xml" path="docs/members[@name='out-metadata']/*" />
</exception>
</members>

<members name="capture-decimal">
Expand All @@ -199,6 +218,9 @@
<paramref name="precision"/> is 0 or more than 38, or <paramref name="scale"/> is more than <paramref name="precision"/>.
</exception>
<exception cref="InvalidOperationException">At the call: another capture reads the same parameter.</exception>
<exception cref="InvalidOperationException">
<include file="Output.docs.xml" path="docs/members[@name='out-metadata']/*" />
</exception>
</members>

<members name="capture-return">
Expand Down
6 changes: 6 additions & 0 deletions Source/Core/OutputLayout.cs
Original file line number Diff line number Diff line change
Expand Up @@ -278,7 +278,10 @@ public OutputLayout(string model, ImmutableArray<OutputMember> members, int[] ce
Cells = cells;
Labels = labels;
foreach (OutputMember member in members)
{
HasReturnValue |= member.IsReturnValue;
HasOutputParameter |= !member.IsReturnValue;
}
}

/// <summary>Initializes the layout of the named form: one value.</summary>
Expand All @@ -302,6 +305,9 @@ public OutputLayout(OutputMember member)

/// <summary>Whether a member reads the return code.</summary>
public readonly bool HasReturnValue;

/// <summary>Whether a member reads a parameter (not only the return code).</summary>
public readonly bool HasOutputParameter;
}

/// <summary>
Expand Down
Loading