diff --git a/Source/Core/ExpressiveCommandBase.Output.cs b/Source/Core/ExpressiveCommandBase.Output.cs index 8ec985a3..32e1a7fd 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 ReadsOutputs(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. /// @@ -439,9 +453,76 @@ void ResolveOutputs(OutputRun run, NameSet? names) } } + // Only a procedure's own set has metadata, and only once it was read. + if (names is { Home: not null }) + { + CheckMetadata(layout, resolved, names, where); + } + run.Names = resolved; } + /// + /// Checks the output members against what the database says about the parameters they resolved to, when it said. + /// + /// + /// 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 a parameter whose mode is IN, or declares a scale lower than the procedure's. + /// + static void CheckMetadata( + OutputLayout layout, string?[] resolved, + NameSet names, string where) + { + if (names.Metadata is not { IsKnown: true } metadata) return; + + for (int i = 0; i < resolved.Length; i++) + { + OutputMember member = layout.Members[i]; + if (member.IsReturnValue + || resolved[i] is not { } name + || names.Find(name) is not { } entry) + { + continue; + } + + if (metadata.IsModeIn(entry.Index)) + { + throw new InvalidOperationException( + $"{member.Display} reads '{entry.Real}' of {where} as an " + + "output parameter, but the database reports that " + + "parameter as an input parameter (mode IN), so the " + + "call would be refused. Declare the parameter OUTPUT in the " + + "procedure, or remove the member. If the procedure was " + + "changed since it was first called, call again."); + } + + int declared = metadata.Scale(entry.Index); + if (member.Wire is { Type: DbType.Decimal, HasPrecision: true } wire + && declared > wire.Scale) + { + string fix = member.Named + ? $"Pass a scale of {declared} or more" + : "Declare the member as [Column(TypeName = " + + $"\"decimal({wire.Precision},{declared})\")] or higher"; + + throw new InvalidOperationException( + $"{member.Display} has the scale {wire.Scale}, but " + + $"'{entry.Real}' of {where} has the scale {declared}, " + + "so the value would be rounded to " + + $"{wire.Scale} decimal places. {fix}, or declare the " + + $"parameter in the procedure with the scale {wire.Scale}. " + + "If the procedure was changed since it was first " + + "called, call again."); + } + } + } + static InvalidOperationException NoOutputMatch( OutputMember member, ImmutableArray real, diff --git a/Source/Core/ExpressiveCommandBase.cs b/Source/Core/ExpressiveCommandBase.cs index 5009f7c3..cd3cc2b3 100644 --- a/Source/Core/ExpressiveCommandBase.cs +++ b/Source/Core/ExpressiveCommandBase.cs @@ -912,6 +912,86 @@ await GetProcedureParameterNamesAsync( cancellationToken) .ConfigureAwait(false)); + /// + /// 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) + { + ProcedureKey key = ProcedureKey(connection); + return ProcedureParameterNames.Find(NameCacheOwner, key) is { } kept + ? NeedsMetadata(kept) + ? NamesWithMetadataAsync(connection, kept, cancellationToken) + : new(kept) + : ReadNamesAndMetadataAsync(connection, key, cancellationToken); + } + + return ResolveDerivedNamesAsync(connection, cancellationToken); + } + + /// + /// 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 NamesWithMetadataAsync(connection, names, cancellationToken) + .ConfigureAwait(false) + : names; + } + + // Only a procedure's own set (a text's markers never have metadata), with + // names, that has not been asked yet. + static bool NeedsMetadata(NameSet names) + => names is { Home: not null, Names.Length: > 0, Metadata: null }; + + async ValueTask NamesWithMetadataAsync( + TConnection connection, + NameSet names, + CancellationToken cancellationToken) + { + await ProcedureParameterMetadata.EnsureAsync( + connection, Command, names, cancellationToken) + .ConfigureAwait(false); + + return names; + } + NameSet? WrittenNames() { if (_params is not { Count: > 0 } || Type != CommandType.Text || Command is not { Length: > 0 } text) return null; @@ -1311,9 +1391,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, - cancellationToken) + names = await ResolveRunNamesAsync( + single, state, cancellationToken) .ConfigureAwait(false); built = PrepareDerived(single, names, output: OutputOf(state)); } @@ -1351,7 +1430,8 @@ async ValueTask ExecutePlainAsync( { if (_hasDerivedParams || typeof(TState) == typeof(OutputRun)) { - leaseNames = await ResolveDerivedNamesAsync(lease.Connection, cancellationToken) + leaseNames = await ResolveRunNamesAsync( + lease.Connection, state, cancellationToken) .ConfigureAwait(false); leaseBuilt = PrepareDerived(lease.Connection, leaseNames, output: OutputOf(state)); } diff --git a/Source/Core/NameSet.cs b/Source/Core/NameSet.cs index fe5005c0..be335481 100644 --- a/Source/Core/NameSet.cs +++ b/Source/Core/NameSet.cs @@ -32,7 +32,8 @@ 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 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,6 +90,28 @@ 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 + // ProcedureParameterMetadata): a set that was never asked for them holds nothing + // more. It lives and dies with the set, so the cap on the sets + // (ProcedureParameterNames) bounds it too, and there is no timer. + ParameterMetadata? _metadata; + + /// + /// 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); + + /// + /// Keeps what the database said about each parameter, unless another call has kept its answer first. + /// + /// The metadata, aligned with . + // Two threads may both ask; the first answer stays, and the answers are + // the same. + public void KeepMetadata(ParameterMetadata metadata) + => Interlocked.CompareExchange(ref _metadata, metadata, null); + /// 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 7dc4c543..c04be8df 100644 --- a/Source/Core/Output.docs.xml +++ b/Source/Core/Output.docs.xml @@ -129,6 +129,16 @@ + + + When the call runs, before the command executes, and the procedure's parameter metadata is available: + a member reads a parameter whose mode the database reports as 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. + + + It is thrown after the command has run, so its effects have happened. @@ -159,6 +169,9 @@ or another capture reads the same outputs (a model reads them all: use one model capture, or named captures only) or the return code (remove one) (for a capture added to the command after the query was made, when the terminal or stream is called). + + + @@ -171,6 +184,9 @@ which needs its precision and scale (use the form that takes them); or another capture reads the same parameter. + + + @@ -187,6 +203,9 @@ At the call: is not or a of it; or another capture reads the same parameter. + + + @@ -199,6 +218,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 f657ffd6..31938cc1 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/ProcedureParameterMetadata.cs b/Source/Core/ProcedureParameterMetadata.cs new file mode 100644 index 00000000..295ff417 --- /dev/null +++ b/Source/Core/ProcedureParameterMetadata.cs @@ -0,0 +1,271 @@ +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. Anything the database did not report is "not +/// known", and a check never fails a call over what is not known. +/// +/// Whether each parameter's mode is IN, aligned with the names of a set. +/// The scale of each parameter, or . +sealed class ParameterMetadata(bool[] modeIn, int[] scales) +{ + /// 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 ParameterMetadata Unknown = new([], []); + + readonly bool[] _modeIn = modeIn; + readonly int[] _scales = scales; + + /// Gets whether anything is known. + public bool IsKnown + => !ReferenceEquals(this, Unknown); + + /// Gets whether the database reports a parameter's mode as IN. + /// The place of the parameter in the set's names. + /// 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]; +} + +/// +/// 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 ). +/// +/// +/// 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 ProcedureParameterMetadata +{ + const string Collection = "ProcedureParameters"; + + /// + /// Reads the metadata of a procedure's parameters into its set, unless the set + /// already holds them. + /// + /// + /// 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. + /// The procedure's set; its names are not empty. + /// + /// A task that represents the asynchronous operation. + public static async ValueTask EnsureAsync( + object connection, string procedure, + NameSet names, CancellationToken cancellationToken) + { + if (names.Metadata is not null) return; + + if (ProcedureSchemaNames.Restrictions(procedure) is not { } restrictions + || connection is not DbConnection db) + { + names.KeepMetadata(ParameterMetadata.Unknown); + return; + } + + ParameterMetadata metadata; + try + { +#if NET10_0_OR_GREATER + using DataTable table = await db.GetSchemaAsync( + Collection, restrictions, cancellationToken) + .ConfigureAwait(false); +#else + // DbConnection.GetSchemaAsync does not exist on the netstandard + // targets. + cancellationToken.ThrowIfCancellationRequested(); + using DataTable table = db.GetSchema(Collection, restrictions); +#endif + metadata = restrictions[1] is not null + ? ReadForSchema(table, names) + : ReadForAnySchema(table, 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. + metadata = ParameterMetadata.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 metadata and the next call + // asks. + return; + } + + names.KeepMetadata(metadata); + } + + /// + /// 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. + /// + /// The schema table. + /// The procedure's set. + /// The metadata; when the table tells nothing usable. + static ParameterMetadata ReadRows(DataTable table, NameSet names) + { + DataColumnCollection columns = table.Columns; + bool hasMode = columns.Contains("PARAMETER_MODE"); + bool hasScale = columns.Contains("NUMERIC_SCALE"); + if (!columns.Contains("PARAMETER_NAME") || !hasMode && !hasScale) + { + return ParameterMetadata.Unknown; + } + + bool hasOrdinal = columns.Contains("ORDINAL_POSITION"); + int count = names.Names.Length; + 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) + { + // 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 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(modeIn, scales) + : ParameterMetadata.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 ParameterMetadata.NoScale; + + try + { + int scale = Convert.ToInt32(value, CultureInfo.InvariantCulture); + return scale < 0 ? ParameterMetadata.NoScale : scale; + } + catch (Exception ex) when ( + ex is FormatException + or InvalidCastException + or OverflowException) + { + return ParameterMetadata.NoScale; + } + } +} diff --git a/Source/Core/ProcedureSchemaNames.cs b/Source/Core/ProcedureSchemaNames.cs index c5b1c915..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). - 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/OutputMetadataLocalDbTests.cs b/Tests/Open.Database.Extensions.Core.Tests/OutputMetadataLocalDbTests.cs new file mode 100644 index 00000000..0df0ce5f --- /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 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 +{ + 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 AnInputParameter_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 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 AnInputParameter_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 parameter (mode IN)", 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 AnInputOutputMemberOnAnInputParameter_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 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. + [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", 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", 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 metadata until a call fails). + [Fact] + public static async Task AFailedScaleCheck_PassesAfterTheProcedureIsAltered() + { + 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 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() + { + 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 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 metadata 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 parameter (mode IN)", 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 parameter (mode IN)", 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 metadata, 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..5f11d2ca --- /dev/null +++ b/Tests/Open.Database.Extensions.Core.Tests/OutputMetadataTests.cs @@ -0,0 +1,630 @@ +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]); + } + + 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) + { + 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 AnInputParameter_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 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); + + // 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, or declare the parameter in the procedure with the scale 2.", 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", 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_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 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_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 parameter (mode IN)", 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 ---------------------------------------------------- + + // 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 parameter (mode IN)", 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() + { + 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_IsNotAskedAgain() + { + 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 ProcedureParameterMetadata.EnsureAsync(With(table), "dbo.p", set, Token); + return set.Metadata!; + } + + [Fact] + public static async Task OnlyTheExactModeIN_IsModeIn() + { + ParameterMetadata metadata = 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 => metadata.IsModeIn(i) ? 'Y' : 'N'))); + } + + [Fact] + public static async Task TheScale_IsTakenWhenItIsAWholeNumberAtLeastZero() + { + ParameterMetadata metadata = 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, 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 + // ordinal 0 is the return value and never a parameter. + [Fact] + public static async Task RowsAreMatchedByName_TheFirstRowWins_AndOrdinalZeroIsSkipped() + { + ParameterMetadata metadata = 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(metadata.IsModeIn(0)); + Assert.Equal(1, metadata.Scale(0)); + Assert.False(metadata.IsModeIn(1)); + Assert.Equal(5, metadata.Scale(1)); + } + + [Fact] + public static async Task AParameterWithNoRow_IsNotModeInAndHasNoScale() + { + ParameterMetadata metadata = await Read(One("IN"), "@total", "@missing"); + + Assert.True(metadata.IsModeIn(0)); + Assert.False(metadata.IsModeIn(1)); + Assert.Equal(ParameterMetadata.NoScale, metadata.Scale(1)); + } + + [Fact] + public static async Task AMissingScaleColumn_StillGivesTheMode_AndAMissingModeColumn_StillGivesTheScale() + { + DataTable noScale = One("IN"); + noScale.Columns.Remove("NUMERIC_SCALE"); + ParameterMetadata mode = await Read(noScale, "@total"); + Assert.True(mode.IsKnown); + 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.IsModeIn(0)); + Assert.Equal(3, scale.Scale(0)); + } + + [Fact] + public static async Task AMissingOrdinalColumn_MatchesByNameOnly() + { + DataTable table = One("IN", 2); + table.Columns.Remove("ORDINAL_POSITION"); + + ParameterMetadata metadata = await Read(table, "@total"); + + Assert.True(metadata.IsModeIn(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(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] + public static async Task ANameTheLookupCannotRestrict_IsUnknown_WithoutAskingTheProvider() + { + MetaConnection connection = With(One("IN")); + var set = new NameSet(["@total"]); + + await ProcedureParameterMetadata.EnsureAsync(connection, "db.dbo.p", set, Token); + + Assert.Same(ParameterMetadata.Unknown, set.Metadata); + Assert.Equal(0, connection.SchemaCalls); + } + + [Fact] + public static async Task AConnectionThatIsNotADbConnection_IsUnknown_AndKept() + { + var set = new NameSet(["@total"]); + + await ProcedureParameterMetadata.EnsureAsync(Substitute.For(), "dbo.p", set, Token); + + Assert.Same(ParameterMetadata.Unknown, set.Metadata); + } + + [Fact] + public static async Task TheFirstAnswerKept_IsTheOneThatStays() + { + var set = new NameSet(["@total"]); + await ProcedureParameterMetadata.EnsureAsync(With(One("IN")), "dbo.p", set, Token); + ParameterMetadata first = set.Metadata!; + + set.KeepMetadata(ParameterMetadata.Unknown); + await ProcedureParameterMetadata.EnsureAsync(With(One("INOUT")), "dbo.p", set, Token); + + Assert.Same(first, set.Metadata); + Assert.True(first.IsModeIn(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 ProcedureParameterMetadata.EnsureAsync(connection, "dbo.p", set, Token), Token))); + + ParameterMetadata kept = set.Metadata!; + await ProcedureParameterMetadata.EnsureAsync(connection, "dbo.p", set, Token); + Assert.Same(kept, set.Metadata); + 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 904bab5d..27033f65 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 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_IsTheProvidersError_AndTheNamesAreForgotten() + public static async Task AnOutputOnAnInputParameter_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 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"); 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 76e023c7..98220601 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, 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 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: @@ -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). +- 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 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. - 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 67faabe4..3bb6c113 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 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.