From 0c6b3534db80526a145f867a910b6285264e3751 Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Wed, 2 Dec 2026 09:28:05 -0800 Subject: [PATCH 1/4] Check output parameters against the procedure's metadata before the run A call that reads output parameters now asks the database, once per procedure, whether each parameter is an input only and what its numeric scale is (the ADO.NET ProcedureParameters schema collection), and keeps the answer on the remembered name set. Two checks run in the build step, before the command executes: - a member (model member, named output, capture) on a parameter the procedure declares as input only throws InvalidOperationException, naming the member, the parameter, the procedure and the fix; - a decimal member whose declared scale (the [Column(TypeName)] attribute, or the precision and scale passed to a named or captured decimal form) is lower than the parameter's throws, because the value would be rounded. A higher scale passes, and no precision is checked. The metadata only checks: it never supplies a value, a type or a scale. It is optional and never fails a call: a provider without the collection, a connection that is not a DbConnection, a name that cannot be looked up and a table with nothing usable are kept as not known; any other failure of the read (for example a refusal inside a pending transaction) lets the call run, keeps nothing and is asked again on the next call; only a cancellation is thrown. Without metadata the provider's own error applies, as before. Calls without output parameters, calls that read only the return code, text commands and procedures whose names are not known never trigger the read. A failed check forgets the entry, so a changed procedure heals on the next call; an ALTER under a running process can cause one spurious failure, which the docs say. Existing tests that declared a lower scale, or an output on an input-only parameter, are converted to the new behaviour. Co-Authored-By: Claude Sonnet 5.5 --- Source/Core/ExpressiveCommandBase.Output.cs | 70 +++ Source/Core/ExpressiveCommandBase.cs | 52 +- Source/Core/NameSet.cs | 20 +- Source/Core/Output.docs.xml | 22 + Source/Core/OutputLayout.cs | 6 + Source/Core/ProcedureSchemaFacts.cs | 224 +++++++ Source/Core/ProcedureSchemaNames.cs | 2 +- .../OutputMetadataLocalDbTests.cs | 375 +++++++++++ .../OutputMetadataTests.cs | 588 ++++++++++++++++++ .../OutputParameterLocalDbTests.cs | 15 +- docsite/articles/expressive-commands.md | 5 +- docsite/articles/release-notes.md | 1 + 12 files changed, 1367 insertions(+), 13 deletions(-) create mode 100644 Source/Core/ProcedureSchemaFacts.cs create mode 100644 Tests/Open.Database.Extensions.Core.Tests/OutputMetadataLocalDbTests.cs create mode 100644 Tests/Open.Database.Extensions.Core.Tests/OutputMetadataTests.cs diff --git a/Source/Core/ExpressiveCommandBase.Output.cs b/Source/Core/ExpressiveCommandBase.Output.cs index fa7b5fae..23347bbd 100644 --- a/Source/Core/ExpressiveCommandBase.Output.cs +++ b/Source/Core/ExpressiveCommandBase.Output.cs @@ -57,6 +57,7 @@ public abstract partial class ExpressiveCommandBaseReturnValue member would also match. /// /// + /// /// /// /// A value does not convert to its member, or is NULL and the member does not take it. @@ -116,6 +117,7 @@ static async (cmd, _, run) => /// Before the command executes: the names are known and none is . /// /// + /// /// /// /// The value does not convert to , or is NULL and is a non-nullable value type. @@ -157,6 +159,7 @@ public ValueTask ExecuteOutputAsync( /// Before the command executes: the names are known and none is . /// /// + /// /// /// /// The value does not convert to , or is NULL and is . @@ -243,6 +246,7 @@ static async ValueTask NotNullAsync(string name, ValueTask va /// Before the command executes: the names are known and none is . /// /// + /// /// /// /// The value does not convert to a . @@ -330,6 +334,16 @@ ValueTask RunOutputAsync( ? (OutputRun)(object)state! : null; + /// + /// 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. + /// + /// The type of the state of the run. + /// The state of the run. + /// for a call that reads an output parameter. + static bool NeedsFacts(TState state) + => typeof(TState) == typeof(OutputRun) + && ((OutputRun)(object)state!).Layout.HasOutputParameter; + /// /// Throws when a model reads the return code of a command that is not a stored procedure. /// @@ -429,9 +443,65 @@ void ResolveOutputs(OutputRun run, NameSet? names) } } + // Only a procedure's own set holds facts (a text's markers never do), and only once they were read. + if (names is { Home: not null }) CheckMetadata(layout, resolved, names, where); + run.Names = resolved; } + /// + /// Checks the output members against what the database says about the parameters they resolved to, when it said. + /// + /// + /// Only the exact mode IN is an input only; a mode that is anything else, or missing, is not (the facts keep no third state, because "not known" and "not an input only" never differ in what the call does). A scale is compared only when it is known. + /// + /// The call's members. + /// The parameter each member resolved to; for the return code. + /// The procedure's set. + /// The procedure, for the messages. + /// + /// A member reads an input-only parameter, or declares a scale lower than the procedure's. + /// + static void CheckMetadata( + OutputLayout layout, + string?[] resolved, + NameSet names, + string where) + { + if (names.Facts is not { IsKnown: true } facts) 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 (facts.IsInputOnly(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 only, 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 = facts.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 + " (a higher scale is fine), or lower the parameter's scale in the procedure. If the procedure was changed since it was first called, call again."); + } + } + } + static InvalidOperationException NoOutputMatch( OutputMember member, ImmutableArray real, diff --git a/Source/Core/ExpressiveCommandBase.cs b/Source/Core/ExpressiveCommandBase.cs index f8386fa0..99697428 100644 --- a/Source/Core/ExpressiveCommandBase.cs +++ b/Source/Core/ExpressiveCommandBase.cs @@ -872,20 +872,26 @@ protected virtual ValueTask> GetProcedureParameterNamesAs /// the @name markers of the text. /// /// An open connection to run the lookup on. + /// + /// for a call with output parameters, which also reads (once) what the database says about each parameter of a procedure. + /// /// /// /// The set of names, or when they are not known. /// ValueTask ResolveDerivedNamesAsync( TConnection connection, + bool needsFacts, CancellationToken cancellationToken) { if (Type == CommandType.StoredProcedure) { ProcedureKey key = ProcedureKey(connection); return ProcedureParameterNames.Find(NameCacheOwner, key) is { } kept - ? new(kept) - : ReadNamesAsync(connection, key, cancellationToken); + ? needsFacts && WantsFacts(kept) + ? ReadFactsAsync(connection, kept, cancellationToken) + : new(kept) + : ReadNamesAsync(connection, key, needsFacts, cancellationToken); } // The @name markers found in the text. @@ -898,8 +904,10 @@ protected virtual ValueTask> GetProcedureParameterNamesAs async ValueTask ReadNamesAsync( TConnection connection, ProcedureKey key, + bool needsFacts, CancellationToken cancellationToken) - => ProcedureParameterNames.Remember( + { + NameSet names = ProcedureParameterNames.Remember( NameCacheOwner, key, await GetProcedureParameterNamesAsync( @@ -908,6 +916,38 @@ await GetProcedureParameterNamesAsync( cancellationToken) .ConfigureAwait(false)); + if (needsFacts && WantsFacts(names)) + { + await ProcedureSchemaFacts.EnsureAsync( + connection, + Command, + names, + cancellationToken) + .ConfigureAwait(false); + } + + return names; + } + + // Only a procedure's own set (a text's markers are never asked), with names, that has not been asked yet. + static bool WantsFacts(NameSet names) + => names is { Home: not null, Names.Length: > 0, Facts: null }; + + async ValueTask ReadFactsAsync( + TConnection connection, + NameSet names, + CancellationToken cancellationToken) + { + await ProcedureSchemaFacts.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; @@ -1309,6 +1349,7 @@ async ValueTask ExecutePlainAsync( { names = await ResolveDerivedNamesAsync( single, + NeedsFacts(state), cancellationToken) .ConfigureAwait(false); built = PrepareDerived(single, names, output: OutputOf(state)); @@ -1347,7 +1388,10 @@ async ValueTask ExecutePlainAsync( { if (_hasDerivedParams || typeof(TState) == typeof(OutputRun)) { - leaseNames = await ResolveDerivedNamesAsync(lease.Connection, cancellationToken) + leaseNames = await ResolveDerivedNamesAsync( + lease.Connection, + NeedsFacts(state), + cancellationToken) .ConfigureAwait(false); leaseBuilt = PrepareDerived(lease.Connection, leaseNames, output: OutputOf(state)); } diff --git a/Source/Core/NameSet.cs b/Source/Core/NameSet.cs index 26795a07..9fbc1fef 100644 --- a/Source/Core/NameSet.cs +++ b/Source/Core/NameSet.cs @@ -29,7 +29,7 @@ sealed class NameSet /// The names. /// Where a procedure's set is kept (see ). /// What it is kept under. - // 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 facts (once). internal NameSet(ImmutableArray names, WeakReference? home = null, ProcedureKey key = default) { Debug.Assert(!names.IsDefault, "A set is made from names, not from 'not known'."); @@ -86,6 +86,24 @@ public int GetHashCode(string obj) } } + /// What the database says about each parameter; when it was not asked. + // Written at most once, and only by a call with output parameters (see ProcedureSchemaFacts): 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. + ParameterFacts? _facts; + + /// + /// Gets what the database says about each parameter: when it was not asked, when it was asked and nothing is known. + /// + internal ParameterFacts? Facts => Volatile.Read(ref _facts); + + /// + /// Keeps what the database said about each parameter, unless another call has kept its answer first. + /// + /// The facts, aligned with . + // Two threads may both ask; the first answer stays, and the answers are the same. + internal void KeepFacts(ParameterFacts facts) + => Interlocked.CompareExchange(ref _facts, facts, null); + /// The entries by name, without the @ and ignoring case; built when first asked, never changed. Dictionary? _entries; diff --git a/Source/Core/Output.docs.xml b/Source/Core/Output.docs.xml index 9c57c81f..23abc077 100644 --- a/Source/Core/Output.docs.xml +++ b/Source/Core/Output.docs.xml @@ -121,6 +121,16 @@ + + + When the call runs, before the command executes, and the procedure's parameter metadata is available: + a member reads a parameter the database reports as an input only, or a 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 ProcedureParameters 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. + + + It is thrown after the command has run, so its effects have happened. @@ -152,6 +162,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). + + + @@ -165,6 +178,9 @@ which needs its precision and scale (use the form that takes them); or another capture reads the same parameter. + + + @@ -182,6 +198,9 @@ At the call: is not or a of it; or another capture reads the same parameter. + + + @@ -195,6 +214,9 @@ is 0 or more than 38, or is more than . At the call: another capture reads the same parameter. + + + diff --git a/Source/Core/OutputLayout.cs b/Source/Core/OutputLayout.cs index b5dfb68b..c28b9b95 100644 --- a/Source/Core/OutputLayout.cs +++ b/Source/Core/OutputLayout.cs @@ -278,7 +278,10 @@ public OutputLayout(string model, ImmutableArray members, int[] ce Cells = cells; Labels = labels; foreach (OutputMember member in members) + { HasReturnValue |= member.IsReturnValue; + HasOutputParameter |= !member.IsReturnValue; + } } /// Initializes the layout of the named form: one value. @@ -302,6 +305,9 @@ public OutputLayout(OutputMember member) /// Whether a member reads the return code. public readonly bool HasReturnValue; + + /// Whether a member reads a parameter (not only the return code). + public readonly bool HasOutputParameter; } /// diff --git a/Source/Core/ProcedureSchemaFacts.cs b/Source/Core/ProcedureSchemaFacts.cs new file mode 100644 index 00000000..4d518441 --- /dev/null +++ b/Source/Core/ProcedureSchemaFacts.cs @@ -0,0 +1,224 @@ +using System.Globalization; + +namespace Open.Database.Extensions; + +/// +/// What the database says about each parameter of a stored procedure that a +/// call with output parameters checks before it runs. +/// +/// +/// Immutable once built. A fact that the database did not report is "not +/// known", and a check never fails a call over a fact that is not known. +/// +sealed class ParameterFacts +{ + /// The scale of a parameter whose scale is not known. + public const int NoScale = -1; + + /// + /// What is kept when the lookup was made and nothing came of it (the + /// provider has no such collection, or reported nothing usable). + /// + // Compared by reference: a lookup that found nothing is never repeated. + public static readonly ParameterFacts Unknown = new([], []); + + readonly bool[] _inputOnly; + readonly int[] _scales; + + /// Initializes the facts, aligned with the names of a set. + /// Whether each parameter is an input only. + /// The scale of each parameter, or . + internal ParameterFacts(bool[] inputOnly, int[] scales) + { + _inputOnly = inputOnly; + _scales = scales; + } + + /// Gets whether anything is known. + public bool IsKnown => !ReferenceEquals(this, Unknown); + + /// Gets whether a parameter is an input only. + /// The place of the parameter in the set's names. + /// only when the database reports the mode IN. + public bool IsInputOnly(int index) => _inputOnly[index]; + + /// Gets the scale the database reports for a parameter. + /// The place of the parameter in the set's names. + /// The scale, or when it is not known. + public int Scale(int index) => _scales[index]; +} + +/// +/// Reads, for the parameters a stored procedure declares, whether each is an +/// input only and its numeric scale, from the ADO.NET schema collection +/// ProcedureParameters (see ). +/// +/// +/// Metadata is optional: a lookup never fails a call. Without the collection (or +/// a ) the answer is kept as not known; a lookup that +/// fails any other way is not kept, so the next call asks again; only a +/// cancellation is thrown. +/// +static class ProcedureSchemaFacts +{ + /// + /// The name of the ADO.NET schema collection. + /// + const string Collection = "ProcedureParameters"; + + /// + /// Reads the facts of a procedure's parameters into its set, unless the set + /// already holds them. + /// + /// + /// Two calls may both read; one answer is kept. + /// A cancellation is thrown; an exception raised while the token is + /// canceled that is not an is + /// thrown with the procedure's name added to + /// under the key Procedure. + /// + /// An open connection to run the lookup on. + /// The procedure name as given to the command. + /// The procedure's set; its names are not empty. + /// + /// A task that represents the asynchronous operation. + internal static async ValueTask EnsureAsync( + object connection, + string procedure, + NameSet names, + CancellationToken cancellationToken) + { + if (names.Facts is not null) return; + + if (connection is not DbConnection db + || ProcedureSchemaNames.Restrictions(procedure) is not { } restrictions) + { + names.KeepFacts(ParameterFacts.Unknown); + return; + } + + ParameterFacts facts; + try + { +#if NET10_0_OR_GREATER + DataTable table = await db + .GetSchemaAsync(Collection, restrictions, cancellationToken) + .ConfigureAwait(false); +#else + // DbConnection.GetSchemaAsync does not exist on the netstandard targets. + cancellationToken.ThrowIfCancellationRequested(); + DataTable table = db.GetSchema(Collection, restrictions); +#endif + facts = Read(table, restrictions[1] is not null, names); + } + catch (Exception ex) when (ex is NotSupportedException or NotImplementedException or ArgumentException + && !cancellationToken.IsCancellationRequested) + { + // Not while the call is canceled: a cancellation surfaced as one of these stores nothing. + facts = ParameterFacts.Unknown; + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + if (cancellationToken.IsCancellationRequested) + { + ex.Data["Procedure"] = procedure; + throw; + } + + // Any other failure (for example a refusal inside a pending + // transaction): the call runs without the facts and the next call asks. + return; + } + + names.KeepFacts(facts); + } + + /// + /// Works out the facts of the set's parameters from the schema table. + /// + /// + /// Rows are matched to the set's names by name, as the set finds a name + /// (ignoring case and a leading @; the first row of a name wins), never + /// by position. When no schema was given and the rows span more than one + /// schema, nothing is known. + /// + /// The schema table. + /// if the procedure name included a schema; otherwise, . + /// The procedure's set. + /// The facts; when the table tells nothing usable. + static ParameterFacts Read(DataTable? table, bool schemaGiven, NameSet names) + { + if (table is null) return ParameterFacts.Unknown; + + DataColumnCollection columns = table.Columns; + bool hasMode = columns.Contains("PARAMETER_MODE"); + bool hasScale = columns.Contains("NUMERIC_SCALE"); + if (!columns.Contains("PARAMETER_NAME") || !hasMode && !hasScale) return ParameterFacts.Unknown; + + bool hasOrdinal = columns.Contains("ORDINAL_POSITION"); + bool checkSchema = !schemaGiven && columns.Contains("SPECIFIC_SCHEMA"); + string? schema = null; + int count = names.Names.Length; + bool[] inputOnly = new bool[count]; + int[] scales = new int[count]; + bool[] seen = new bool[count]; + for (int i = 0; i < count; i++) scales[i] = ParameterFacts.NoScale; + bool any = false; + foreach (DataRow row in table.Rows) + { + if (checkSchema) + { + string current = row["SPECIFIC_SCHEMA"] as string ?? ""; + schema ??= current; + if (!string.Equals(schema, current, StringComparison.OrdinalIgnoreCase)) return ParameterFacts.Unknown; + } + + // The ordinal 0 row is the return value, never a declared parameter. + if (hasOrdinal && IsReturnRow(row["ORDINAL_POSITION"])) continue; + + if (row["PARAMETER_NAME"] is not string { Length: > 0 } name + || names.Find(name) is not { } entry + || seen[entry.Index]) + { + continue; + } + + seen[entry.Index] = true; + any = true; + // Only the exact mode IN is an input only; INOUT (an OUTPUT parameter on SQL Server), OUT, anything unexpected and a missing value are not. + inputOnly[entry.Index] = hasMode && row["PARAMETER_MODE"] is string mode && string.Equals(mode, "IN", StringComparison.Ordinal); + if (hasScale) scales[entry.Index] = ScaleOf(row["NUMERIC_SCALE"]); + } + + return any ? new ParameterFacts(inputOnly, scales) : ParameterFacts.Unknown; + } + + static bool IsReturnRow(object ordinal) + { + if (ordinal is DBNull) return false; + + try + { + return Convert.ToInt32(ordinal, CultureInfo.InvariantCulture) == 0; + } + catch (Exception ex) when (ex is FormatException or InvalidCastException or OverflowException) + { + return false; + } + } + + static int ScaleOf(object value) + { + if (value is DBNull) return ParameterFacts.NoScale; + + try + { + int scale = Convert.ToInt32(value, CultureInfo.InvariantCulture); + return scale < 0 ? ParameterFacts.NoScale : scale; + } + catch (Exception ex) when (ex is FormatException or InvalidCastException or OverflowException) + { + return ParameterFacts.NoScale; + } + } +} diff --git a/Source/Core/ProcedureSchemaNames.cs b/Source/Core/ProcedureSchemaNames.cs index c5b1c915..9ede27ad 100644 --- a/Source/Core/ProcedureSchemaNames.cs +++ b/Source/Core/ProcedureSchemaNames.cs @@ -98,7 +98,7 @@ internal static async ValueTask> GetAsync(DbConnection co /// /// The procedure name as given to the command. /// The restrictions; when the name is not looked up (a database part, or an empty or unclosed part). - static string?[]? Restrictions(string procedure) + internal static string?[]? Restrictions(string procedure) { List? parts = Split(procedure); if (parts is null || parts.Count > 2 || parts.Exists(static p => p.Length == 0)) return null; diff --git a/Tests/Open.Database.Extensions.Core.Tests/OutputMetadataLocalDbTests.cs b/Tests/Open.Database.Extensions.Core.Tests/OutputMetadataLocalDbTests.cs new file mode 100644 index 00000000..be798017 --- /dev/null +++ b/Tests/Open.Database.Extensions.Core.Tests/OutputMetadataLocalDbTests.cs @@ -0,0 +1,375 @@ +extern alias mssql; + +using Microsoft.Data.SqlClient; +using System.ComponentModel.DataAnnotations.Schema; +using System.Data.Common; +using Expressive = mssql::Open.Database.Extensions.ExpressiveSqlCommand; + +#nullable enable + +namespace Open.Database.Extensions.Tests; + +// What a call with output parameters checks before it runs, from the procedure's metadata (ProcedureParameters), against SQL Server: +// an output on an input-only parameter, and a decimal whose scale is lower than the procedure's. Skipped without LocalDB (see LocalDbFixture). +[ExcludeFromCodeCoverage] +[Collection("LocalDB DDL")] +public static class OutputMetadataLocalDbTests +{ + static CancellationToken Token => TestContext.Current.CancellationToken; + + public sealed record PostId(int Id); + + public sealed record Total2([property: Column(TypeName = "decimal(10,2)")] decimal Total); + + public sealed record Total3([property: Column(TypeName = "decimal(10,3)")] decimal Total); + + public sealed record Total4([property: Column(TypeName = "decimal(10,4)")] decimal Total); + + public sealed record Money2([property: Column(TypeName = "decimal(19,2)")] decimal Total); + + public sealed record Money4([property: Column(TypeName = "decimal(19,4)")] decimal Total); + + public sealed record Row(int N); + + static LocalDbFixture.Scratch Procedure(string parameters, string body) + => LocalDbFixture.CreateProcedureWithBody(parameters, "set nocount on; " + body, "ode_meta"); + + static async Task OpenAsync() + { + SqlConnection connection = LocalDbFixture.Create(); + await connection.OpenAsync(Token); + return connection; + } + + // A procedure that records every execution in a table, so "nothing ran" is a count of zero rows read on another connection. + static (LocalDbFixture.Scratch Table, LocalDbFixture.Scratch Procedure) Recording(string parameters, string body = "") + { + LocalDbFixture.Scratch table = LocalDbFixture.CreateTable("ode_meta_t"); + LocalDbFixture.Scratch procedure = Procedure(parameters, $"insert dbo.[{table.Name}] values (1); {body}"); + return (table, procedure); + } + + [Fact] + public static async Task AnInputOnlyParameter_ThrowsBeforeTheRun_ForAModelMember() + { + LocalDbFixture.SkipUnlessAvailable(); + (LocalDbFixture.Scratch table, LocalDbFixture.Scratch procedure) = Recording("@id int"); + using (table) + using (procedure) + { + await using SqlConnection connection = await OpenAsync(); + + var ex = await Assert.ThrowsAsync(async () => await connection.StoredProcedure("dbo." + procedure.Name).ExecuteOutputAsync(Token)); + + Assert.Contains("PostId.Id reads '@id' of dbo.", ex.Message); + Assert.Contains("reports that parameter as an input only, so the call would be refused", ex.Message); + Assert.Contains("Declare the parameter OUTPUT in the procedure, or remove the member", ex.Message); + Assert.Equal(0, LocalDbFixture.Count(table.Name)); + } + } + + [Fact] + public static async Task AnInputOnlyParameter_ThrowsBeforeTheRun_ForANamedOutputAndACapture() + { + LocalDbFixture.SkipUnlessAvailable(); + (LocalDbFixture.Scratch table, LocalDbFixture.Scratch procedure) = Recording("@id int", "select 1 as N;"); + using (table) + using (procedure) + { + await using SqlConnection connection = await OpenAsync(); + string name = "dbo." + procedure.Name; + + var named = await Assert.ThrowsAsync(async () => await connection.StoredProcedure(name).ExecuteOutputAsync("id", Token)); + Assert.Contains("The output parameter 'id' reads '@id'", named.Message); + Assert.Contains("an input only", named.Message); + + var captured = await Assert.ThrowsAsync(async () => await connection.StoredProcedure(name) + .CaptureOutput("id", out DbCapture id) + .Map() + .ToListAsync(Token)); + Assert.Contains("CaptureOutput(\"id\") reads '@id'", captured.Message); + Assert.Contains("Declare the parameter OUTPUT in the procedure", captured.Message); + + Assert.Equal(0, LocalDbFixture.Count(table.Name)); + } + } + + // A value given to an IN parameter makes the member an InputOutput: the server refuses that too, and so does the check. + [Fact] + public static async Task AnInputOutputMemberOnAnInputOnlyParameter_Throws() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = Procedure("@id int", "select 1;"); + await using SqlConnection connection = await OpenAsync(); + + var ex = await Assert.ThrowsAsync(async () => await connection + .StoredProcedure("dbo." + procedure.Name) + .AddParam("id", 5) + .ExecuteOutputAsync(Token)); + + Assert.Contains("an input only", ex.Message); + } + + // An OUTPUT parameter is reported as INOUT, and a procedure with a mix of the two checks each parameter by its own mode. + [Fact] + public static async Task AnOutputBesideAnInput_Passes() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = Procedure("@a int, @id int output", "set @id = @a + 1;"); + await using SqlConnection connection = await OpenAsync(); + + PostId result = await connection + .StoredProcedure("dbo." + procedure.Name) + .AddParam("a", 4) + .ExecuteOutputAsync(Token); + + Assert.Equal(5, result.Id); + } + + // A lower scale rounds silently, so it throws; the same or a higher one is lossless and passes (a rolling change: attribute first, ALTER later). + [Fact] + public static async Task ADecimalScaleLowerThanTheProcedures_ThrowsBeforeTheRun_AndHigherOrEqualPasses() + { + LocalDbFixture.SkipUnlessAvailable(); + (LocalDbFixture.Scratch table, LocalDbFixture.Scratch procedure) = Recording("@total decimal(10,3) output", "set @total = 1.234;"); + using (table) + using (procedure) + { + await using SqlConnection connection = await OpenAsync(); + string name = "dbo." + procedure.Name; + + var ex = await Assert.ThrowsAsync(async () => await connection.StoredProcedure(name).ExecuteOutputAsync(Token)); + Assert.Contains("Total2.Total has the scale 2, but '@total' of dbo.", ex.Message); + Assert.Contains("has the scale 3, so the value would be rounded to 2 decimal places", ex.Message); + Assert.Contains("Declare the member as [Column(TypeName = \"decimal(10,3)\")] or higher (a higher scale is fine)", ex.Message); + Assert.Equal(0, LocalDbFixture.Count(table.Name)); + + Assert.Equal(1.234m, (await connection.StoredProcedure(name).ExecuteOutputAsync(Token)).Total); + Assert.Equal(1.234m, (await connection.StoredProcedure(name).ExecuteOutputAsync(Token)).Total); + } + } + + [Fact] + public static async Task ADecimalScaleCheck_AlsoCoversTheNamedAndCapturedForms() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = Procedure("@total decimal(10,3) output", "select 1 as N; set @total = 1.234;"); + await using SqlConnection connection = await OpenAsync(); + string name = "dbo." + procedure.Name; + + var generic = await Assert.ThrowsAsync(async () => await connection.StoredProcedure(name).ExecuteOutputAsync("total", 10, 2, Token)); + Assert.Contains("The output parameter 'total' has the scale 2, but '@total' of dbo.", generic.Message); + Assert.Contains("Pass a scale of 3 or more (a higher scale is fine)", generic.Message); + + var compiled = await Assert.ThrowsAsync(async () => await connection.StoredProcedure(name).ExecuteOutputDecimalAsync("total", 10, 2, Token)); + Assert.Contains("has the scale 3", compiled.Message); + + var captured = await Assert.ThrowsAsync(async () => await connection.StoredProcedure(name) + .CaptureOutputDecimal("total", 10, 2, out DbCapture total) + .Map() + .ToListAsync(Token)); + Assert.Contains("Pass a scale of 3 or more", captured.Message); + + Assert.Equal(1.234m, await connection.StoredProcedure(name).ExecuteOutputAsync("total", 10, 3, Token)); + Assert.Equal(1.234m, await connection.StoredProcedure(name).ExecuteOutputDecimalAsync("total", 12, 4, Token)); + List rows = await connection.StoredProcedure(name) + .CaptureOutputDecimal("total", 10, 3, out DbCapture kept) + .Map() + .ToListAsync(Token); + Assert.Equal([1], rows.Select(static r => r.N)); + Assert.Equal(1.234m, await kept); + } + + // An int parameter reports the scale 0: no scale a decimal member declares is lower. A money parameter reports 4, so a decimal(19,2) + // over it would round silently and throws; the member that declares 4 passes. + [Fact] + public static async Task AnIntParameterNeverFailsTheScaleCheck_AndAMoneyParameterHasTheScaleFour() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch whole = Procedure("@total int output", "set @total = 12;"); + using LocalDbFixture.Scratch money = Procedure("@total money output", "set @total = 12.3456;"); + await using SqlConnection connection = await OpenAsync(); + + Assert.Equal(12m, (await connection.StoredProcedure("dbo." + whole.Name).ExecuteOutputAsync(Token)).Total); + + var ex = await Assert.ThrowsAsync(async () => await connection.StoredProcedure("dbo." + money.Name).ExecuteOutputAsync(Token)); + Assert.Contains("has the scale 2", ex.Message); + Assert.Contains("has the scale 4", ex.Message); + + Assert.Equal(12.3456m, (await connection.StoredProcedure("dbo." + money.Name).ExecuteOutputAsync(Token)).Total); + } + + // A float has no scale (NUMERIC_SCALE is NULL): not known, so nothing is compared and the call runs as it did. + [Fact] + public static async Task AParameterWithNoScale_IsNotChecked() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = Procedure("@total float output", "set @total = 12.5;"); + await using SqlConnection connection = await OpenAsync(); + + Assert.Equal(12.5m, (await connection.StoredProcedure("dbo." + procedure.Name).ExecuteOutputAsync(Token)).Total); + } + + // The failed check forgot the entry: after the procedure is changed the next call reads again and passes. One throw after a change is + // accepted (the entry still holds the old facts until a call fails). + [Fact] + public static async Task AFailedScaleCheck_HealsAfterTheProcedureIsAltered() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = Procedure("@total decimal(10,3) output", "set @total = 1.234;"); + await using SqlConnection connection = await OpenAsync(); + string name = "dbo." + procedure.Name; + + await Assert.ThrowsAsync(async () => await connection.StoredProcedure(name).ExecuteOutputAsync(Token)); + + LocalDbFixture.Execute($"alter procedure dbo.[{procedure.Name}] @total decimal(10,2) output as set @total = 1.23"); + Assert.Equal(1.23m, (await connection.StoredProcedure(name).ExecuteOutputAsync(Token)).Total); + } + + // Both directions of an ALTER under a running process: an output turned input-only is the provider's error (which forgets the + // entry); an input-only turned output is one throw, then the call passes. + [Fact] + public static async Task AnAlterUnderARunningProcess_OneFailureThenItHeals_InBothDirections() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = Procedure("@id int output", "set @id = 1;"); + await using SqlConnection connection = await OpenAsync(); + string name = "dbo." + procedure.Name; + Assert.Equal(1, (await connection.StoredProcedure(name).ExecuteOutputAsync(Token)).Id); + + LocalDbFixture.Execute($"alter procedure dbo.[{procedure.Name}] @id int as select 1"); + var provider = await Assert.ThrowsAsync(async () => await connection.StoredProcedure(name).ExecuteOutputAsync(Token)); + Assert.Equal(8162, provider.Number); + + // The failure forgot the entry: this call reads the new facts, and the check is the library's. + await Assert.ThrowsAsync(async () => await connection.StoredProcedure(name).ExecuteOutputAsync(Token)); + + LocalDbFixture.Execute($"alter procedure dbo.[{procedure.Name}] @id int output as set @id = 2"); + Assert.Equal(2, (await connection.StoredProcedure(name).ExecuteOutputAsync(Token)).Id); + } + + // The SQL Server package reads the names with its own query and the facts through Core's lookup. + [Fact] + public static async Task ASqlServerPackageCommand_IsCheckedToo() + { + LocalDbFixture.SkipUnlessAvailable(); + (LocalDbFixture.Scratch table, LocalDbFixture.Scratch procedure) = Recording("@id int"); + using (table) + using (procedure) + { + await using SqlConnection connection = await OpenAsync(); + + var ex = await Assert.ThrowsAsync(async () => await new Expressive(connection, CommandType.StoredProcedure, "dbo." + procedure.Name).ExecuteOutputAsync(Token)); + + Assert.Contains("an input only", ex.Message); + Assert.Equal(0, LocalDbFixture.Count(table.Name)); + } + } + + // Microsoft.Data.SqlClient answers the schema collection inside a pending transaction (System.Data.SqlClient refuses it, which the + // fake provider covers as a failed read): the check runs there too, and throws before the command executes. + [Fact] + public static async Task InAPendingTransaction_TheMetadataIsRead_AndTheCheckThrowsBeforeTheRun() + { + LocalDbFixture.SkipUnlessAvailable(); + (LocalDbFixture.Scratch table, LocalDbFixture.Scratch procedure) = Recording("@id int"); + using (table) + using (procedure) + { + await using SqlConnection connection = await OpenAsync(); + + await using (SqlTransaction transaction = connection.BeginTransaction()) + { + var ex = await Assert.ThrowsAsync(async () => await new Expressive(connection, transaction, CommandType.StoredProcedure, "dbo." + procedure.Name).ExecuteOutputAsync(Token)); + Assert.Contains("an input only", ex.Message); + await transaction.RollbackAsync(Token); + } + + Assert.Equal(0, LocalDbFixture.Count(table.Name)); + } + } + + // A provider that answers no metadata (the metadata read is refused as unsupported; the names come from the real connection): + // not known, so the provider's own error applies (SQL Server 8162), as before the check existed. A provider's error forgets the + // entry, so each failing call asks again; a call that works asks once, however many calls follow. + [Fact] + public static async Task WithoutMetadata_TheProvidersOwnErrorApplies_AndTheLookupIsNotRepeated() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch input = Procedure("@id int", "select 1;"); + using LocalDbFixture.Scratch output = Procedure("@id int output", "set @id = 3;"); + await using SqlConnection inner = await OpenAsync(); + var connection = new MetadataRefusedConnection(inner, new NotSupportedException("no metadata")); + + for (int i = 0; i < 3; i++) + { + var ex = await Assert.ThrowsAsync(async () => await new NamedCommand(connection, "dbo." + input.Name).ExecuteOutputAsync(Token)); + Assert.Equal(8162, ex.Number); + } + + Assert.Equal(3, connection.SchemaCalls); + + connection.SchemaCalls = 0; + for (int i = 0; i < 3; i++) + { + Assert.Equal(3, (await new NamedCommand(connection, "dbo." + output.Name).ExecuteOutputAsync(Token)).Id); + } + + Assert.Equal(1, connection.SchemaCalls); + } + + // A refusal that is not "no such collection" (here an InvalidOperationException, as inside a transaction) is not kept: the call runs + // without the facts, and each call asks again. + [Fact] + public static async Task AFailedMetadataRead_LetsTheCallRun_AndIsAskedAgainEveryCall() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = Procedure("@id int output", "set @id = 3;"); + await using SqlConnection inner = await OpenAsync(); + var connection = new MetadataRefusedConnection(inner, new InvalidOperationException("refused")); + + for (int i = 0; i < 3; i++) + { + Assert.Equal(3, (await new NamedCommand(connection, "dbo." + procedure.Name).ExecuteOutputAsync(Token)).Id); + } + + Assert.Equal(3, connection.SchemaCalls); + } + + // Every metadata read is refused with the given exception. + sealed class MetadataRefusedConnection(SqlConnection inner, Exception refusal) : DbConnection + { + public SqlConnection Inner => inner; + + public int SchemaCalls { get; set; } + + [AllowNull] + public override string ConnectionString { get => inner.ConnectionString; set { } } + public override string Database => inner.Database; + public override string DataSource => inner.DataSource; + public override string ServerVersion => inner.ServerVersion; + public override ConnectionState State => inner.State; + public override void ChangeDatabase(string databaseName) => inner.ChangeDatabase(databaseName); + public override void Open() { } + public override void Close() { } + protected override DbTransaction BeginDbTransaction(IsolationLevel isolationLevel) => throw new NotSupportedException(); + protected override DbCommand CreateDbCommand() => inner.CreateCommand(); + + public override DataTable GetSchema(string collectionName, string?[] restrictionValues) + { + SchemaCalls++; + throw refusal; + } + } + + // The names are read from the real connection, so the wrapper counts only the metadata reads. + sealed class NamedCommand(MetadataRefusedConnection connection, string procedure) + : ExpressiveDbCommand(connection, CommandType.StoredProcedure, procedure) + { + protected override ImmutableArray GetProcedureParameterNames(DbConnection connection, string procedure) + => ProcedureSchemaNames.Get(((MetadataRefusedConnection)connection).Inner, procedure); + + protected override ValueTask> GetProcedureParameterNamesAsync(DbConnection connection, string procedure, CancellationToken cancellationToken) + => ProcedureSchemaNames.GetAsync(((MetadataRefusedConnection)connection).Inner, procedure, cancellationToken); + } +} diff --git a/Tests/Open.Database.Extensions.Core.Tests/OutputMetadataTests.cs b/Tests/Open.Database.Extensions.Core.Tests/OutputMetadataTests.cs new file mode 100644 index 00000000..4b3536a5 --- /dev/null +++ b/Tests/Open.Database.Extensions.Core.Tests/OutputMetadataTests.cs @@ -0,0 +1,588 @@ +using Open.Database.Extensions.Benchmarks; +using System.ComponentModel.DataAnnotations.Schema; +using System.Data.Common; + +#nullable enable + +namespace Open.Database.Extensions.Tests; + +// What a call with output parameters does with the procedure's metadata, on a fake provider whose schema collection the test controls: +// when it is asked (only for a call that reads an output parameter of a procedure with known names), what is kept and what is not, +// how the rows are read, and that a failed read never fails a call. The same checks against SQL Server are in OutputMetadataLocalDbTests. +[ExcludeFromCodeCoverage] +public static class OutputMetadataTests +{ + static CancellationToken Token => TestContext.Current.CancellationToken; + + public sealed record Whole(int Total); + + public sealed record Scaled([property: Column(TypeName = "decimal(10,2)")] decimal Total); + + public sealed record Both(int Total, int Other); + + // ---- the provider ------------------------------------------------------------ + + sealed class MetaConnection : DbConnection + { + public DataTable? Table { get; set; } + + public Exception? Failure { get; set; } + + public int SchemaCalls { get; private set; } + + public int Executed { get; set; } + + [AllowNull] + public override string ConnectionString { get; set; } = "meta"; + public override string Database => "meta"; + public override string DataSource => "meta"; + public override string ServerVersion => "1.0"; + public override ConnectionState State => ConnectionState.Open; + public override void ChangeDatabase(string databaseName) { } + public override void Close() { } + public override void Open() { } + protected override DbTransaction BeginDbTransaction(IsolationLevel isolationLevel) => throw new NotSupportedException(); + protected override DbCommand CreateDbCommand() => new MetaCommand(this); + + public override DataTable GetSchema(string collectionName, string?[] restrictionValues) + { + SchemaCalls++; + if (Failure is not null) throw Failure; + return Table ?? throw new NotSupportedException(); + } + } + + sealed class MetaCommand(MetaConnection connection) : DbCommand + { + readonly BenchParameterCollection _parameters = []; + + [AllowNull] + public override string CommandText { get; set; } = ""; + public override int CommandTimeout { get; set; } + public override CommandType CommandType { get; set; } + public override bool DesignTimeVisible { get; set; } + public override UpdateRowSource UpdatedRowSource { get; set; } + protected override DbConnection? DbConnection { get => connection; set { } } + protected override DbParameterCollection DbParameterCollection => _parameters; + protected override DbTransaction? DbTransaction { get; set; } + public override void Cancel() { } + public override void Prepare() { } + public override object? ExecuteScalar() => throw new NotSupportedException(); + protected override DbParameter CreateDbParameter() => new MetaParameter(); + protected override DbDataReader ExecuteDbDataReader(CommandBehavior behavior) => throw new NotSupportedException(); + + public override int ExecuteNonQuery() + { + connection.Executed++; + foreach (DbParameter p in _parameters) + { + if (p.Direction != ParameterDirection.Input) p.Value = p.DbType == DbType.Decimal ? 1.5m : 1; + } + + return 1; + } + } + + sealed class MetaParameter : DbParameter + { + public override DbType DbType { get; set; } + public override ParameterDirection Direction { get; set; } = ParameterDirection.Input; + public override bool IsNullable { get; set; } + [AllowNull] + public override string ParameterName { get; set; } = ""; + public override int Size { get; set; } + public override byte Precision { get; set; } + public override byte Scale { get; set; } + [AllowNull] + public override string SourceColumn { get; set; } = ""; + public override bool SourceColumnNullMapping { get; set; } + public override object? Value { get; set; } + public override void ResetDbType() { } + } + + // Names from the call, so the connection counts only the metadata reads. + sealed class NamedCommand(DbConnection connection, string procedure, params string[] names) + : ExpressiveDbCommand(connection, CommandType.StoredProcedure, procedure) + { + protected override ImmutableArray GetProcedureParameterNames(DbConnection connection, string procedure) => [.. names]; + + protected override ValueTask> GetProcedureParameterNamesAsync(DbConnection connection, string procedure, CancellationToken cancellationToken) => new([.. names]); + } + + // The columns of the collection that matter. A row: schema, ordinal, mode, name, scale. + static DataTable Table(params (string Schema, int Ordinal, string? Mode, string Name, object? Scale)[] rows) + { + var table = new DataTable("ProcedureParameters"); + table.Columns.Add("SPECIFIC_SCHEMA", typeof(string)); + table.Columns.Add("ORDINAL_POSITION", typeof(int)); + table.Columns.Add("PARAMETER_MODE", typeof(string)); + table.Columns.Add("PARAMETER_NAME", typeof(string)); + table.Columns.Add("NUMERIC_SCALE", typeof(object)); + foreach ((string schema, int ordinal, string? mode, string name, object? scale) in rows) + { + table.Rows.Add(schema, ordinal, mode ?? (object)DBNull.Value, name, scale ?? DBNull.Value); + } + + return table; + } + + static DataTable One(string mode, object? scale = null, string name = "@total") + => Table(("dbo", 1, mode, name, scale)); + + static string Proc() => ParameterNameHarness.NewProcedure(); + + static MetaConnection With(DataTable? table, Exception? failure = null) + => new() { Table = table, Failure = failure }; + + static ValueTask Total(MetaConnection connection, string procedure, params string[] names) + => new NamedCommand(connection, procedure, names).ExecuteOutputAsync(Token); + + // ---- when the metadata is asked ---------------------------------------------- + + [Fact] + public static async Task AnInputOnlyParameter_ThrowsBeforeTheRun_ForgetsTheEntry_AndTheNextCallReadsAgain() + { + MetaConnection connection = With(One("IN")); + string procedure = Proc(); + + var ex = await Assert.ThrowsAsync(async () => await Total(connection, procedure, "@total")); + + Assert.Contains("Whole.Total reads '@total' of " + procedure, ex.Message); + Assert.Contains("reports that parameter as an input only, so the call would be refused", ex.Message); + Assert.Contains("Declare the parameter OUTPUT in the procedure, or remove the member. If the procedure was changed since it was first called, call again.", ex.Message); + Assert.Equal(0, connection.Executed); + Assert.Equal(1, connection.SchemaCalls); + + // The procedure was changed: the failed call forgot the entry, so this one reads again and passes. + connection.Table = One("INOUT"); + Assert.Equal(1, (await Total(connection, procedure, "@total")).Total); + Assert.Equal(2, connection.SchemaCalls); + Assert.Equal(1, connection.Executed); + } + + [Fact] + public static async Task TheMetadataIsReadOnce_ForAnyNumberOfCalls() + { + MetaConnection connection = With(One("INOUT")); + string procedure = Proc(); + + for (int i = 0; i < 5; i++) Assert.Equal(1, (await Total(connection, procedure, "@total")).Total); + + Assert.Equal(1, connection.SchemaCalls); + Assert.Equal(5, connection.Executed); + } + + [Theory] + [InlineData(3, true)] + [InlineData(4, true)] + [InlineData(2, false)] + [InlineData(1, false)] + [InlineData(0, false)] + public static async Task ADecimalScaleLowerThanTheProcedures_Throws_AndEqualOrHigherPasses(int procedureScale, bool throws) + { + MetaConnection connection = With(One("INOUT", procedureScale)); + var command = new NamedCommand(connection, Proc(), "@total"); + + if (!throws) + { + Assert.Equal(1.5m, (await command.ExecuteOutputAsync(Token)).Total); + return; + } + + var ex = await Assert.ThrowsAsync(async () => await command.ExecuteOutputAsync(Token)); + Assert.Contains($"Scaled.Total has the scale 2, but '@total' of ", ex.Message); + Assert.Contains($"has the scale {procedureScale}, so the value would be rounded to 2 decimal places", ex.Message); + Assert.Contains($"Declare the member as [Column(TypeName = \"decimal(10,{procedureScale})\")] or higher (a higher scale is fine), or lower the parameter's scale in the procedure.", ex.Message); + Assert.Equal(0, connection.Executed); + } + + [Fact] + public static async Task ANamedDecimal_IsCheckedLikeAModelMember() + { + MetaConnection connection = With(One("INOUT", 3)); + string procedure = Proc(); + + var generic = await Assert.ThrowsAsync(async () => await new NamedCommand(connection, procedure, "@total").ExecuteOutputAsync("total", 10, 2, Token)); + Assert.Contains("The output parameter 'total' has the scale 2, but '@total' of ", generic.Message); + Assert.Contains("Pass a scale of 3 or more (a higher scale is fine)", generic.Message); + + var compiled = await Assert.ThrowsAsync(async () => await new NamedCommand(connection, procedure, "@total").ExecuteOutputDecimalAsync("total", 10, 2, Token)); + Assert.Contains("has the scale 3", compiled.Message); + Assert.Equal(0, connection.Executed); + + Assert.Equal(1.5m, await new NamedCommand(connection, procedure, "@total").ExecuteOutputAsync("total", 10, 3, Token)); + Assert.Equal(1.5m, await new NamedCommand(connection, procedure, "@total").ExecuteOutputDecimalAsync("total", 12, 4, Token)); + } + + [Fact] + public static async Task ANamedOutput_OnAnInputOnlyParameter_Throws() + { + MetaConnection connection = With(One("IN")); + + var ex = await Assert.ThrowsAsync(async () => await new NamedCommand(connection, Proc(), "@total").ExecuteOutputAsync("total", Token)); + + Assert.Contains("The output parameter 'total' reads '@total'", ex.Message); + Assert.Contains("an input only", ex.Message); + } + + // A value given to the parameter makes the member an InputOutput: the check covers it. + [Fact] + public static async Task AnInputOutputMember_OnAnInputOnlyParameter_Throws() + { + MetaConnection connection = With(One("IN")); + + var ex = await Assert.ThrowsAsync(async () => await new NamedCommand(connection, Proc(), "@total").AddParam("total", 5).ExecuteOutputAsync(Token)); + + Assert.Contains("an input only", ex.Message); + Assert.Equal(0, connection.Executed); + } + + // Each member is checked against its own parameter, in the order of the procedure's declaration, not of the rows. + [Fact] + public static async Task EachMemberIsCheckedAgainstItsOwnParameter() + { + MetaConnection connection = With(Table( + ("dbo", 2, "IN", "@other", null), + ("dbo", 1, "INOUT", "@total", 0))); + + var ex = await Assert.ThrowsAsync(async () => await new NamedCommand(connection, Proc(), "@total", "@other").ExecuteOutputAsync(Token)); + + Assert.Contains("Both.Other reads '@other'", ex.Message); + } + + // ---- when it is not asked ---------------------------------------------------- + + [Fact] + public static async Task ACallWithoutOutputs_NeverAsks() + { + MetaConnection connection = With(One("IN")); + var command = new NamedCommand(connection, Proc(), "@total"); + + await command.AddParam("total", 5).ExecuteNonQueryAsync(Token); + + Assert.Equal(0, connection.SchemaCalls); + Assert.Equal(1, connection.Executed); + } + + [Fact] + public static async Task ACallThatReadsOnlyTheReturnCode_NeverAsks() + { + MetaConnection connection = With(One("IN")); + + int code = await new NamedCommand(connection, Proc(), "@total").AddParam("total", 5).ExecuteReturnAsync(Token); + + Assert.Equal(1, code); + Assert.Equal(0, connection.SchemaCalls); + } + + [Fact] + public static async Task ATextCommandsMarker_NeverAsks() + { + MetaConnection connection = With(One("IN")); + + Whole whole = await new ExpressiveDbCommand(connection, CommandType.Text, "exec dbo.p @total output").ExecuteOutputAsync(Token); + + Assert.Equal(1, whole.Total); + Assert.Equal(0, connection.SchemaCalls); + } + + // A provider that reports no names: nothing to match rows to, so only the names' own read is made. + [Fact] + public static async Task AProcedureWhoseNamesAreNotKnown_NeverAsks() + { + MetaConnection connection = With(null); + + Whole whole = await new ExpressiveDbCommand(connection, CommandType.StoredProcedure, Proc()).ExecuteOutputAsync(Token); + + Assert.Equal(1, whole.Total); + Assert.Equal(1, connection.SchemaCalls); + } + + // ---- metadata is optional: a failed read never fails a call --------------------- + + [Fact] + public static async Task AProviderWithoutTheCollection_IsKnownAsUnknown_AndNotAskedAgain() + { + MetaConnection connection = With(null); + string procedure = Proc(); + + for (int i = 0; i < 3; i++) Assert.Equal(1, (await Total(connection, procedure, "@total")).Total); + + Assert.Equal(1, connection.SchemaCalls); + Assert.Equal(3, connection.Executed); + } + + [Fact] + public static async Task AnArgumentException_IsTheSameAsNoCollection() + { + MetaConnection connection = With(One("IN"), new ArgumentException("no such collection")); + string procedure = Proc(); + + for (int i = 0; i < 3; i++) Assert.Equal(1, (await Total(connection, procedure, "@total")).Total); + + Assert.Equal(1, connection.SchemaCalls); + } + + // A refusal such as one inside a pending transaction: the call runs and nothing is kept, so every call asks (accepted cost). + [Fact] + public static async Task AnyOtherFailure_LetsTheCallRun_NothingIsKept_AndTheNextCallAsks() + { + MetaConnection connection = With(One("IN"), new InvalidOperationException("refused")); + string procedure = Proc(); + + for (int i = 0; i < 3; i++) Assert.Equal(1, (await Total(connection, procedure, "@total")).Total); + + Assert.Equal(3, connection.SchemaCalls); + Assert.Equal(3, connection.Executed); + + // The refusal is over: the next call asks, and the answer is checked. + connection.Failure = null; + await Assert.ThrowsAsync(async () => await Total(connection, procedure, "@total")); + Assert.Equal(4, connection.SchemaCalls); + Assert.Equal(3, connection.Executed); + } + + [Fact] + public static async Task ACancellation_IsThrown_NothingRuns_AndNothingIsKept() + { + MetaConnection connection = With(One("INOUT"), new OperationCanceledException()); + string procedure = Proc(); + + await Assert.ThrowsAnyAsync(async () => await Total(connection, procedure, "@total")); + Assert.Equal(0, connection.Executed); + + connection.Failure = null; + Assert.Equal(1, (await Total(connection, procedure, "@total")).Total); + Assert.Equal(2, connection.SchemaCalls); + } + + [Fact] + public static async Task ARefusedCall_ThatIsNotACancellation_WhileTheTokenIsCanceled_IsThrownWithTheProcedure() + { + using var source = new CancellationTokenSource(); + var connection = new CancelingConnection(source); + string procedure = Proc(); + + var ex = await Assert.ThrowsAsync(async () => await new NamedCommand(connection, procedure, "@total").ExecuteOutputAsync(source.Token)); + + Assert.Equal(procedure, ex.Data["Procedure"]); + Assert.Equal(0, connection.Executed); + } + + // Cancels the call's token while the metadata is read and fails the read with something that is not a cancellation. + sealed class CancelingConnection(CancellationTokenSource source) : DbConnection + { + readonly MetaConnection _inner = new(); + + public int Executed => _inner.Executed; + + [AllowNull] + public override string ConnectionString { get; set; } = "cancel"; + public override string Database => "cancel"; + public override string DataSource => "cancel"; + public override string ServerVersion => "1.0"; + public override ConnectionState State => ConnectionState.Open; + public override void ChangeDatabase(string databaseName) { } + public override void Close() { } + public override void Open() { } + protected override DbTransaction BeginDbTransaction(IsolationLevel isolationLevel) => throw new NotSupportedException(); + protected override DbCommand CreateDbCommand() => _inner.CreateCommand(); + + public override DataTable GetSchema(string collectionName, string?[] restrictionValues) + { + source.Cancel(); + throw new InvalidOperationException("failed while canceled"); + } + } + + // ---- one name in two schemas, and a name the lookup cannot restrict ------------- + + [Fact] + public static async Task TwoSchemasWithoutOneGiven_AreNotKnown_AndNoRowOfTheOtherThrows() + { + MetaConnection connection = With(Table( + ("dbo", 1, "INOUT", "@total", 2), + ("other", 1, "IN", "@total", 2))); + string procedure = "procedure_" + Guid.NewGuid().ToString("N"); + + for (int i = 0; i < 2; i++) Assert.Equal(1, (await Total(connection, procedure, "@total")).Total); + + Assert.Equal(1, connection.SchemaCalls); + } + + [Fact] + public static async Task ANameWithADatabasePart_IsNotAskedForRows_AndRunsWithoutThem() + { + MetaConnection connection = With(One("IN")); + + Assert.Equal(1, (await Total(connection, "other.dbo.p", "@total")).Total); + + Assert.Equal(0, connection.SchemaCalls); + } + + // ---- how the rows are read --------------------------------------------------------- + + static async Task Read(DataTable table, params string[] names) + { + var set = new NameSet([.. names]); + await ProcedureSchemaFacts.EnsureAsync(With(table), "dbo.p", set, Token); + return set.Facts!; + } + + [Fact] + public static async Task OnlyTheExactModeIN_IsInputOnly() + { + ParameterFacts facts = await Read( + Table( + ("dbo", 1, "IN", "@a", null), + ("dbo", 2, "INOUT", "@b", null), + ("dbo", 3, "OUT", "@c", null), + ("dbo", 4, "in", "@d", null), + ("dbo", 5, "IN ", "@e", null), + ("dbo", 6, null, "@f", null)), + "@a", "@b", "@c", "@d", "@e", "@f"); + + Assert.Equal("YNNNNN", string.Concat(Enumerable.Range(0, 6).Select(i => facts.IsInputOnly(i) ? 'Y' : 'N'))); + } + + [Fact] + public static async Task TheScale_IsTakenWhenItIsAWholeNumberAtLeastZero() + { + ParameterFacts facts = await Read( + Table( + ("dbo", 1, "IN", "@a", 4), + ("dbo", 2, "IN", "@b", null), + ("dbo", 3, "IN", "@c", -1), + ("dbo", 4, "IN", "@d", "not a number"), + ("dbo", 5, "IN", "@e", "3"), + ("dbo", 6, "IN", "@f", 0)), + "@a", "@b", "@c", "@d", "@e", "@f"); + + Assert.Equal(new[] { 4, ParameterFacts.NoScale, ParameterFacts.NoScale, ParameterFacts.NoScale, 3, 0 }, Enumerable.Range(0, 6).Select(facts.Scale)); + } + + // Rows are matched to names by name (ignoring case and a leading @), never by position; the first row of a name wins; the row of + // ordinal 0 is the return value and never a parameter. + [Fact] + public static async Task RowsAreMatchedByName_TheFirstRowWins_AndOrdinalZeroIsSkipped() + { + ParameterFacts facts = await Read( + Table( + ("dbo", 0, "IN", "@total", 9), + ("dbo", 2, "INOUT", "TOTAL", 5), + ("dbo", 1, "IN", "@Other", 1), + ("dbo", 3, "IN", "@total", 7), + ("dbo", 4, "IN", "@unknown", 3)), + "@other", "@total"); + + Assert.True(facts.IsInputOnly(0)); + Assert.Equal(1, facts.Scale(0)); + Assert.False(facts.IsInputOnly(1)); + Assert.Equal(5, facts.Scale(1)); + } + + [Fact] + public static async Task AParameterWithNoRow_IsNotInputOnlyAndHasNoScale() + { + ParameterFacts facts = await Read(One("IN"), "@total", "@missing"); + + Assert.True(facts.IsInputOnly(0)); + Assert.False(facts.IsInputOnly(1)); + Assert.Equal(ParameterFacts.NoScale, facts.Scale(1)); + } + + [Fact] + public static async Task AMissingScaleColumn_StillGivesTheMode_AndAMissingModeColumn_StillGivesTheScale() + { + DataTable noScale = One("IN"); + noScale.Columns.Remove("NUMERIC_SCALE"); + ParameterFacts mode = await Read(noScale, "@total"); + Assert.True(mode.IsKnown); + Assert.True(mode.IsInputOnly(0)); + Assert.Equal(ParameterFacts.NoScale, mode.Scale(0)); + + DataTable noMode = One("IN", 3); + noMode.Columns.Remove("PARAMETER_MODE"); + ParameterFacts scale = await Read(noMode, "@total"); + Assert.True(scale.IsKnown); + Assert.False(scale.IsInputOnly(0)); + Assert.Equal(3, scale.Scale(0)); + } + + [Fact] + public static async Task AMissingOrdinalColumn_MatchesByNameOnly() + { + DataTable table = One("IN", 2); + table.Columns.Remove("ORDINAL_POSITION"); + + ParameterFacts facts = await Read(table, "@total"); + + Assert.True(facts.IsInputOnly(0)); + } + + [Fact] + public static async Task NothingUsable_IsUnknown_AndKept() + { + DataTable noMode = One("IN", 3); + noMode.Columns.Remove("PARAMETER_MODE"); + noMode.Columns.Remove("NUMERIC_SCALE"); + DataTable noName = One("IN", 3); + noName.Columns.Remove("PARAMETER_NAME"); + + Assert.Same(ParameterFacts.Unknown, await Read(noMode, "@total")); + Assert.Same(ParameterFacts.Unknown, await Read(noName, "@total")); + Assert.Same(ParameterFacts.Unknown, await Read(Table(), "@total")); + Assert.Same(ParameterFacts.Unknown, await Read(One("IN", 3, "@somethingelse"), "@total")); + Assert.Same(ParameterFacts.Unknown, await Read(Table(("dbo", 0, "OUT", "@total", null)), "@total")); + } + + [Fact] + public static async Task ANameTheLookupCannotRestrict_IsUnknown_WithoutAskingTheProvider() + { + MetaConnection connection = With(One("IN")); + var set = new NameSet(["@total"]); + + await ProcedureSchemaFacts.EnsureAsync(connection, "db.dbo.p", set, Token); + + Assert.Same(ParameterFacts.Unknown, set.Facts); + Assert.Equal(0, connection.SchemaCalls); + } + + [Fact] + public static async Task AConnectionThatIsNotADbConnection_IsUnknown_AndKept() + { + var set = new NameSet(["@total"]); + + await ProcedureSchemaFacts.EnsureAsync(Substitute.For(), "dbo.p", set, Token); + + Assert.Same(ParameterFacts.Unknown, set.Facts); + } + + [Fact] + public static async Task TheFirstAnswerKept_IsTheOneThatStays() + { + var set = new NameSet(["@total"]); + await ProcedureSchemaFacts.EnsureAsync(With(One("IN")), "dbo.p", set, Token); + ParameterFacts first = set.Facts!; + + set.KeepFacts(ParameterFacts.Unknown); + await ProcedureSchemaFacts.EnsureAsync(With(One("INOUT")), "dbo.p", set, Token); + + Assert.Same(first, set.Facts); + Assert.True(first.IsInputOnly(0)); + } + + [Fact] + public static async Task TwoCallsThatBothAsk_KeepOneAnswer() + { + var set = new NameSet(["@total"]); + MetaConnection connection = With(One("IN")); + + await Task.WhenAll(Enumerable.Range(0, 16).Select(_ => Task.Run(async () => await ProcedureSchemaFacts.EnsureAsync(connection, "dbo.p", set, Token), Token))); + + ParameterFacts kept = set.Facts!; + await ProcedureSchemaFacts.EnsureAsync(connection, "dbo.p", set, Token); + Assert.Same(kept, set.Facts); + Assert.True(kept.IsInputOnly(0)); + } +} diff --git a/Tests/Open.Database.Extensions.Core.Tests/OutputParameterLocalDbTests.cs b/Tests/Open.Database.Extensions.Core.Tests/OutputParameterLocalDbTests.cs index 93304e9b..a3b6c674 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/OutputParameterLocalDbTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/OutputParameterLocalDbTests.cs @@ -101,7 +101,7 @@ public static async Task ADecimal_TakesItsTypeName_OutputAndInputOutput() { LocalDbFixture.SkipUnlessAvailable(); using LocalDbFixture.Scratch procedure = Procedure( - "@total decimal(10,2) output, @echo decimal(10,3) output", + "@total decimal(10,2) output, @echo decimal(10,2) output", "set @total = 1234.56;"); await using SqlConnection connection = await OpenAsync(); @@ -191,18 +191,21 @@ public static async Task ALaterStatementsError_IsTheProvidersError() Assert.Equal(245, ex.Number); } - // An output member on an input-only parameter is the provider's error (8162, P14e), and the kept names are forgotten: - // the next call reads them again and finds the renamed parameter. + // An output member on an input-only parameter throws before the run (the procedure's mode is known), and the kept names are + // forgotten: after the procedure is changed the next call reads them again and finds the renamed parameter. The provider's own + // error (8162) for unknown metadata is in OutputMetadataLocalDbTests. [Fact] - public static async Task AnOutputOnAnInputOnlyParameter_IsTheProvidersError_AndTheNamesAreForgotten() + public static async Task AnOutputOnAnInputOnlyParameter_ThrowsBeforeTheRun_AndTheNamesAreForgotten() { LocalDbFixture.SkipUnlessAvailable(); using LocalDbFixture.Scratch procedure = Procedure("@post_id int", "select 1;"); await using SqlConnection connection = await OpenAsync(); string name = "dbo." + procedure.Name; - var ex = await Assert.ThrowsAsync(async () => await connection.StoredProcedure(name).ExecuteOutputAsync(Token)); - Assert.Equal(8162, ex.Number); + var ex = await Assert.ThrowsAsync(async () => await connection.StoredProcedure(name).ExecuteOutputAsync(Token)); + Assert.Contains("NewPostId.PostId reads '@post_id' of dbo.", ex.Message); + Assert.Contains("an input only", ex.Message); + Assert.Contains("Declare the parameter OUTPUT in the procedure, or remove the member", ex.Message); LocalDbFixture.Execute($"alter procedure dbo.[{procedure.Name}] @p_post_id int output as set @p_post_id = 5"); Assert.Equal(5, (await connection.StoredProcedure(name).ExecuteOutputAsync(Token)).PostId); diff --git a/docsite/articles/expressive-commands.md b/docsite/articles/expressive-commands.md index 57659880..a7e20bb7 100644 --- a/docsite/articles/expressive-commands.md +++ b/docsite/articles/expressive-commands.md @@ -211,6 +211,7 @@ A result set and the return value are readable on the chain; output parameters a - **Types.** A `DateTime` is sent as `datetime2`, a `DateOnly` as `date` and a `TimeOnly` as `time` (nullable forms too; a `TimeOnly` keeps all seven fraction digits); a `string` or `byte[]` with size -1, so the whole value comes back; a `char` with size 1, so it reads one character (a `char(3)` holding `XYZ` reads `X`: use a `string` for more). A `decimal` needs `[Column(TypeName = "decimal(10,2)")]` (positional records: `[property: Column(...)]`); without it the call throws before it runs. - **One value.** `ExecuteOutputAsync("name")` reads one parameter, named exactly (with or without `@`, any case); `"ReturnValue"` there names a declared parameter, not the return code. A `decimal` needs its precision and scale: `ExecuteOutputAsync("total", 19, 4)` for a `decimal(19,4)` (`decimal?` for NULL), or `ExecuteOutputDecimalAsync("total", 19, 4)`, which returns a `decimal?`. Without them `ExecuteOutputAsync(name)` throws before it runs, and only a `decimal` takes them. - **Not delivered.** An Output parameter still empty after the call means the response never completed: the call throws `InvalidOperationException`, never a NULL. +- **Checked before the run.** When the procedure's parameter metadata is available (SQL Server, and any provider whose ADO.NET `ProcedureParameters` schema collection answers), a member on a parameter the procedure declares as input only, and a `decimal` member whose scale is lower than the parameter's, throw `InvalidOperationException` before the command runs, naming the member, the parameter and the fix. A higher scale passes, and no precision is checked. The metadata only checks: it never supplies a value, a type or a scale. It is read once per procedure, only for a call that reads an output parameter. Without it the call runs and the provider's own error applies: for an output on an input-only parameter on SQL Server, 8162. One value, and a decimal with its precision and scale: @@ -224,7 +225,9 @@ There is no blocking form. Known limits: - The declared scale of a `decimal` also rounds a value sent in (`1.239` sent as `decimal(10,2)` arrives as `1.24`). - An InputOutput parameter whose outputs never arrive keeps the value sent: that case cannot be told from a real answer. - A parameter added with a null value (`AddParam(name, (int?)null, type)`) that is also an output member is sent as InputOutput too, so a lost output cannot be told from a NULL. For a pure output, add no value; add one only when the procedure reads it. -- A member on a parameter the procedure does not declare `OUTPUT` is the provider's error (SQL Server: 8162), and SQLite refuses every output direction with its own `ArgumentException`. +- A member on a parameter the procedure does not declare `OUTPUT` throws before the run when the metadata is known, and is the provider's error when it is not (SQL Server: 8162); SQLite refuses every output direction with its own `ArgumentException`. +- If the procedure was changed with `ALTER` while the process runs, the remembered metadata is out of date until a call fails. An input-only parameter made an output gives one `InvalidOperationException`, and the next call passes; an output made input-only reaches the provider's error, and the call after it is checked. If the procedure was changed, call again. A lower scale made by the change rounds silently until a call fails or the process restarts. +- A read of the metadata that the provider refuses (on the Core package inside a pending transaction, for example) lets the call run, and is read again on every call. A call that keeps failing a check removes the remembered metadata for every caller of that procedure, so their next call reads it again. - SqlClient reports an error after the outputs are set, and a cancel while the command runs, with its own `SqlException`. - **A legacy `datetime` output can differ from a row in the last digits.** Outputs are sent as `datetime2`, so a `datetime` that stores `.997` (ticks of 1/300 second) reads back into a `DateTime` as `.9966667`, where a row read of the same value gives `.997`. `smalldatetime` and `datetime2` arrive exactly. To get what a row read gives, pass the value through `new SqlDateTime(value).Value` (from `System.Data.SqlTypes`), or have the procedure declare the output as `datetime2(3)`. Feeding such a value back in as an input lands on the same stored tick. - Output models use the runtime map, not a generated reader. diff --git a/docsite/articles/release-notes.md b/docsite/articles/release-notes.md index 22560526..a94113ab 100644 --- a/docsite/articles/release-notes.md +++ b/docsite/articles/release-notes.md @@ -7,6 +7,7 @@ Version 11 is `11.0.0-rc.16`. For moving a 10.x codebase, read [Coming from earl ### Changes since rc.16 - **Generated row readers for `DbQuery` too.** A plain `Map()` on a `DbQuery`, a `DbQuery` or a query bound with `Using` now gets its row reader written at build time, as on a command or a reader; before, it used the runtime map. The runtime map's conversions are therefore no longer applied there: see [Generated readers](mapping.md#generated-readers) for the differences and the switch. +- **New: output parameters are checked against the procedure's metadata before the run.** When the database reports a procedure's parameters (the ADO.NET `ProcedureParameters` schema collection, which SQL Server answers), a call that reads output parameters throws `InvalidOperationException` before the command runs if a member reads a parameter the procedure declares as input only, or if a `decimal` member declares a scale lower than the parameter's (the value would be rounded); a higher scale passes, and no precision is checked. The metadata is read once per procedure, only for such a call, and only checks: it never fills a value, a type or a scale. Without it the call runs as before and the provider's own error applies (SQL Server: 8162 for an output on an input-only parameter). See [Output parameters](expressive-commands.md#output-parameters). - **Fixed: a cancel during `AsAsyncEnumerable(pool)`.** On a `DbDataReader`, `AsAsyncEnumerable(arrayPool)` with a pool (the form that reads every column) did not pass its token to `ReadAsync`, so a read the provider cancelled threw out of the enumeration. It now ends the enumeration quietly with the rows already yielded, as the other forms do. - **Fixed: `CreateCommand` on a `SqlTransaction` that has no connection throws `InvalidOperationException`.** The SQL Server package threw `ArgumentNullException` named `connection`; it now reports "Transaction has no connection.", as the core package does. `CreateTextCommand` and `CreateStoredProcedureCommand` follow. - **Removed: parameter directions on the fluent chain.** `AddParam` and `AddParamIf` no longer take a `ParameterDirection`; `AddReturnParam` is gone, and `AddParam(name, direction)`, `AddParamIf(condition, name, direction)`, `AddParam(name, type)` and `AddParamIf(condition, name, type)` are now compile errors that say what to do instead. The forms that took a direction after the value, `AddParam(name, value, ParameterDirection)` and `AddParam(name, value, type, direction)` (the SQL Server forms with a database type and a direction too), fail to compile with the compiler's own argument error, without a message of their own: use the raw `AddParameter` inside `ExecuteAsync(command => ...)`, or read the output with `ExecuteOutputAsync`. A parameter on the chain is an input. To set a direction, use `ExecuteAsync(command => ...)` with the raw `AddParameter`, `AddParameterType` and `AddReturnParameter` extensions. Calls that never passed a direction compile unchanged, with one exception: a constant zero of type `byte` on the SQL Server command, `AddParam(name, (byte)0)`, used to bind silently to the direction overload and is now an ambiguous-call error (CS0121); pass a variable, or give the database type, `AddParam(name, value, SqlDbType.TinyInt)`. `Param` has no `direction` constructor parameter and no `Direction` property. From c2e807d043c6eba3429961a1f3c4e0afeef2490d Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Wed, 2 Dec 2026 10:04:17 -0800 Subject: [PATCH 2/4] Output metadata checks: cover the pooled call, wrap long lines, fix a doc sentence - Add a test for the call that takes its connection from a pool: the input-only check throws before the run, the metadata is read once, and a failed check forgets the entry. It fails when that call site does not ask for the metadata. - Group the argument and parameter lists logically, wrap the added lines that were over 80 columns, and make the members of the internal types public. - Reword the documentation of a refused metadata read: System.Data.SqlClient refuses the schema collection inside a pending transaction, while Microsoft.Data.SqlClient answers it. Co-Authored-By: Claude Sonnet 5.5 --- Source/Core/ExpressiveCommandBase.Output.cs | 34 +++++--- Source/Core/ExpressiveCommandBase.cs | 22 ++--- Source/Core/NameSet.cs | 16 ++-- Source/Core/ProcedureSchemaFacts.cs | 84 ++++++++++++------- Source/Core/ProcedureSchemaNames.cs | 2 +- .../OutputMetadataTests.cs | 42 ++++++++++ docsite/articles/expressive-commands.md | 2 +- 7 files changed, 137 insertions(+), 65 deletions(-) diff --git a/Source/Core/ExpressiveCommandBase.Output.cs b/Source/Core/ExpressiveCommandBase.Output.cs index 23347bbd..f4e99af4 100644 --- a/Source/Core/ExpressiveCommandBase.Output.cs +++ b/Source/Core/ExpressiveCommandBase.Output.cs @@ -443,8 +443,12 @@ void ResolveOutputs(OutputRun run, NameSet? names) } } - // Only a procedure's own set holds facts (a text's markers never do), and only once they were read. - if (names is { Home: not null }) CheckMetadata(layout, resolved, names, where); + // Only a procedure's own set holds facts (a text's markers never do), + // and only once they were read. + if (names is { Home: not null }) + { + CheckMetadata(layout, resolved, names, where); + } run.Names = resolved; } @@ -463,10 +467,8 @@ void ResolveOutputs(OutputRun run, NameSet? names) /// A member reads an input-only parameter, or declares a scale lower than the procedure's. /// static void CheckMetadata( - OutputLayout layout, - string?[] resolved, - NameSet names, - string where) + OutputLayout layout, string?[] resolved, + NameSet names, string where) { if (names.Facts is not { IsKnown: true } facts) return; @@ -483,8 +485,12 @@ static void CheckMetadata( if (facts.IsInputOnly(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 only, 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."); + $"{member.Display} reads '{entry.Real}' of {where} as an " + + "output parameter, but the database reports that " + + "parameter as an input only, 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 = facts.Scale(entry.Index); @@ -493,11 +499,17 @@ static void CheckMetadata( { string fix = member.Named ? $"Pass a scale of {declared} or more" - : $"Declare the member as [Column(TypeName = \"decimal({wire.Precision},{declared})\")] or higher"; + : "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 + " (a higher scale is fine), or lower the parameter's scale in the procedure. If the procedure was changed since it was first called, call again."); + $"{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} (a higher scale " + + "is fine), or lower the parameter's scale in the " + + "procedure. If the procedure was changed since it " + + "was first called, call again."); } } } diff --git a/Source/Core/ExpressiveCommandBase.cs b/Source/Core/ExpressiveCommandBase.cs index 99697428..a3def4e6 100644 --- a/Source/Core/ExpressiveCommandBase.cs +++ b/Source/Core/ExpressiveCommandBase.cs @@ -891,7 +891,8 @@ protected virtual ValueTask> GetProcedureParameterNamesAs ? needsFacts && WantsFacts(kept) ? ReadFactsAsync(connection, kept, cancellationToken) : new(kept) - : ReadNamesAsync(connection, key, needsFacts, cancellationToken); + : ReadNamesAsync( + connection, key, needsFacts, cancellationToken); } // The @name markers found in the text. @@ -902,10 +903,8 @@ protected virtual ValueTask> GetProcedureParameterNamesAs } async ValueTask ReadNamesAsync( - TConnection connection, - ProcedureKey key, - bool needsFacts, - CancellationToken cancellationToken) + TConnection connection, ProcedureKey key, + bool needsFacts, CancellationToken cancellationToken) { NameSet names = ProcedureParameterNames.Remember( NameCacheOwner, @@ -919,17 +918,15 @@ await GetProcedureParameterNamesAsync( if (needsFacts && WantsFacts(names)) { await ProcedureSchemaFacts.EnsureAsync( - connection, - Command, - names, - cancellationToken) + connection, Command, names, cancellationToken) .ConfigureAwait(false); } return names; } - // Only a procedure's own set (a text's markers are never asked), with names, that has not been asked yet. + // Only a procedure's own set (a text's markers are never asked), with + // names, that has not been asked yet. static bool WantsFacts(NameSet names) => names is { Home: not null, Names.Length: > 0, Facts: null }; @@ -939,10 +936,7 @@ static bool WantsFacts(NameSet names) CancellationToken cancellationToken) { await ProcedureSchemaFacts.EnsureAsync( - connection, - Command, - names, - cancellationToken) + connection, Command, names, cancellationToken) .ConfigureAwait(false); return names; diff --git a/Source/Core/NameSet.cs b/Source/Core/NameSet.cs index 9fbc1fef..c63f7ebb 100644 --- a/Source/Core/NameSet.cs +++ b/Source/Core/NameSet.cs @@ -29,7 +29,8 @@ sealed class NameSet /// The names. /// Where a procedure's set is kept (see ). /// What it is kept under. - // The names are set here, before the set is published, and never change; the only field written afterwards is the facts (once). + // The names are set here, before the set is published, and never change; + // the only field written afterwards is the facts (once). internal NameSet(ImmutableArray names, WeakReference? home = null, ProcedureKey key = default) { Debug.Assert(!names.IsDefault, "A set is made from names, not from 'not known'."); @@ -87,21 +88,24 @@ public int GetHashCode(string obj) } /// What the database says about each parameter; when it was not asked. - // Written at most once, and only by a call with output parameters (see ProcedureSchemaFacts): 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. + // Written at most once, and only by a call with output parameters (see + // ProcedureSchemaFacts): 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. ParameterFacts? _facts; /// /// Gets what the database says about each parameter: when it was not asked, when it was asked and nothing is known. /// - internal ParameterFacts? Facts => Volatile.Read(ref _facts); + public ParameterFacts? Facts => Volatile.Read(ref _facts); /// /// Keeps what the database said about each parameter, unless another call has kept its answer first. /// /// The facts, aligned with . - // Two threads may both ask; the first answer stays, and the answers are the same. - internal void KeepFacts(ParameterFacts facts) + // Two threads may both ask; the first answer stays, and the answers are + // the same. + public void KeepFacts(ParameterFacts facts) => Interlocked.CompareExchange(ref _facts, facts, null); /// The entries by name, without the @ and ignoring case; built when first asked, never changed. diff --git a/Source/Core/ProcedureSchemaFacts.cs b/Source/Core/ProcedureSchemaFacts.cs index 4d518441..428389f6 100644 --- a/Source/Core/ProcedureSchemaFacts.cs +++ b/Source/Core/ProcedureSchemaFacts.cs @@ -10,7 +10,9 @@ namespace Open.Database.Extensions; /// Immutable once built. A fact that the database did not report is "not /// known", and a check never fails a call over a fact that is not known. /// -sealed class ParameterFacts +/// Whether each parameter is an input only, aligned with the names of a set. +/// The scale of each parameter, or . +sealed class ParameterFacts(bool[] inputOnly, int[] scales) { /// The scale of a parameter whose scale is not known. public const int NoScale = -1; @@ -22,17 +24,8 @@ sealed class ParameterFacts // Compared by reference: a lookup that found nothing is never repeated. public static readonly ParameterFacts Unknown = new([], []); - readonly bool[] _inputOnly; - readonly int[] _scales; - - /// Initializes the facts, aligned with the names of a set. - /// Whether each parameter is an input only. - /// The scale of each parameter, or . - internal ParameterFacts(bool[] inputOnly, int[] scales) - { - _inputOnly = inputOnly; - _scales = scales; - } + readonly bool[] _inputOnly = inputOnly; + readonly int[] _scales = scales; /// Gets whether anything is known. public bool IsKnown => !ReferenceEquals(this, Unknown); @@ -82,16 +75,14 @@ static class ProcedureSchemaFacts /// The procedure's set; its names are not empty. /// /// A task that represents the asynchronous operation. - internal static async ValueTask EnsureAsync( - object connection, - string procedure, - NameSet names, - CancellationToken cancellationToken) + public static async ValueTask EnsureAsync( + object connection, string procedure, + NameSet names, CancellationToken cancellationToken) { if (names.Facts is not null) return; - if (connection is not DbConnection db - || ProcedureSchemaNames.Restrictions(procedure) is not { } restrictions) + if (ProcedureSchemaNames.Restrictions(procedure) is not { } restrictions + || connection is not DbConnection db) { names.KeepFacts(ParameterFacts.Unknown); return; @@ -105,16 +96,21 @@ internal static async ValueTask EnsureAsync( .GetSchemaAsync(Collection, restrictions, cancellationToken) .ConfigureAwait(false); #else - // DbConnection.GetSchemaAsync does not exist on the netstandard targets. + // DbConnection.GetSchemaAsync does not exist on the netstandard + // targets. cancellationToken.ThrowIfCancellationRequested(); DataTable table = db.GetSchema(Collection, restrictions); #endif facts = Read(table, restrictions[1] is not null, names); } - catch (Exception ex) when (ex is NotSupportedException or NotImplementedException or ArgumentException + catch (Exception ex) when ( + ex is NotSupportedException + or NotImplementedException + or ArgumentException && !cancellationToken.IsCancellationRequested) { - // Not while the call is canceled: a cancellation surfaced as one of these stores nothing. + // Not while the call is canceled: a cancellation surfaced as one of + // these stores nothing. facts = ParameterFacts.Unknown; } catch (Exception ex) when (ex is not OperationCanceledException) @@ -126,7 +122,8 @@ internal static async ValueTask EnsureAsync( } // Any other failure (for example a refusal inside a pending - // transaction): the call runs without the facts and the next call asks. + // transaction): the call runs without the facts and the next call + // asks. return; } @@ -146,14 +143,18 @@ internal static async ValueTask EnsureAsync( /// if the procedure name included a schema; otherwise, . /// The procedure's set. /// The facts; when the table tells nothing usable. - static ParameterFacts Read(DataTable? table, bool schemaGiven, NameSet names) + static ParameterFacts Read( + DataTable? table, bool schemaGiven, NameSet names) { if (table is null) return ParameterFacts.Unknown; DataColumnCollection columns = table.Columns; bool hasMode = columns.Contains("PARAMETER_MODE"); bool hasScale = columns.Contains("NUMERIC_SCALE"); - if (!columns.Contains("PARAMETER_NAME") || !hasMode && !hasScale) return ParameterFacts.Unknown; + if (!columns.Contains("PARAMETER_NAME") || !hasMode && !hasScale) + { + return ParameterFacts.Unknown; + } bool hasOrdinal = columns.Contains("ORDINAL_POSITION"); bool checkSchema = !schemaGiven && columns.Contains("SPECIFIC_SCHEMA"); @@ -170,10 +171,17 @@ static ParameterFacts Read(DataTable? table, bool schemaGiven, NameSet names) { string current = row["SPECIFIC_SCHEMA"] as string ?? ""; schema ??= current; - if (!string.Equals(schema, current, StringComparison.OrdinalIgnoreCase)) return ParameterFacts.Unknown; + if (!string.Equals( + schema, + current, + StringComparison.OrdinalIgnoreCase)) + { + return ParameterFacts.Unknown; + } } - // The ordinal 0 row is the return value, never a declared parameter. + // The ordinal 0 row is the return value, never a declared + // parameter. if (hasOrdinal && IsReturnRow(row["ORDINAL_POSITION"])) continue; if (row["PARAMETER_NAME"] is not string { Length: > 0 } name @@ -185,12 +193,18 @@ static ParameterFacts Read(DataTable? table, bool schemaGiven, NameSet names) seen[entry.Index] = true; any = true; - // Only the exact mode IN is an input only; INOUT (an OUTPUT parameter on SQL Server), OUT, anything unexpected and a missing value are not. - inputOnly[entry.Index] = hasMode && row["PARAMETER_MODE"] is string mode && string.Equals(mode, "IN", StringComparison.Ordinal); + // Only the exact mode IN is an input only; INOUT (an OUTPUT + // parameter on SQL Server), OUT, anything unexpected and a missing + // value are not. + inputOnly[entry.Index] = hasMode + && row["PARAMETER_MODE"] is string mode + && string.Equals(mode, "IN", StringComparison.Ordinal); if (hasScale) scales[entry.Index] = ScaleOf(row["NUMERIC_SCALE"]); } - return any ? new ParameterFacts(inputOnly, scales) : ParameterFacts.Unknown; + return any + ? new ParameterFacts(inputOnly, scales) + : ParameterFacts.Unknown; } static bool IsReturnRow(object ordinal) @@ -201,7 +215,10 @@ static bool IsReturnRow(object ordinal) { return Convert.ToInt32(ordinal, CultureInfo.InvariantCulture) == 0; } - catch (Exception ex) when (ex is FormatException or InvalidCastException or OverflowException) + catch (Exception ex) when ( + ex is FormatException + or InvalidCastException + or OverflowException) { return false; } @@ -216,7 +233,10 @@ static int ScaleOf(object value) int scale = Convert.ToInt32(value, CultureInfo.InvariantCulture); return scale < 0 ? ParameterFacts.NoScale : scale; } - catch (Exception ex) when (ex is FormatException or InvalidCastException or OverflowException) + catch (Exception ex) when ( + ex is FormatException + or InvalidCastException + or OverflowException) { return ParameterFacts.NoScale; } diff --git a/Source/Core/ProcedureSchemaNames.cs b/Source/Core/ProcedureSchemaNames.cs index 9ede27ad..6be61660 100644 --- a/Source/Core/ProcedureSchemaNames.cs +++ b/Source/Core/ProcedureSchemaNames.cs @@ -98,7 +98,7 @@ internal static async ValueTask> GetAsync(DbConnection co /// /// The procedure name as given to the command. /// The restrictions; when the name is not looked up (a database part, or an empty or unclosed part). - internal static string?[]? Restrictions(string procedure) + public static string?[]? Restrictions(string procedure) { List? parts = Split(procedure); if (parts is null || parts.Count > 2 || parts.Exists(static p => p.Length == 0)) return null; diff --git a/Tests/Open.Database.Extensions.Core.Tests/OutputMetadataTests.cs b/Tests/Open.Database.Extensions.Core.Tests/OutputMetadataTests.cs index 4b3536a5..ce22bbf1 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/OutputMetadataTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/OutputMetadataTests.cs @@ -109,6 +109,23 @@ sealed class NamedCommand(DbConnection connection, string procedure, params stri protected override ValueTask> GetProcedureParameterNamesAsync(DbConnection connection, string procedure, CancellationToken cancellationToken) => new([.. names]); } + sealed class OnePool(DbConnection connection) : IDbConnectionPool + { + public DbConnection Take() => connection; + + IDbConnection IDbConnectionPool.Take() => connection; + + public void Give(IDbConnection connection) { } + } + + sealed class NamedPooledCommand(IDbConnectionPool pool, string procedure, params string[] names) + : ExpressiveDbCommand(pool, CommandType.StoredProcedure, procedure) + { + protected override ImmutableArray GetProcedureParameterNames(DbConnection connection, string procedure) => [.. names]; + + protected override ValueTask> GetProcedureParameterNamesAsync(DbConnection connection, string procedure, CancellationToken cancellationToken) => new([.. names]); + } + // The columns of the collection that matter. A row: schema, ordinal, mode, name, scale. static DataTable Table(params (string Schema, int Ordinal, string? Mode, string Name, object? Scale)[] rows) { @@ -252,6 +269,31 @@ public static async Task EachMemberIsCheckedAgainstItsOwnParameter() // ---- when it is not asked ---------------------------------------------------- + // The call that takes its connection from a pool is a second call site of the run: it asks too, once, and checks before the run. + [Fact] + public static async Task ACallOnAPooledConnection_AsksOnce_AndChecksBeforeTheRun() + { + MetaConnection connection = With(One("IN")); + string procedure = Proc(); + var pool = new OnePool(connection); + + var ex = await Assert.ThrowsAsync(async () => await new NamedPooledCommand(pool, procedure, "@total").ExecuteOutputAsync(Token)); + + Assert.Contains("an input only", ex.Message); + Assert.Equal(0, connection.Executed); + Assert.Equal(1, connection.SchemaCalls); + + // The failed check forgot the entry; once the procedure passes, one read serves any number of calls. + connection.Table = One("INOUT"); + for (int i = 0; i < 3; i++) + { + Assert.Equal(1, (await new NamedPooledCommand(pool, procedure, "@total").ExecuteOutputAsync(Token)).Total); + } + + Assert.Equal(2, connection.SchemaCalls); + Assert.Equal(3, connection.Executed); + } + [Fact] public static async Task ACallWithoutOutputs_NeverAsks() { diff --git a/docsite/articles/expressive-commands.md b/docsite/articles/expressive-commands.md index a7e20bb7..877293ca 100644 --- a/docsite/articles/expressive-commands.md +++ b/docsite/articles/expressive-commands.md @@ -227,7 +227,7 @@ There is no blocking form. Known limits: - A parameter added with a null value (`AddParam(name, (int?)null, type)`) that is also an output member is sent as InputOutput too, so a lost output cannot be told from a NULL. For a pure output, add no value; add one only when the procedure reads it. - A member on a parameter the procedure does not declare `OUTPUT` throws before the run when the metadata is known, and is the provider's error when it is not (SQL Server: 8162); SQLite refuses every output direction with its own `ArgumentException`. - If the procedure was changed with `ALTER` while the process runs, the remembered metadata is out of date until a call fails. An input-only parameter made an output gives one `InvalidOperationException`, and the next call passes; an output made input-only reaches the provider's error, and the call after it is checked. If the procedure was changed, call again. A lower scale made by the change rounds silently until a call fails or the process restarts. -- A read of the metadata that the provider refuses (on the Core package inside a pending transaction, for example) lets the call run, and is read again on every call. A call that keeps failing a check removes the remembered metadata for every caller of that procedure, so their next call reads it again. +- A read of the metadata that the provider refuses (System.Data.SqlClient inside a pending transaction, for example) lets the call run, and is read again on every call. A call that keeps failing a check removes the remembered metadata for every caller of that procedure, so their next call reads it again. - SqlClient reports an error after the outputs are set, and a cancel while the command runs, with its own `SqlException`. - **A legacy `datetime` output can differ from a row in the last digits.** Outputs are sent as `datetime2`, so a `datetime` that stores `.997` (ticks of 1/300 second) reads back into a `DateTime` as `.9966667`, where a row read of the same value gives `.997`. `smalldatetime` and `datetime2` arrive exactly. To get what a row read gives, pass the value through `new SqlDateTime(value).Value` (from `System.Data.SqlTypes`), or have the procedure declare the output as `datetime2(3)`. Feeding such a value back in as an input lands on the same stored tick. - Output models use the runtime map, not a generated reader. From 43cbc104ee18355de0b47da384cf75e2732acd26 Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Wed, 2 Dec 2026 11:41:56 -0800 Subject: [PATCH 3/4] Rename the output parameter metadata types and read it by a named path The parameter metadata a call with output parameters checks (input-only mode and numeric scale) is now called metadata everywhere: ProcedureParameterMetadata (was ProcedureSchemaFacts), ParameterMetadata, NameSet.Metadata and NameSet.KeepMetadata, in code, comments, tests, release notes and documentation. The check against that metadata is unchanged. The flag that switched ResolveDerivedNamesAsync between reading the names only and also reading the metadata is gone. There are two named paths instead: ResolveDerivedNamesAsync reads the names, and ResolveDerivedNamesAndMetadataAsync reads the names and then the metadata of a procedure. A call chooses its path by reading an output parameter (ReadsOutputs); the run still has one await at that point and gains no field. Two test names that used an informal verb now say what they check. Co-Authored-By: Claude Sonnet 5.5 --- Source/Core/ExpressiveCommandBase.Output.cs | 12 +- Source/Core/ExpressiveCommandBase.cs | 105 ++++++++++++------ Source/Core/NameSet.cs | 16 +-- ...Facts.cs => ProcedureParameterMetadata.cs} | 50 ++++----- .../OutputMetadataLocalDbTests.cs | 12 +- .../OutputMetadataTests.cs | 78 ++++++------- 6 files changed, 158 insertions(+), 115 deletions(-) rename Source/Core/{ProcedureSchemaFacts.cs => ProcedureParameterMetadata.cs} (83%) diff --git a/Source/Core/ExpressiveCommandBase.Output.cs b/Source/Core/ExpressiveCommandBase.Output.cs index f4e99af4..34b34544 100644 --- a/Source/Core/ExpressiveCommandBase.Output.cs +++ b/Source/Core/ExpressiveCommandBase.Output.cs @@ -340,7 +340,7 @@ ValueTask RunOutputAsync( /// The type of the state of the run. /// The state of the run. /// for a call that reads an output parameter. - static bool NeedsFacts(TState state) + static bool ReadsOutputs(TState state) => typeof(TState) == typeof(OutputRun) && ((OutputRun)(object)state!).Layout.HasOutputParameter; @@ -443,7 +443,7 @@ void ResolveOutputs(OutputRun run, NameSet? names) } } - // Only a procedure's own set holds facts (a text's markers never do), + // Only a procedure's own set holds metadata (a text's markers never do), // and only once they were read. if (names is { Home: not null }) { @@ -457,7 +457,7 @@ void ResolveOutputs(OutputRun run, NameSet? names) /// Checks the output members against what the database says about the parameters they resolved to, when it said. /// /// - /// Only the exact mode IN is an input only; a mode that is anything else, or missing, is not (the facts keep no third state, because "not known" and "not an input only" never differ in what the call does). A scale is compared only when it is known. + /// Only the exact mode IN is an input only; a mode that is anything else, or missing, is not (the metadata has no third state, because "not known" and "not an input only" never differ in what the call does). A scale is compared only when it is known. /// /// The call's members. /// The parameter each member resolved to; for the return code. @@ -470,7 +470,7 @@ static void CheckMetadata( OutputLayout layout, string?[] resolved, NameSet names, string where) { - if (names.Facts is not { IsKnown: true } facts) return; + if (names.Metadata is not { IsKnown: true } metadata) return; for (int i = 0; i < resolved.Length; i++) { @@ -482,7 +482,7 @@ static void CheckMetadata( continue; } - if (facts.IsInputOnly(entry.Index)) + if (metadata.IsInputOnly(entry.Index)) { throw new InvalidOperationException( $"{member.Display} reads '{entry.Real}' of {where} as an " @@ -493,7 +493,7 @@ static void CheckMetadata( + "changed since it was first called, call again."); } - int declared = facts.Scale(entry.Index); + int declared = metadata.Scale(entry.Index); if (member.Wire is { Type: DbType.Decimal, HasPrecision: true } wire && declared > wire.Scale) { diff --git a/Source/Core/ExpressiveCommandBase.cs b/Source/Core/ExpressiveCommandBase.cs index a3def4e6..1a487265 100644 --- a/Source/Core/ExpressiveCommandBase.cs +++ b/Source/Core/ExpressiveCommandBase.cs @@ -872,27 +872,20 @@ protected virtual ValueTask> GetProcedureParameterNamesAs /// the @name markers of the text. /// /// An open connection to run the lookup on. - /// - /// for a call with output parameters, which also reads (once) what the database says about each parameter of a procedure. - /// /// /// /// The set of names, or when they are not known. /// ValueTask ResolveDerivedNamesAsync( TConnection connection, - bool needsFacts, CancellationToken cancellationToken) { if (Type == CommandType.StoredProcedure) { ProcedureKey key = ProcedureKey(connection); return ProcedureParameterNames.Find(NameCacheOwner, key) is { } kept - ? needsFacts && WantsFacts(kept) - ? ReadFactsAsync(connection, kept, cancellationToken) - : new(kept) - : ReadNamesAsync( - connection, key, needsFacts, cancellationToken); + ? new(kept) + : ReadNamesAsync(connection, key, cancellationToken); } // The @name markers found in the text. @@ -903,10 +896,10 @@ protected virtual ValueTask> GetProcedureParameterNamesAs } async ValueTask ReadNamesAsync( - TConnection connection, ProcedureKey key, - bool needsFacts, CancellationToken cancellationToken) - { - NameSet names = ProcedureParameterNames.Remember( + TConnection connection, + ProcedureKey key, + CancellationToken cancellationToken) + => ProcedureParameterNames.Remember( NameCacheOwner, key, await GetProcedureParameterNamesAsync( @@ -915,27 +908,81 @@ await GetProcedureParameterNamesAsync( cancellationToken) .ConfigureAwait(false)); - if (needsFacts && WantsFacts(names)) + /// + /// Asynchronously finds the names as + /// does, and for a procedure also reads (once) its parameter metadata, which + /// a call with output parameters checks before it runs. + /// + /// An open connection to run the lookups on. + /// + /// + /// The set of names, or when they are not known. + /// + ValueTask ResolveDerivedNamesAndMetadataAsync( + TConnection connection, + CancellationToken cancellationToken) + { + if (Type == CommandType.StoredProcedure) { - await ProcedureSchemaFacts.EnsureAsync( - connection, Command, names, cancellationToken) - .ConfigureAwait(false); + ProcedureKey key = ProcedureKey(connection); + return ProcedureParameterNames.Find(NameCacheOwner, key) is { } kept + ? NeedsMetadata(kept) + ? ReadMetadataAsync(connection, kept, cancellationToken) + : new(kept) + : ReadNamesAndMetadataAsync(connection, key, cancellationToken); } - return names; + // The @name markers of a text have no metadata. + return ResolveDerivedNamesAsync(connection, cancellationToken); + } + + /// + /// Asynchronously finds the names for a call: with the parameter metadata + /// when the call reads an output parameter (see + /// ), otherwise the names + /// only (see ). + /// + /// The type of the state of the run. + /// An open connection to run the lookups on. + /// The state of the run. + /// + /// + /// The set of names, or when they are not known. + /// + // Not async: the one await stays in the run, which gains no field. + ValueTask ResolveRunNamesAsync( + TConnection connection, + TState state, + CancellationToken cancellationToken) + => ReadsOutputs(state) + ? ResolveDerivedNamesAndMetadataAsync(connection, cancellationToken) + : ResolveDerivedNamesAsync(connection, cancellationToken); + + async ValueTask ReadNamesAndMetadataAsync( + TConnection connection, + ProcedureKey key, + CancellationToken cancellationToken) + { + NameSet? names = await ReadNamesAsync(connection, key, cancellationToken) + .ConfigureAwait(false); + + return names is not null && NeedsMetadata(names) + ? await ReadMetadataAsync(connection, names, cancellationToken) + .ConfigureAwait(false) + : names; } - // Only a procedure's own set (a text's markers are never asked), with + // Only a procedure's own set (a text's markers never have metadata), with // names, that has not been asked yet. - static bool WantsFacts(NameSet names) - => names is { Home: not null, Names.Length: > 0, Facts: null }; + static bool NeedsMetadata(NameSet names) + => names is { Home: not null, Names.Length: > 0, Metadata: null }; - async ValueTask ReadFactsAsync( + async ValueTask ReadMetadataAsync( TConnection connection, NameSet names, CancellationToken cancellationToken) { - await ProcedureSchemaFacts.EnsureAsync( + await ProcedureParameterMetadata.EnsureAsync( connection, Command, names, cancellationToken) .ConfigureAwait(false); @@ -1341,10 +1388,8 @@ async ValueTask ExecutePlainAsync( // No local outlives the await, so the state machine gains no field. if (_hasDerivedParams || typeof(TState) == typeof(OutputRun)) { - names = await ResolveDerivedNamesAsync( - single, - NeedsFacts(state), - cancellationToken) + names = await ResolveRunNamesAsync( + single, state, cancellationToken) .ConfigureAwait(false); built = PrepareDerived(single, names, output: OutputOf(state)); } @@ -1382,10 +1427,8 @@ async ValueTask ExecutePlainAsync( { if (_hasDerivedParams || typeof(TState) == typeof(OutputRun)) { - leaseNames = await ResolveDerivedNamesAsync( - lease.Connection, - NeedsFacts(state), - cancellationToken) + leaseNames = await ResolveRunNamesAsync( + lease.Connection, state, cancellationToken) .ConfigureAwait(false); leaseBuilt = PrepareDerived(lease.Connection, leaseNames, output: OutputOf(state)); } diff --git a/Source/Core/NameSet.cs b/Source/Core/NameSet.cs index c63f7ebb..91182db6 100644 --- a/Source/Core/NameSet.cs +++ b/Source/Core/NameSet.cs @@ -30,7 +30,7 @@ sealed class NameSet /// Where a procedure's set is kept (see ). /// What it is kept under. // The names are set here, before the set is published, and never change; - // the only field written afterwards is the facts (once). + // the only field written afterwards is the metadata (once). internal NameSet(ImmutableArray names, WeakReference? home = null, ProcedureKey key = default) { Debug.Assert(!names.IsDefault, "A set is made from names, not from 'not known'."); @@ -89,24 +89,24 @@ public int GetHashCode(string obj) /// What the database says about each parameter; when it was not asked. // Written at most once, and only by a call with output parameters (see - // ProcedureSchemaFacts): a set that was never asked for them holds nothing + // 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. - ParameterFacts? _facts; + ParameterMetadata? _metadata; /// - /// Gets what the database says about each parameter: when it was not asked, when it was asked and nothing is known. + /// Gets what the database says about each parameter: when it was not asked, when it was asked and nothing is known. /// - public ParameterFacts? Facts => Volatile.Read(ref _facts); + public ParameterMetadata? Metadata => Volatile.Read(ref _metadata); /// /// Keeps what the database said about each parameter, unless another call has kept its answer first. /// - /// The facts, aligned with . + /// The metadata, aligned with . // Two threads may both ask; the first answer stays, and the answers are // the same. - public void KeepFacts(ParameterFacts facts) - => Interlocked.CompareExchange(ref _facts, facts, null); + public void KeepMetadata(ParameterMetadata metadata) + => Interlocked.CompareExchange(ref _metadata, metadata, null); /// The entries by name, without the @ and ignoring case; built when first asked, never changed. Dictionary? _entries; diff --git a/Source/Core/ProcedureSchemaFacts.cs b/Source/Core/ProcedureParameterMetadata.cs similarity index 83% rename from Source/Core/ProcedureSchemaFacts.cs rename to Source/Core/ProcedureParameterMetadata.cs index 428389f6..eca02214 100644 --- a/Source/Core/ProcedureSchemaFacts.cs +++ b/Source/Core/ProcedureParameterMetadata.cs @@ -7,12 +7,12 @@ namespace Open.Database.Extensions; /// call with output parameters checks before it runs. /// /// -/// Immutable once built. A fact that the database did not report is "not -/// known", and a check never fails a call over a fact that is not known. +/// Immutable once built. Anything the database did not report is "not +/// known", and a check never fails a call over what is not known. /// /// Whether each parameter is an input only, aligned with the names of a set. /// The scale of each parameter, or . -sealed class ParameterFacts(bool[] inputOnly, int[] scales) +sealed class ParameterMetadata(bool[] inputOnly, int[] scales) { /// The scale of a parameter whose scale is not known. public const int NoScale = -1; @@ -22,7 +22,7 @@ sealed class ParameterFacts(bool[] inputOnly, int[] scales) /// provider has no such collection, or reported nothing usable). /// // Compared by reference: a lookup that found nothing is never repeated. - public static readonly ParameterFacts Unknown = new([], []); + public static readonly ParameterMetadata Unknown = new([], []); readonly bool[] _inputOnly = inputOnly; readonly int[] _scales = scales; @@ -52,7 +52,7 @@ sealed class ParameterFacts(bool[] inputOnly, int[] scales) /// fails any other way is not kept, so the next call asks again; only a /// cancellation is thrown. /// -static class ProcedureSchemaFacts +static class ProcedureParameterMetadata { /// /// The name of the ADO.NET schema collection. @@ -60,7 +60,7 @@ static class ProcedureSchemaFacts const string Collection = "ProcedureParameters"; /// - /// Reads the facts of a procedure's parameters into its set, unless the set + /// Reads the metadata of a procedure's parameters into its set, unless the set /// already holds them. /// /// @@ -79,16 +79,16 @@ public static async ValueTask EnsureAsync( object connection, string procedure, NameSet names, CancellationToken cancellationToken) { - if (names.Facts is not null) return; + if (names.Metadata is not null) return; if (ProcedureSchemaNames.Restrictions(procedure) is not { } restrictions || connection is not DbConnection db) { - names.KeepFacts(ParameterFacts.Unknown); + names.KeepMetadata(ParameterMetadata.Unknown); return; } - ParameterFacts facts; + ParameterMetadata metadata; try { #if NET10_0_OR_GREATER @@ -101,7 +101,7 @@ public static async ValueTask EnsureAsync( cancellationToken.ThrowIfCancellationRequested(); DataTable table = db.GetSchema(Collection, restrictions); #endif - facts = Read(table, restrictions[1] is not null, names); + metadata = Read(table, restrictions[1] is not null, names); } catch (Exception ex) when ( ex is NotSupportedException @@ -111,7 +111,7 @@ or ArgumentException { // Not while the call is canceled: a cancellation surfaced as one of // these stores nothing. - facts = ParameterFacts.Unknown; + metadata = ParameterMetadata.Unknown; } catch (Exception ex) when (ex is not OperationCanceledException) { @@ -122,16 +122,16 @@ or ArgumentException } // Any other failure (for example a refusal inside a pending - // transaction): the call runs without the facts and the next call + // transaction): the call runs without the metadata and the next call // asks. return; } - names.KeepFacts(facts); + names.KeepMetadata(metadata); } /// - /// Works out the facts of the set's parameters from the schema table. + /// Works out the metadata of the set's parameters from the schema table. /// /// /// Rows are matched to the set's names by name, as the set finds a name @@ -142,18 +142,18 @@ or ArgumentException /// The schema table. /// if the procedure name included a schema; otherwise, . /// The procedure's set. - /// The facts; when the table tells nothing usable. - static ParameterFacts Read( + /// The metadata; when the table tells nothing usable. + static ParameterMetadata Read( DataTable? table, bool schemaGiven, NameSet names) { - if (table is null) return ParameterFacts.Unknown; + if (table is null) return ParameterMetadata.Unknown; DataColumnCollection columns = table.Columns; bool hasMode = columns.Contains("PARAMETER_MODE"); bool hasScale = columns.Contains("NUMERIC_SCALE"); if (!columns.Contains("PARAMETER_NAME") || !hasMode && !hasScale) { - return ParameterFacts.Unknown; + return ParameterMetadata.Unknown; } bool hasOrdinal = columns.Contains("ORDINAL_POSITION"); @@ -163,7 +163,7 @@ static ParameterFacts Read( bool[] inputOnly = new bool[count]; int[] scales = new int[count]; bool[] seen = new bool[count]; - for (int i = 0; i < count; i++) scales[i] = ParameterFacts.NoScale; + for (int i = 0; i < count; i++) scales[i] = ParameterMetadata.NoScale; bool any = false; foreach (DataRow row in table.Rows) { @@ -176,7 +176,7 @@ static ParameterFacts Read( current, StringComparison.OrdinalIgnoreCase)) { - return ParameterFacts.Unknown; + return ParameterMetadata.Unknown; } } @@ -203,8 +203,8 @@ static ParameterFacts Read( } return any - ? new ParameterFacts(inputOnly, scales) - : ParameterFacts.Unknown; + ? new ParameterMetadata(inputOnly, scales) + : ParameterMetadata.Unknown; } static bool IsReturnRow(object ordinal) @@ -226,19 +226,19 @@ or InvalidCastException static int ScaleOf(object value) { - if (value is DBNull) return ParameterFacts.NoScale; + if (value is DBNull) return ParameterMetadata.NoScale; try { int scale = Convert.ToInt32(value, CultureInfo.InvariantCulture); - return scale < 0 ? ParameterFacts.NoScale : scale; + return scale < 0 ? ParameterMetadata.NoScale : scale; } catch (Exception ex) when ( ex is FormatException or InvalidCastException or OverflowException) { - return ParameterFacts.NoScale; + return ParameterMetadata.NoScale; } } } diff --git a/Tests/Open.Database.Extensions.Core.Tests/OutputMetadataLocalDbTests.cs b/Tests/Open.Database.Extensions.Core.Tests/OutputMetadataLocalDbTests.cs index be798017..241b2174 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/OutputMetadataLocalDbTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/OutputMetadataLocalDbTests.cs @@ -211,9 +211,9 @@ public static async Task AParameterWithNoScale_IsNotChecked() } // The failed check forgot the entry: after the procedure is changed the next call reads again and passes. One throw after a change is - // accepted (the entry still holds the old facts until a call fails). + // accepted (the entry still holds the old metadata until a call fails). [Fact] - public static async Task AFailedScaleCheck_HealsAfterTheProcedureIsAltered() + public static async Task AFailedScaleCheck_PassesAfterTheProcedureIsAltered() { LocalDbFixture.SkipUnlessAvailable(); using LocalDbFixture.Scratch procedure = Procedure("@total decimal(10,3) output", "set @total = 1.234;"); @@ -229,7 +229,7 @@ public static async Task AFailedScaleCheck_HealsAfterTheProcedureIsAltered() // Both directions of an ALTER under a running process: an output turned input-only is the provider's error (which forgets the // entry); an input-only turned output is one throw, then the call passes. [Fact] - public static async Task AnAlterUnderARunningProcess_OneFailureThenItHeals_InBothDirections() + public static async Task AnAlterUnderARunningProcess_OneFailureThenItPasses_InBothDirections() { LocalDbFixture.SkipUnlessAvailable(); using LocalDbFixture.Scratch procedure = Procedure("@id int output", "set @id = 1;"); @@ -241,14 +241,14 @@ public static async Task AnAlterUnderARunningProcess_OneFailureThenItHeals_InBot var provider = await Assert.ThrowsAsync(async () => await connection.StoredProcedure(name).ExecuteOutputAsync(Token)); Assert.Equal(8162, provider.Number); - // The failure forgot the entry: this call reads the new facts, and the check is the library's. + // The failure forgot the entry: this call reads the new metadata, and the check is the library's. await Assert.ThrowsAsync(async () => await connection.StoredProcedure(name).ExecuteOutputAsync(Token)); LocalDbFixture.Execute($"alter procedure dbo.[{procedure.Name}] @id int output as set @id = 2"); Assert.Equal(2, (await connection.StoredProcedure(name).ExecuteOutputAsync(Token)).Id); } - // The SQL Server package reads the names with its own query and the facts through Core's lookup. + // The SQL Server package reads the names with its own query and the metadata through Core's lookup. [Fact] public static async Task ASqlServerPackageCommand_IsCheckedToo() { @@ -319,7 +319,7 @@ public static async Task WithoutMetadata_TheProvidersOwnErrorApplies_AndTheLooku } // A refusal that is not "no such collection" (here an InvalidOperationException, as inside a transaction) is not kept: the call runs - // without the facts, and each call asks again. + // without the metadata, and each call asks again. [Fact] public static async Task AFailedMetadataRead_LetsTheCallRun_AndIsAskedAgainEveryCall() { diff --git a/Tests/Open.Database.Extensions.Core.Tests/OutputMetadataTests.cs b/Tests/Open.Database.Extensions.Core.Tests/OutputMetadataTests.cs index ce22bbf1..76cead7f 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/OutputMetadataTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/OutputMetadataTests.cs @@ -464,17 +464,17 @@ public static async Task ANameWithADatabasePart_IsNotAskedForRows_AndRunsWithout // ---- how the rows are read --------------------------------------------------------- - static async Task Read(DataTable table, params string[] names) + static async Task Read(DataTable table, params string[] names) { var set = new NameSet([.. names]); - await ProcedureSchemaFacts.EnsureAsync(With(table), "dbo.p", set, Token); - return set.Facts!; + await ProcedureParameterMetadata.EnsureAsync(With(table), "dbo.p", set, Token); + return set.Metadata!; } [Fact] public static async Task OnlyTheExactModeIN_IsInputOnly() { - ParameterFacts facts = await Read( + ParameterMetadata metadata = await Read( Table( ("dbo", 1, "IN", "@a", null), ("dbo", 2, "INOUT", "@b", null), @@ -484,13 +484,13 @@ public static async Task OnlyTheExactModeIN_IsInputOnly() ("dbo", 6, null, "@f", null)), "@a", "@b", "@c", "@d", "@e", "@f"); - Assert.Equal("YNNNNN", string.Concat(Enumerable.Range(0, 6).Select(i => facts.IsInputOnly(i) ? 'Y' : 'N'))); + Assert.Equal("YNNNNN", string.Concat(Enumerable.Range(0, 6).Select(i => metadata.IsInputOnly(i) ? 'Y' : 'N'))); } [Fact] public static async Task TheScale_IsTakenWhenItIsAWholeNumberAtLeastZero() { - ParameterFacts facts = await Read( + ParameterMetadata metadata = await Read( Table( ("dbo", 1, "IN", "@a", 4), ("dbo", 2, "IN", "@b", null), @@ -500,7 +500,7 @@ public static async Task TheScale_IsTakenWhenItIsAWholeNumberAtLeastZero() ("dbo", 6, "IN", "@f", 0)), "@a", "@b", "@c", "@d", "@e", "@f"); - Assert.Equal(new[] { 4, ParameterFacts.NoScale, ParameterFacts.NoScale, ParameterFacts.NoScale, 3, 0 }, Enumerable.Range(0, 6).Select(facts.Scale)); + Assert.Equal(new[] { 4, ParameterMetadata.NoScale, ParameterMetadata.NoScale, ParameterMetadata.NoScale, 3, 0 }, Enumerable.Range(0, 6).Select(metadata.Scale)); } // Rows are matched to names by name (ignoring case and a leading @), never by position; the first row of a name wins; the row of @@ -508,7 +508,7 @@ public static async Task TheScale_IsTakenWhenItIsAWholeNumberAtLeastZero() [Fact] public static async Task RowsAreMatchedByName_TheFirstRowWins_AndOrdinalZeroIsSkipped() { - ParameterFacts facts = await Read( + ParameterMetadata metadata = await Read( Table( ("dbo", 0, "IN", "@total", 9), ("dbo", 2, "INOUT", "TOTAL", 5), @@ -517,20 +517,20 @@ public static async Task RowsAreMatchedByName_TheFirstRowWins_AndOrdinalZeroIsSk ("dbo", 4, "IN", "@unknown", 3)), "@other", "@total"); - Assert.True(facts.IsInputOnly(0)); - Assert.Equal(1, facts.Scale(0)); - Assert.False(facts.IsInputOnly(1)); - Assert.Equal(5, facts.Scale(1)); + Assert.True(metadata.IsInputOnly(0)); + Assert.Equal(1, metadata.Scale(0)); + Assert.False(metadata.IsInputOnly(1)); + Assert.Equal(5, metadata.Scale(1)); } [Fact] public static async Task AParameterWithNoRow_IsNotInputOnlyAndHasNoScale() { - ParameterFacts facts = await Read(One("IN"), "@total", "@missing"); + ParameterMetadata metadata = await Read(One("IN"), "@total", "@missing"); - Assert.True(facts.IsInputOnly(0)); - Assert.False(facts.IsInputOnly(1)); - Assert.Equal(ParameterFacts.NoScale, facts.Scale(1)); + Assert.True(metadata.IsInputOnly(0)); + Assert.False(metadata.IsInputOnly(1)); + Assert.Equal(ParameterMetadata.NoScale, metadata.Scale(1)); } [Fact] @@ -538,14 +538,14 @@ public static async Task AMissingScaleColumn_StillGivesTheMode_AndAMissingModeCo { DataTable noScale = One("IN"); noScale.Columns.Remove("NUMERIC_SCALE"); - ParameterFacts mode = await Read(noScale, "@total"); + ParameterMetadata mode = await Read(noScale, "@total"); Assert.True(mode.IsKnown); Assert.True(mode.IsInputOnly(0)); - Assert.Equal(ParameterFacts.NoScale, mode.Scale(0)); + Assert.Equal(ParameterMetadata.NoScale, mode.Scale(0)); DataTable noMode = One("IN", 3); noMode.Columns.Remove("PARAMETER_MODE"); - ParameterFacts scale = await Read(noMode, "@total"); + ParameterMetadata scale = await Read(noMode, "@total"); Assert.True(scale.IsKnown); Assert.False(scale.IsInputOnly(0)); Assert.Equal(3, scale.Scale(0)); @@ -557,9 +557,9 @@ public static async Task AMissingOrdinalColumn_MatchesByNameOnly() DataTable table = One("IN", 2); table.Columns.Remove("ORDINAL_POSITION"); - ParameterFacts facts = await Read(table, "@total"); + ParameterMetadata metadata = await Read(table, "@total"); - Assert.True(facts.IsInputOnly(0)); + Assert.True(metadata.IsInputOnly(0)); } [Fact] @@ -571,11 +571,11 @@ public static async Task NothingUsable_IsUnknown_AndKept() DataTable noName = One("IN", 3); noName.Columns.Remove("PARAMETER_NAME"); - Assert.Same(ParameterFacts.Unknown, await Read(noMode, "@total")); - Assert.Same(ParameterFacts.Unknown, await Read(noName, "@total")); - Assert.Same(ParameterFacts.Unknown, await Read(Table(), "@total")); - Assert.Same(ParameterFacts.Unknown, await Read(One("IN", 3, "@somethingelse"), "@total")); - Assert.Same(ParameterFacts.Unknown, await Read(Table(("dbo", 0, "OUT", "@total", null)), "@total")); + Assert.Same(ParameterMetadata.Unknown, await Read(noMode, "@total")); + Assert.Same(ParameterMetadata.Unknown, await Read(noName, "@total")); + Assert.Same(ParameterMetadata.Unknown, await Read(Table(), "@total")); + Assert.Same(ParameterMetadata.Unknown, await Read(One("IN", 3, "@somethingelse"), "@total")); + Assert.Same(ParameterMetadata.Unknown, await Read(Table(("dbo", 0, "OUT", "@total", null)), "@total")); } [Fact] @@ -584,9 +584,9 @@ public static async Task ANameTheLookupCannotRestrict_IsUnknown_WithoutAskingThe MetaConnection connection = With(One("IN")); var set = new NameSet(["@total"]); - await ProcedureSchemaFacts.EnsureAsync(connection, "db.dbo.p", set, Token); + await ProcedureParameterMetadata.EnsureAsync(connection, "db.dbo.p", set, Token); - Assert.Same(ParameterFacts.Unknown, set.Facts); + Assert.Same(ParameterMetadata.Unknown, set.Metadata); Assert.Equal(0, connection.SchemaCalls); } @@ -595,22 +595,22 @@ public static async Task AConnectionThatIsNotADbConnection_IsUnknown_AndKept() { var set = new NameSet(["@total"]); - await ProcedureSchemaFacts.EnsureAsync(Substitute.For(), "dbo.p", set, Token); + await ProcedureParameterMetadata.EnsureAsync(Substitute.For(), "dbo.p", set, Token); - Assert.Same(ParameterFacts.Unknown, set.Facts); + Assert.Same(ParameterMetadata.Unknown, set.Metadata); } [Fact] public static async Task TheFirstAnswerKept_IsTheOneThatStays() { var set = new NameSet(["@total"]); - await ProcedureSchemaFacts.EnsureAsync(With(One("IN")), "dbo.p", set, Token); - ParameterFacts first = set.Facts!; + await ProcedureParameterMetadata.EnsureAsync(With(One("IN")), "dbo.p", set, Token); + ParameterMetadata first = set.Metadata!; - set.KeepFacts(ParameterFacts.Unknown); - await ProcedureSchemaFacts.EnsureAsync(With(One("INOUT")), "dbo.p", set, Token); + set.KeepMetadata(ParameterMetadata.Unknown); + await ProcedureParameterMetadata.EnsureAsync(With(One("INOUT")), "dbo.p", set, Token); - Assert.Same(first, set.Facts); + Assert.Same(first, set.Metadata); Assert.True(first.IsInputOnly(0)); } @@ -620,11 +620,11 @@ public static async Task TwoCallsThatBothAsk_KeepOneAnswer() var set = new NameSet(["@total"]); MetaConnection connection = With(One("IN")); - await Task.WhenAll(Enumerable.Range(0, 16).Select(_ => Task.Run(async () => await ProcedureSchemaFacts.EnsureAsync(connection, "dbo.p", set, Token), Token))); + await Task.WhenAll(Enumerable.Range(0, 16).Select(_ => Task.Run(async () => await ProcedureParameterMetadata.EnsureAsync(connection, "dbo.p", set, Token), Token))); - ParameterFacts kept = set.Facts!; - await ProcedureSchemaFacts.EnsureAsync(connection, "dbo.p", set, Token); - Assert.Same(kept, set.Facts); + ParameterMetadata kept = set.Metadata!; + await ProcedureParameterMetadata.EnsureAsync(connection, "dbo.p", set, Token); + Assert.Same(kept, set.Metadata); Assert.True(kept.IsInputOnly(0)); } } From a30a79b9112651efc468bc49cb596ac421ba2ef1 Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Wed, 2 Dec 2026 12:10:46 -0800 Subject: [PATCH 4/4] Output metadata checks: mode IN wording, two read methods, shorter text - Say what the database reports in the words SQL Server and ADO.NET use: a parameter whose mode is IN (an input parameter), instead of an invented phrase. The member is IsModeIn; the exception message, the documentation and the tests follow. - Split the schema table read into two named methods, one for a procedure name that included its schema and one for a name without it (which refuses a table that spans schemas), sharing one private method for the rows. No bool parameter selects the behavior. - Correct the documentation of an ALTER under a running process: a scale lowered by the change is not caught and rounds silently, as without metadata, until the remembered metadata is dropped by an unrelated failure or eviction. - Layout: the expression bodies of the small members, a using declaration for the schema table, grouped arguments. - Cut repeated text: one statement of the provider error in the article, one comment per fact in the run, the constant summary and the repeated class remark. The scale message states the scale to declare in the procedure. - Name the helper that returns a set whose metadata was read NamesWithMetadataAsync, and one test after what it proves. Co-Authored-By: Claude Sonnet 5.5 --- Source/Core/ExpressiveCommandBase.Output.cs | 21 ++- Source/Core/ExpressiveCommandBase.cs | 7 +- Source/Core/NameSet.cs | 3 +- Source/Core/Output.docs.xml | 2 +- Source/Core/ProcedureParameterMetadata.cs | 129 +++++++++++------- .../OutputMetadataLocalDbTests.cs | 26 ++-- .../OutputMetadataTests.cs | 44 +++--- .../OutputParameterLocalDbTests.cs | 6 +- docsite/articles/expressive-commands.md | 4 +- docsite/articles/release-notes.md | 2 +- 10 files changed, 135 insertions(+), 109 deletions(-) diff --git a/Source/Core/ExpressiveCommandBase.Output.cs b/Source/Core/ExpressiveCommandBase.Output.cs index 44cfc5e6..32e1a7fd 100644 --- a/Source/Core/ExpressiveCommandBase.Output.cs +++ b/Source/Core/ExpressiveCommandBase.Output.cs @@ -453,8 +453,7 @@ void ResolveOutputs(OutputRun run, NameSet? names) } } - // Only a procedure's own set holds metadata (a text's markers never do), - // and only once they were read. + // 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); @@ -467,14 +466,14 @@ void ResolveOutputs(OutputRun run, NameSet? names) /// Checks the output members against what the database says about the parameters they resolved to, when it said. /// /// - /// Only the exact mode IN is an input only; a mode that is anything else, or missing, is not (the metadata has no third state, because "not known" and "not an input only" never differ in what the call does). A scale is compared only when it is known. + /// Only the exact mode IN counts; a mode that is anything else, or missing, does not (the metadata has no third state, because "not known" and "not mode IN" never differ in what the call does). A scale is compared only when it is known. /// /// The call's members. /// The parameter each member resolved to; for the return code. /// The procedure's set. /// The procedure, for the messages. /// - /// A member reads an input-only parameter, or declares a scale lower than the procedure's. + /// A member reads a parameter whose mode is IN, or declares a scale lower than the procedure's. /// static void CheckMetadata( OutputLayout layout, string?[] resolved, @@ -492,13 +491,13 @@ static void CheckMetadata( continue; } - if (metadata.IsInputOnly(entry.Index)) + 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 only, so the call would be " - + "refused. Declare the parameter OUTPUT in the " + + "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."); } @@ -516,10 +515,10 @@ static void CheckMetadata( $"{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} (a higher scale " - + "is fine), or lower the parameter's scale in the " - + "procedure. If the procedure was changed since it " - + "was first called, call again."); + + $"{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."); } } } diff --git a/Source/Core/ExpressiveCommandBase.cs b/Source/Core/ExpressiveCommandBase.cs index 7b7291f3..cd3cc2b3 100644 --- a/Source/Core/ExpressiveCommandBase.cs +++ b/Source/Core/ExpressiveCommandBase.cs @@ -931,12 +931,11 @@ await GetProcedureParameterNamesAsync( ProcedureKey key = ProcedureKey(connection); return ProcedureParameterNames.Find(NameCacheOwner, key) is { } kept ? NeedsMetadata(kept) - ? ReadMetadataAsync(connection, kept, cancellationToken) + ? NamesWithMetadataAsync(connection, kept, cancellationToken) : new(kept) : ReadNamesAndMetadataAsync(connection, key, cancellationToken); } - // The @name markers of a text have no metadata. return ResolveDerivedNamesAsync(connection, cancellationToken); } @@ -971,7 +970,7 @@ await GetProcedureParameterNamesAsync( .ConfigureAwait(false); return names is not null && NeedsMetadata(names) - ? await ReadMetadataAsync(connection, names, cancellationToken) + ? await NamesWithMetadataAsync(connection, names, cancellationToken) .ConfigureAwait(false) : names; } @@ -981,7 +980,7 @@ await GetProcedureParameterNamesAsync( static bool NeedsMetadata(NameSet names) => names is { Home: not null, Names.Length: > 0, Metadata: null }; - async ValueTask ReadMetadataAsync( + async ValueTask NamesWithMetadataAsync( TConnection connection, NameSet names, CancellationToken cancellationToken) diff --git a/Source/Core/NameSet.cs b/Source/Core/NameSet.cs index 82b3058d..be335481 100644 --- a/Source/Core/NameSet.cs +++ b/Source/Core/NameSet.cs @@ -100,7 +100,8 @@ public int GetHashCode(string obj) /// /// Gets what the database says about each parameter: when it was not asked, when it was asked and nothing is known. /// - public ParameterMetadata? Metadata => Volatile.Read(ref _metadata); + public ParameterMetadata? Metadata + => Volatile.Read(ref _metadata); /// /// Keeps what the database said about each parameter, unless another call has kept its answer first. diff --git a/Source/Core/Output.docs.xml b/Source/Core/Output.docs.xml index 8a167af2..c04be8df 100644 --- a/Source/Core/Output.docs.xml +++ b/Source/Core/Output.docs.xml @@ -132,7 +132,7 @@ When the call runs, before the command executes, and the procedure's parameter metadata is available: - a member reads a parameter the database reports as an input only, or a member declares a scale lower than the procedure's parameter has (the value would be rounded). + a member reads a parameter whose mode the database reports as IN (an input parameter), or a 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 ProcedureParameters 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. diff --git a/Source/Core/ProcedureParameterMetadata.cs b/Source/Core/ProcedureParameterMetadata.cs index eca02214..295ff417 100644 --- a/Source/Core/ProcedureParameterMetadata.cs +++ b/Source/Core/ProcedureParameterMetadata.cs @@ -10,9 +10,9 @@ namespace Open.Database.Extensions; /// Immutable once built. Anything the database did not report is "not /// known", and a check never fails a call over what is not known. /// -/// Whether each parameter is an input only, aligned with the names of a set. +/// Whether each parameter's mode is IN, aligned with the names of a set. /// The scale of each parameter, or . -sealed class ParameterMetadata(bool[] inputOnly, int[] scales) +sealed class ParameterMetadata(bool[] modeIn, int[] scales) { /// The scale of a parameter whose scale is not known. public const int NoScale = -1; @@ -24,26 +24,29 @@ sealed class ParameterMetadata(bool[] inputOnly, int[] scales) // Compared by reference: a lookup that found nothing is never repeated. public static readonly ParameterMetadata Unknown = new([], []); - readonly bool[] _inputOnly = inputOnly; + readonly bool[] _modeIn = modeIn; readonly int[] _scales = scales; /// Gets whether anything is known. - public bool IsKnown => !ReferenceEquals(this, Unknown); + public bool IsKnown + => !ReferenceEquals(this, Unknown); - /// Gets whether a parameter is an input only. + /// Gets whether the database reports a parameter's mode as IN. /// The place of the parameter in the set's names. - /// only when the database reports the mode IN. - public bool IsInputOnly(int index) => _inputOnly[index]; + /// only when the mode is exactly IN. + public bool IsModeIn(int index) + => _modeIn[index]; /// Gets the scale the database reports for a parameter. /// The place of the parameter in the set's names. /// The scale, or when it is not known. - public int Scale(int index) => _scales[index]; + public int Scale(int index) + => _scales[index]; } /// -/// Reads, for the parameters a stored procedure declares, whether each is an -/// input only and its numeric scale, from the ADO.NET schema collection +/// Reads, for the parameters a stored procedure declares, whether each has the +/// mode IN and its numeric scale, from the ADO.NET schema collection /// ProcedureParameters (see ). /// /// @@ -54,9 +57,6 @@ sealed class ParameterMetadata(bool[] inputOnly, int[] scales) /// static class ProcedureParameterMetadata { - /// - /// The name of the ADO.NET schema collection. - /// const string Collection = "ProcedureParameters"; /// @@ -64,11 +64,11 @@ static class ProcedureParameterMetadata /// already holds them. /// /// - /// Two calls may both read; one answer is kept. - /// A cancellation is thrown; an exception raised while the token is - /// canceled that is not an is - /// thrown with the procedure's name added to - /// under the key Procedure. + /// Two calls may both read; one answer is kept. An exception raised while + /// the token is canceled that is not an + /// is thrown with the procedure's + /// name added to under the key + /// Procedure. /// /// An open connection to run the lookup on. /// The procedure name as given to the command. @@ -92,16 +92,18 @@ public static async ValueTask EnsureAsync( try { #if NET10_0_OR_GREATER - DataTable table = await db - .GetSchemaAsync(Collection, restrictions, cancellationToken) + using DataTable table = await db.GetSchemaAsync( + Collection, restrictions, cancellationToken) .ConfigureAwait(false); #else // DbConnection.GetSchemaAsync does not exist on the netstandard // targets. cancellationToken.ThrowIfCancellationRequested(); - DataTable table = db.GetSchema(Collection, restrictions); + using DataTable table = db.GetSchema(Collection, restrictions); #endif - metadata = Read(table, restrictions[1] is not null, names); + metadata = restrictions[1] is not null + ? ReadForSchema(table, names) + : ReadForAnySchema(table, names); } catch (Exception ex) when ( ex is NotSupportedException @@ -131,23 +133,64 @@ or ArgumentException } /// - /// Works out the metadata of the set's parameters from the schema table. + /// Works out the metadata of the set's parameters from the schema table of a + /// procedure whose name included its schema. + /// + /// The schema table. + /// The procedure's set. + /// The metadata; when the table tells nothing usable. + static ParameterMetadata ReadForSchema(DataTable? table, NameSet names) + => table is null + ? ParameterMetadata.Unknown + : ReadRows(table, names); + + /// + /// Works out the metadata of the set's parameters from the schema table of a + /// procedure whose name had no schema: rows from more than one schema are + /// ambiguous, and nothing is known. + /// + /// The schema table. + /// The procedure's set. + /// The metadata; when the table tells nothing usable or spans schemas. + static ParameterMetadata ReadForAnySchema(DataTable? table, NameSet names) + => table is null || SpansSchemas(table) + ? ParameterMetadata.Unknown + : ReadRows(table, names); + + static bool SpansSchemas(DataTable table) + { + if (!table.Columns.Contains("SPECIFIC_SCHEMA")) return false; + + string? schema = null; + foreach (DataRow row in table.Rows) + { + string current = row["SPECIFIC_SCHEMA"] as string ?? ""; + schema ??= current; + if (!string.Equals( + schema, + current, + StringComparison.OrdinalIgnoreCase)) + { + return true; + } + } + + return false; + } + + /// + /// Reads the rows of a schema table into the metadata of the set's parameters. /// /// /// Rows are matched to the set's names by name, as the set finds a name /// (ignoring case and a leading @; the first row of a name wins), never - /// by position. When no schema was given and the rows span more than one - /// schema, nothing is known. + /// by position. /// /// The schema table. - /// if the procedure name included a schema; otherwise, . /// The procedure's set. /// The metadata; when the table tells nothing usable. - static ParameterMetadata Read( - DataTable? table, bool schemaGiven, NameSet names) + static ParameterMetadata ReadRows(DataTable table, NameSet names) { - if (table is null) return ParameterMetadata.Unknown; - DataColumnCollection columns = table.Columns; bool hasMode = columns.Contains("PARAMETER_MODE"); bool hasScale = columns.Contains("NUMERIC_SCALE"); @@ -157,29 +200,14 @@ static ParameterMetadata Read( } bool hasOrdinal = columns.Contains("ORDINAL_POSITION"); - bool checkSchema = !schemaGiven && columns.Contains("SPECIFIC_SCHEMA"); - string? schema = null; int count = names.Names.Length; - bool[] inputOnly = new bool[count]; + bool[] modeIn = new bool[count]; int[] scales = new int[count]; bool[] seen = new bool[count]; for (int i = 0; i < count; i++) scales[i] = ParameterMetadata.NoScale; bool any = false; foreach (DataRow row in table.Rows) { - if (checkSchema) - { - string current = row["SPECIFIC_SCHEMA"] as string ?? ""; - schema ??= current; - if (!string.Equals( - schema, - current, - StringComparison.OrdinalIgnoreCase)) - { - return ParameterMetadata.Unknown; - } - } - // The ordinal 0 row is the return value, never a declared // parameter. if (hasOrdinal && IsReturnRow(row["ORDINAL_POSITION"])) continue; @@ -193,17 +221,16 @@ static ParameterMetadata Read( seen[entry.Index] = true; any = true; - // Only the exact mode IN is an input only; INOUT (an OUTPUT - // parameter on SQL Server), OUT, anything unexpected and a missing - // value are not. - inputOnly[entry.Index] = hasMode + // Only the exact mode IN counts; INOUT (an OUTPUT parameter on SQL + // Server), OUT, anything unexpected and a missing value do not. + modeIn[entry.Index] = hasMode && row["PARAMETER_MODE"] is string mode && string.Equals(mode, "IN", StringComparison.Ordinal); if (hasScale) scales[entry.Index] = ScaleOf(row["NUMERIC_SCALE"]); } return any - ? new ParameterMetadata(inputOnly, scales) + ? new ParameterMetadata(modeIn, scales) : ParameterMetadata.Unknown; } diff --git a/Tests/Open.Database.Extensions.Core.Tests/OutputMetadataLocalDbTests.cs b/Tests/Open.Database.Extensions.Core.Tests/OutputMetadataLocalDbTests.cs index 241b2174..0df0ce5f 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/OutputMetadataLocalDbTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/OutputMetadataLocalDbTests.cs @@ -10,7 +10,7 @@ namespace Open.Database.Extensions.Tests; // What a call with output parameters checks before it runs, from the procedure's metadata (ProcedureParameters), against SQL Server: -// an output on an input-only parameter, and a decimal whose scale is lower than the procedure's. Skipped without LocalDB (see LocalDbFixture). +// an output on an input parameter (mode IN), and a decimal whose scale is lower than the procedure's. Skipped without LocalDB (see LocalDbFixture). [ExcludeFromCodeCoverage] [Collection("LocalDB DDL")] public static class OutputMetadataLocalDbTests @@ -50,7 +50,7 @@ static async Task OpenAsync() } [Fact] - public static async Task AnInputOnlyParameter_ThrowsBeforeTheRun_ForAModelMember() + public static async Task AnInputParameter_ThrowsBeforeTheRun_ForAModelMember() { LocalDbFixture.SkipUnlessAvailable(); (LocalDbFixture.Scratch table, LocalDbFixture.Scratch procedure) = Recording("@id int"); @@ -62,14 +62,14 @@ public static async Task AnInputOnlyParameter_ThrowsBeforeTheRun_ForAModelMember var ex = await Assert.ThrowsAsync(async () => await connection.StoredProcedure("dbo." + procedure.Name).ExecuteOutputAsync(Token)); Assert.Contains("PostId.Id reads '@id' of dbo.", ex.Message); - Assert.Contains("reports that parameter as an input only, so the call would be refused", ex.Message); + Assert.Contains("reports that parameter as an input parameter (mode IN), so the call would be refused", ex.Message); Assert.Contains("Declare the parameter OUTPUT in the procedure, or remove the member", ex.Message); Assert.Equal(0, LocalDbFixture.Count(table.Name)); } } [Fact] - public static async Task AnInputOnlyParameter_ThrowsBeforeTheRun_ForANamedOutputAndACapture() + public static async Task AnInputParameter_ThrowsBeforeTheRun_ForANamedOutputAndACapture() { LocalDbFixture.SkipUnlessAvailable(); (LocalDbFixture.Scratch table, LocalDbFixture.Scratch procedure) = Recording("@id int", "select 1 as N;"); @@ -81,7 +81,7 @@ public static async Task AnInputOnlyParameter_ThrowsBeforeTheRun_ForANamedOutput var named = await Assert.ThrowsAsync(async () => await connection.StoredProcedure(name).ExecuteOutputAsync("id", Token)); Assert.Contains("The output parameter 'id' reads '@id'", named.Message); - Assert.Contains("an input only", named.Message); + Assert.Contains("an input parameter (mode IN)", named.Message); var captured = await Assert.ThrowsAsync(async () => await connection.StoredProcedure(name) .CaptureOutput("id", out DbCapture id) @@ -96,7 +96,7 @@ public static async Task AnInputOnlyParameter_ThrowsBeforeTheRun_ForANamedOutput // A value given to an IN parameter makes the member an InputOutput: the server refuses that too, and so does the check. [Fact] - public static async Task AnInputOutputMemberOnAnInputOnlyParameter_Throws() + public static async Task AnInputOutputMemberOnAnInputParameter_Throws() { LocalDbFixture.SkipUnlessAvailable(); using LocalDbFixture.Scratch procedure = Procedure("@id int", "select 1;"); @@ -107,7 +107,7 @@ public static async Task AnInputOutputMemberOnAnInputOnlyParameter_Throws() .AddParam("id", 5) .ExecuteOutputAsync(Token)); - Assert.Contains("an input only", ex.Message); + Assert.Contains("an input parameter (mode IN)", ex.Message); } // An OUTPUT parameter is reported as INOUT, and a procedure with a mix of the two checks each parameter by its own mode. @@ -141,7 +141,7 @@ public static async Task ADecimalScaleLowerThanTheProcedures_ThrowsBeforeTheRun_ var ex = await Assert.ThrowsAsync(async () => await connection.StoredProcedure(name).ExecuteOutputAsync(Token)); Assert.Contains("Total2.Total has the scale 2, but '@total' of dbo.", ex.Message); Assert.Contains("has the scale 3, so the value would be rounded to 2 decimal places", ex.Message); - Assert.Contains("Declare the member as [Column(TypeName = \"decimal(10,3)\")] or higher (a higher scale is fine)", ex.Message); + Assert.Contains("Declare the member as [Column(TypeName = \"decimal(10,3)\")] or higher", ex.Message); Assert.Equal(0, LocalDbFixture.Count(table.Name)); Assert.Equal(1.234m, (await connection.StoredProcedure(name).ExecuteOutputAsync(Token)).Total); @@ -159,7 +159,7 @@ public static async Task ADecimalScaleCheck_AlsoCoversTheNamedAndCapturedForms() var generic = await Assert.ThrowsAsync(async () => await connection.StoredProcedure(name).ExecuteOutputAsync("total", 10, 2, Token)); Assert.Contains("The output parameter 'total' has the scale 2, but '@total' of dbo.", generic.Message); - Assert.Contains("Pass a scale of 3 or more (a higher scale is fine)", generic.Message); + Assert.Contains("Pass a scale of 3 or more", generic.Message); var compiled = await Assert.ThrowsAsync(async () => await connection.StoredProcedure(name).ExecuteOutputDecimalAsync("total", 10, 2, Token)); Assert.Contains("has the scale 3", compiled.Message); @@ -226,8 +226,8 @@ public static async Task AFailedScaleCheck_PassesAfterTheProcedureIsAltered() Assert.Equal(1.23m, (await connection.StoredProcedure(name).ExecuteOutputAsync(Token)).Total); } - // Both directions of an ALTER under a running process: an output turned input-only is the provider's error (which forgets the - // entry); an input-only turned output is one throw, then the call passes. + // Both directions of an ALTER under a running process: an output turned to mode IN is the provider's error (which forgets the + // entry); an input parameter turned to an output is one throw, then the call passes. [Fact] public static async Task AnAlterUnderARunningProcess_OneFailureThenItPasses_InBothDirections() { @@ -261,7 +261,7 @@ public static async Task ASqlServerPackageCommand_IsCheckedToo() var ex = await Assert.ThrowsAsync(async () => await new Expressive(connection, CommandType.StoredProcedure, "dbo." + procedure.Name).ExecuteOutputAsync(Token)); - Assert.Contains("an input only", ex.Message); + Assert.Contains("an input parameter (mode IN)", ex.Message); Assert.Equal(0, LocalDbFixture.Count(table.Name)); } } @@ -281,7 +281,7 @@ public static async Task InAPendingTransaction_TheMetadataIsRead_AndTheCheckThro await using (SqlTransaction transaction = connection.BeginTransaction()) { var ex = await Assert.ThrowsAsync(async () => await new Expressive(connection, transaction, CommandType.StoredProcedure, "dbo." + procedure.Name).ExecuteOutputAsync(Token)); - Assert.Contains("an input only", ex.Message); + Assert.Contains("an input parameter (mode IN)", ex.Message); await transaction.RollbackAsync(Token); } diff --git a/Tests/Open.Database.Extensions.Core.Tests/OutputMetadataTests.cs b/Tests/Open.Database.Extensions.Core.Tests/OutputMetadataTests.cs index 76cead7f..5f11d2ca 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/OutputMetadataTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/OutputMetadataTests.cs @@ -157,7 +157,7 @@ static ValueTask Total(MetaConnection connection, string procedure, param // ---- when the metadata is asked ---------------------------------------------- [Fact] - public static async Task AnInputOnlyParameter_ThrowsBeforeTheRun_ForgetsTheEntry_AndTheNextCallReadsAgain() + public static async Task AnInputParameter_ThrowsBeforeTheRun_ForgetsTheEntry_AndTheNextCallReadsAgain() { MetaConnection connection = With(One("IN")); string procedure = Proc(); @@ -165,7 +165,7 @@ public static async Task AnInputOnlyParameter_ThrowsBeforeTheRun_ForgetsTheEntry var ex = await Assert.ThrowsAsync(async () => await Total(connection, procedure, "@total")); Assert.Contains("Whole.Total reads '@total' of " + procedure, ex.Message); - Assert.Contains("reports that parameter as an input only, so the call would be refused", ex.Message); + Assert.Contains("reports that parameter as an input parameter (mode IN), so the call would be refused", ex.Message); Assert.Contains("Declare the parameter OUTPUT in the procedure, or remove the member. If the procedure was changed since it was first called, call again.", ex.Message); Assert.Equal(0, connection.Executed); Assert.Equal(1, connection.SchemaCalls); @@ -209,7 +209,7 @@ public static async Task ADecimalScaleLowerThanTheProcedures_Throws_AndEqualOrHi var ex = await Assert.ThrowsAsync(async () => await command.ExecuteOutputAsync(Token)); Assert.Contains($"Scaled.Total has the scale 2, but '@total' of ", ex.Message); Assert.Contains($"has the scale {procedureScale}, so the value would be rounded to 2 decimal places", ex.Message); - Assert.Contains($"Declare the member as [Column(TypeName = \"decimal(10,{procedureScale})\")] or higher (a higher scale is fine), or lower the parameter's scale in the procedure.", ex.Message); + Assert.Contains($"Declare the member as [Column(TypeName = \"decimal(10,{procedureScale})\")] or higher, or declare the parameter in the procedure with the scale 2.", ex.Message); Assert.Equal(0, connection.Executed); } @@ -221,7 +221,7 @@ public static async Task ANamedDecimal_IsCheckedLikeAModelMember() var generic = await Assert.ThrowsAsync(async () => await new NamedCommand(connection, procedure, "@total").ExecuteOutputAsync("total", 10, 2, Token)); Assert.Contains("The output parameter 'total' has the scale 2, but '@total' of ", generic.Message); - Assert.Contains("Pass a scale of 3 or more (a higher scale is fine)", generic.Message); + Assert.Contains("Pass a scale of 3 or more", generic.Message); var compiled = await Assert.ThrowsAsync(async () => await new NamedCommand(connection, procedure, "@total").ExecuteOutputDecimalAsync("total", 10, 2, Token)); Assert.Contains("has the scale 3", compiled.Message); @@ -232,25 +232,25 @@ public static async Task ANamedDecimal_IsCheckedLikeAModelMember() } [Fact] - public static async Task ANamedOutput_OnAnInputOnlyParameter_Throws() + public static async Task ANamedOutput_OnAnInputParameter_Throws() { MetaConnection connection = With(One("IN")); var ex = await Assert.ThrowsAsync(async () => await new NamedCommand(connection, Proc(), "@total").ExecuteOutputAsync("total", Token)); Assert.Contains("The output parameter 'total' reads '@total'", ex.Message); - Assert.Contains("an input only", ex.Message); + Assert.Contains("an input parameter (mode IN)", ex.Message); } // A value given to the parameter makes the member an InputOutput: the check covers it. [Fact] - public static async Task AnInputOutputMember_OnAnInputOnlyParameter_Throws() + public static async Task AnInputOutputMember_OnAnInputParameter_Throws() { MetaConnection connection = With(One("IN")); var ex = await Assert.ThrowsAsync(async () => await new NamedCommand(connection, Proc(), "@total").AddParam("total", 5).ExecuteOutputAsync(Token)); - Assert.Contains("an input only", ex.Message); + Assert.Contains("an input parameter (mode IN)", ex.Message); Assert.Equal(0, connection.Executed); } @@ -279,7 +279,7 @@ public static async Task ACallOnAPooledConnection_AsksOnce_AndChecksBeforeTheRun var ex = await Assert.ThrowsAsync(async () => await new NamedPooledCommand(pool, procedure, "@total").ExecuteOutputAsync(Token)); - Assert.Contains("an input only", ex.Message); + Assert.Contains("an input parameter (mode IN)", ex.Message); Assert.Equal(0, connection.Executed); Assert.Equal(1, connection.SchemaCalls); @@ -343,7 +343,7 @@ public static async Task AProcedureWhoseNamesAreNotKnown_NeverAsks() // ---- metadata is optional: a failed read never fails a call --------------------- [Fact] - public static async Task AProviderWithoutTheCollection_IsKnownAsUnknown_AndNotAskedAgain() + public static async Task AProviderWithoutTheCollection_IsNotAskedAgain() { MetaConnection connection = With(null); string procedure = Proc(); @@ -472,7 +472,7 @@ static async Task Read(DataTable table, params string[] names } [Fact] - public static async Task OnlyTheExactModeIN_IsInputOnly() + public static async Task OnlyTheExactModeIN_IsModeIn() { ParameterMetadata metadata = await Read( Table( @@ -484,7 +484,7 @@ public static async Task OnlyTheExactModeIN_IsInputOnly() ("dbo", 6, null, "@f", null)), "@a", "@b", "@c", "@d", "@e", "@f"); - Assert.Equal("YNNNNN", string.Concat(Enumerable.Range(0, 6).Select(i => metadata.IsInputOnly(i) ? 'Y' : 'N'))); + Assert.Equal("YNNNNN", string.Concat(Enumerable.Range(0, 6).Select(i => metadata.IsModeIn(i) ? 'Y' : 'N'))); } [Fact] @@ -517,19 +517,19 @@ public static async Task RowsAreMatchedByName_TheFirstRowWins_AndOrdinalZeroIsSk ("dbo", 4, "IN", "@unknown", 3)), "@other", "@total"); - Assert.True(metadata.IsInputOnly(0)); + Assert.True(metadata.IsModeIn(0)); Assert.Equal(1, metadata.Scale(0)); - Assert.False(metadata.IsInputOnly(1)); + Assert.False(metadata.IsModeIn(1)); Assert.Equal(5, metadata.Scale(1)); } [Fact] - public static async Task AParameterWithNoRow_IsNotInputOnlyAndHasNoScale() + public static async Task AParameterWithNoRow_IsNotModeInAndHasNoScale() { ParameterMetadata metadata = await Read(One("IN"), "@total", "@missing"); - Assert.True(metadata.IsInputOnly(0)); - Assert.False(metadata.IsInputOnly(1)); + Assert.True(metadata.IsModeIn(0)); + Assert.False(metadata.IsModeIn(1)); Assert.Equal(ParameterMetadata.NoScale, metadata.Scale(1)); } @@ -540,14 +540,14 @@ public static async Task AMissingScaleColumn_StillGivesTheMode_AndAMissingModeCo noScale.Columns.Remove("NUMERIC_SCALE"); ParameterMetadata mode = await Read(noScale, "@total"); Assert.True(mode.IsKnown); - Assert.True(mode.IsInputOnly(0)); + Assert.True(mode.IsModeIn(0)); Assert.Equal(ParameterMetadata.NoScale, mode.Scale(0)); DataTable noMode = One("IN", 3); noMode.Columns.Remove("PARAMETER_MODE"); ParameterMetadata scale = await Read(noMode, "@total"); Assert.True(scale.IsKnown); - Assert.False(scale.IsInputOnly(0)); + Assert.False(scale.IsModeIn(0)); Assert.Equal(3, scale.Scale(0)); } @@ -559,7 +559,7 @@ public static async Task AMissingOrdinalColumn_MatchesByNameOnly() ParameterMetadata metadata = await Read(table, "@total"); - Assert.True(metadata.IsInputOnly(0)); + Assert.True(metadata.IsModeIn(0)); } [Fact] @@ -611,7 +611,7 @@ public static async Task TheFirstAnswerKept_IsTheOneThatStays() await ProcedureParameterMetadata.EnsureAsync(With(One("INOUT")), "dbo.p", set, Token); Assert.Same(first, set.Metadata); - Assert.True(first.IsInputOnly(0)); + Assert.True(first.IsModeIn(0)); } [Fact] @@ -625,6 +625,6 @@ public static async Task TwoCallsThatBothAsk_KeepOneAnswer() ParameterMetadata kept = set.Metadata!; await ProcedureParameterMetadata.EnsureAsync(connection, "dbo.p", set, Token); Assert.Same(kept, set.Metadata); - Assert.True(kept.IsInputOnly(0)); + Assert.True(kept.IsModeIn(0)); } } diff --git a/Tests/Open.Database.Extensions.Core.Tests/OutputParameterLocalDbTests.cs b/Tests/Open.Database.Extensions.Core.Tests/OutputParameterLocalDbTests.cs index a662a1a2..27033f65 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/OutputParameterLocalDbTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/OutputParameterLocalDbTests.cs @@ -191,11 +191,11 @@ public static async Task ALaterStatementsError_IsTheProvidersError() Assert.Equal(245, ex.Number); } - // An output member on an input-only parameter throws before the run (the procedure's mode is known), and the kept names are + // An output member on an input parameter (mode IN) throws before the run (the procedure's mode is known), and the kept names are // forgotten: after the procedure is changed the next call reads them again and finds the renamed parameter. The provider's own // error (8162) for unknown metadata is in OutputMetadataLocalDbTests. [Fact] - public static async Task AnOutputOnAnInputOnlyParameter_ThrowsBeforeTheRun_AndTheNamesAreForgotten() + public static async Task AnOutputOnAnInputParameter_ThrowsBeforeTheRun_AndTheNamesAreForgotten() { LocalDbFixture.SkipUnlessAvailable(); using LocalDbFixture.Scratch procedure = Procedure("@post_id int", "select 1;"); @@ -204,7 +204,7 @@ public static async Task AnOutputOnAnInputOnlyParameter_ThrowsBeforeTheRun_AndTh var ex = await Assert.ThrowsAsync(async () => await connection.StoredProcedure(name).ExecuteOutputAsync(Token)); Assert.Contains("NewPostId.PostId reads '@post_id' of dbo.", ex.Message); - Assert.Contains("an input only", ex.Message); + Assert.Contains("an input parameter (mode IN)", ex.Message); Assert.Contains("Declare the parameter OUTPUT in the procedure, or remove the member", ex.Message); LocalDbFixture.Execute($"alter procedure dbo.[{procedure.Name}] @p_post_id int output as set @p_post_id = 5"); diff --git a/docsite/articles/expressive-commands.md b/docsite/articles/expressive-commands.md index 82d884e4..98220601 100644 --- a/docsite/articles/expressive-commands.md +++ b/docsite/articles/expressive-commands.md @@ -211,7 +211,7 @@ A result set and the return value are readable on the chain; output parameters a - **Types.** A `DateTime` is sent as `datetime2`, a `DateOnly` as `date` and a `TimeOnly` as `time` (nullable forms too; a `TimeOnly` keeps all seven fraction digits); a `string` or `byte[]` with size -1, so the whole value comes back; a `char` with size 1, so it reads one character (a `char(3)` holding `XYZ` reads `X`: use a `string` for more). A `decimal` needs `[Column(TypeName = "decimal(10,2)")]` (positional records: `[property: Column(...)]`); without it the call throws before it runs. - **One value.** `ExecuteOutputAsync("name")` reads one parameter, found the way `AddParam` finds its name (with or without `@`: exactly, else ignoring case, else ignoring case and underscores, else without a common prefix such as `p_`; the exact name wins, and a name that fits two parameters equally well throws, so pass the exact one); `"ReturnValue"` there names a declared parameter, not the return code. A `decimal` needs its precision and scale: `ExecuteOutputAsync("total", 19, 4)` for a `decimal(19,4)` (`decimal?` for NULL), or `ExecuteOutputDecimalAsync("total", 19, 4)`, which returns a `decimal?`. Without them `ExecuteOutputAsync(name)` throws before it runs, and only a `decimal` takes them. - **Not delivered.** An Output parameter still empty after the call means the response never completed: the call throws `InvalidOperationException`, never a NULL. -- **Checked before the run.** When the procedure's parameter metadata is available (SQL Server, and any provider whose ADO.NET `ProcedureParameters` schema collection answers), a member on a parameter the procedure declares as input only, and a `decimal` member whose scale is lower than the parameter's, throw `InvalidOperationException` before the command runs, naming the member, the parameter and the fix. A higher scale passes, and no precision is checked. The metadata only checks: it never supplies a value, a type or a scale. It is read once per procedure, only for a call that reads an output parameter. Without it the call runs and the provider's own error applies: for an output on an input-only parameter on SQL Server, 8162. +- **Checked before the run.** When the procedure's parameter metadata is available (SQL Server, and any provider whose ADO.NET `ProcedureParameters` schema collection answers), a member on a parameter whose mode is `IN` (an input parameter), and a `decimal` member whose scale is lower than the parameter's, throw `InvalidOperationException` before the command runs, naming the member, the parameter and the fix. A higher scale passes, and no precision is checked. The metadata only checks: it never supplies a value, a type or a scale. It is read once per procedure, only for a call that reads an output parameter. Without it the call runs and the provider's own error applies. One value, and a decimal with its precision and scale: @@ -226,7 +226,7 @@ There is no blocking form. Known limits: - An InputOutput parameter whose outputs never arrive keeps the value sent: that case cannot be told from a real answer. - A parameter added with a null value (`AddParam(name, (int?)null, type)`) that is also an output member is sent as InputOutput too, so a lost output cannot be told from a NULL. For a pure output, add no value; add one only when the procedure reads it. - A member on a parameter the procedure does not declare `OUTPUT` throws before the run when the metadata is known, and is the provider's error when it is not (SQL Server: 8162). -- If the procedure was changed with `ALTER` while the process runs, the remembered metadata is out of date until a call fails. An input-only parameter made an output gives one `InvalidOperationException`, and the next call passes; an output made input-only reaches the provider's error, and the call after it is checked. If the procedure was changed, call again. A lower scale made by the change rounds silently until a call fails or the process restarts. +- If the procedure was changed with `ALTER` while the process runs, the remembered metadata is out of date until it is dropped (by a failed call, or by eviction). A parameter changed from `IN` to an output gives one `InvalidOperationException`, and the next call passes; one changed from an output to `IN` reaches the provider's error, and the call after it is checked. If the procedure was changed, call again. A scale lowered by the change is not caught: the value rounds silently, as it does without metadata, until the remembered metadata is dropped. - A read of the metadata that the provider refuses (System.Data.SqlClient inside a pending transaction, for example) lets the call run, and is read again on every call. A call that keeps failing a check removes the remembered metadata for every caller of that procedure, so their next call reads it again. - SqlClient reports an error after the outputs are set, and a cancel while the command runs, with its own `SqlException`. - **A legacy `datetime` output can differ from a row in the last digits.** Outputs are sent as `datetime2`, so a `datetime` that stores `.997` (ticks of 1/300 second) reads back into a `DateTime` as `.9966667`, where a row read of the same value gives `.997`. `smalldatetime` and `datetime2` arrive exactly. To get what a row read gives, pass the value through `new SqlDateTime(value).Value` (from `System.Data.SqlTypes`), or have the procedure declare the output as `datetime2(3)`. Feeding such a value back in as an input lands on the same stored tick. diff --git a/docsite/articles/release-notes.md b/docsite/articles/release-notes.md index 2a42e40f..3bb6c113 100644 --- a/docsite/articles/release-notes.md +++ b/docsite/articles/release-notes.md @@ -7,7 +7,7 @@ Version 11 is `11.0.0-rc.16`. For moving a 10.x codebase, read [Coming from earl ### Changes since rc.16 - **Generated row readers for `DbQuery` too.** A plain `Map()` on a `DbQuery`, a `DbQuery` or a query bound with `Using` now gets its row reader written at build time, as on a command or a reader; before, it used the runtime map. The runtime map's conversions are therefore no longer applied there: see [Generated readers](mapping.md#generated-readers) for the differences and the switch. -- **New: output parameters are checked against the procedure's metadata before the run.** When the database reports a procedure's parameters (the ADO.NET `ProcedureParameters` schema collection, which SQL Server answers), a call that reads output parameters throws `InvalidOperationException` before the command runs if a member reads a parameter the procedure declares as input only, or if a `decimal` member declares a scale lower than the parameter's (the value would be rounded); a higher scale passes, and no precision is checked. The metadata is read once per procedure, only for such a call, and only checks: it never fills a value, a type or a scale. Without it the call runs as before and the provider's own error applies (SQL Server: 8162 for an output on an input-only parameter). See [Output parameters](expressive-commands.md#output-parameters). +- **New: output parameters are checked against the procedure's metadata before the run.** When the database reports a procedure's parameters (the ADO.NET `ProcedureParameters` schema collection, which SQL Server answers), a call that reads output parameters throws `InvalidOperationException` before the command runs if a member reads a parameter whose mode is `IN` (an input parameter), or if a `decimal` member declares a scale lower than the parameter's (the value would be rounded); a higher scale passes, and no precision is checked. The metadata is read once per procedure, only for such a call, and only checks: it never fills a value, a type or a scale. Without it the call runs as before and the provider's own error applies (SQL Server: 8162 for an output on an `IN` parameter). See [Output parameters](expressive-commands.md#output-parameters). - **Fixed: a cancel during `AsAsyncEnumerable(pool)`.** On a `DbDataReader`, `AsAsyncEnumerable(arrayPool)` with a pool (the form that reads every column) did not pass its token to `ReadAsync`, so a read the provider cancelled threw out of the enumeration. It now ends the enumeration quietly with the rows already yielded, as the other forms do. - **Fixed: `CreateCommand` on a `SqlTransaction` that has no connection throws `InvalidOperationException`.** The SQL Server package threw `ArgumentNullException` named `connection`; it now reports "Transaction has no connection.", as the core package does. `CreateTextCommand` and `CreateStoredProcedureCommand` follow. - **Removed: parameter directions on the fluent chain.** `AddParam` and `AddParamIf` no longer take a `ParameterDirection`; `AddReturnParam` is gone, and `AddParam(name, direction)`, `AddParamIf(condition, name, direction)`, `AddParam(name, type)` and `AddParamIf(condition, name, type)` are now compile errors that say what to do instead. The forms that took a direction after the value, `AddParam(name, value, ParameterDirection)` and `AddParam(name, value, type, direction)` (the SQL Server forms with a database type and a direction too), fail to compile with the compiler's own argument error, without a message of their own: use the raw `AddParameter` inside `ExecuteAsync(command => ...)`, or read the output with `ExecuteOutputAsync`. A parameter on the chain is an input. To set a direction, use `ExecuteAsync(command => ...)` with the raw `AddParameter`, `AddParameterType` and `AddReturnParameter` extensions. Calls that never passed a direction compile unchanged, with one exception: a constant zero of type `byte` on the SQL Server command, `AddParam(name, (byte)0)`, used to bind silently to the direction overload and is now an ambiguous-call error (CS0121); pass a variable, or give the database type, `AddParam(name, value, SqlDbType.TinyInt)`. `Param` has no `direction` constructor parameter and no `Direction` property.