diff --git a/Source/Core/BoundCall.cs b/Source/Core/BoundCall.cs index a9a429d7..5ee9d1b2 100644 --- a/Source/Core/BoundCall.cs +++ b/Source/Core/BoundCall.cs @@ -339,8 +339,8 @@ public static ValueTask ExecuteOutputAsync( call.Call.Params, cancellationToken); /// - /// Runs the write and returns the stored procedure's return code, converted - /// to . + /// Runs the write and returns its return code, converted to + /// . /// /// /// @@ -349,7 +349,7 @@ public static ValueTask ExecuteOutputAsync( /// The bound call. /// /// A task that represents the asynchronous operation; its result is the return code. - /// Before any connection is used: is a model, the call's definition is text (it has no return code), is a value, or a capture on the call reads the return code too. + /// Before any connection is used: is a model, is a value, or a capture on the call reads the return code too. /// is canceled. public static ValueTask ExecuteReturnAsync( this BoundCall call, @@ -357,19 +357,12 @@ public static ValueTask ExecuteReturnAsync( { // All checked at the call, before a task exists or a connection is used. ReturnCode.ThrowUnlessScalar(); - DbQuery definition = call.Call.Definition; - if (definition.Kind != CommandType.StoredProcedure) - { - throw new InvalidOperationException( - $"ExecuteReturnAsync<{Shape.TypeName(typeof(T))}>() reads a stored procedure's return code, but this call's definition is {OutputDefinitions.Describe(definition)}, and a text definition has no return code: the provider reports 0. " - + "Declare the definition with DbNonQuery.Procedure(name) to read the return code."); - } // A capture of the return code and this would read it twice. call.Captures?.ThrowIfReturnBeside(cancellationToken); return DbQueryRunner.ReturnAsync( - definition, + call.Call.Definition, call.Call.SourceCore, call.Call.Params, call.Captures, @@ -378,15 +371,11 @@ public static ValueTask ExecuteReturnAsync( // ---- captures: per kind, so a call made from Output has none ---- - // Returns the call with one more capture, checked at the call. A - // definition's kind never changes, so the return code is checked here. + // Returns the call with one more capture, checked at the call. static BoundCall WithCapture( BoundCall call, ICaptureSource source) - => new( - call.Call, - CaptureSet.WithOnDefinition( - call.Captures, source, call.Call.Definition.Kind)); + => new(call.Call, CaptureSet.WithOnQuery(call.Captures, source)); // The call with the capture, and the capture's handle for the caller. static BoundCall WithCapture( diff --git a/Source/Core/Capture.cs b/Source/Core/Capture.cs index 8eef33d5..a562dcec 100644 --- a/Source/Core/Capture.cs +++ b/Source/Core/Capture.cs @@ -463,37 +463,6 @@ CaptureSet Added(ICaptureSource source) return new([.. Sources, source], OnQuery); } - /// - /// Returns the captures of a definition's call with one more, as - /// does. - /// - /// - /// A definition's kind never changes, so a capture of the return code is - /// checked here, at the call; a command's type can, so a command checks - /// it when the run starts. - /// - /// The captures so far, or - /// . - /// The new capture. - /// The definition's kind. - /// The new set. - /// The capture reads the - /// return code of a definition that is not a stored procedure, or reads - /// what another capture reads. - public static CaptureSet WithOnDefinition( - CaptureSet? set, - ICaptureSource source, - CommandType kind) - { - if (source.ReadsReturn && kind != CommandType.StoredProcedure) - { - throw new InvalidOperationException( - CaptureMessages.NotProcedure(source)); - } - - return WithOnQuery(set, source); - } - /// /// Returns what a run of a query fills when the query has captures of its /// own and its command has some too: the command's, then the query's. @@ -622,12 +591,6 @@ public override Exception Refuse( return exception; } - /// Makes the exception for a capture that reads the return code of - /// a command that is not a stored procedure. - /// The exception. - public InvalidOperationException NotProcedure() - => new(CaptureMessages.NotProcedure(ReturnReader!)); - /// Refuses a call that reads the return code itself when a capture /// reads it too: the capture is completed with the refusal. /// The token that governs the call. @@ -1027,18 +990,6 @@ public const string ToListInstead public const string ExecuteNonQueryInstead = "ExecuteNonQueryAsync instead of ExecuteNonQuery"; - /// - /// Why a text command cannot give a return code, in the messages that - /// need a stored procedure. - /// - public const string NoReturnCodeInText - = "a text command has no return code, " - + "and the provider would report 0. "; - - /// The fix of a message that needs a stored procedure. - public const string CallByName - = "Call the procedure by name with StoredProcedure(…), "; - /// The last resort of a message about a capture. public const string OrRemoveTheCapture = "or remove the capture."; @@ -1127,20 +1078,6 @@ public static string CancelOnEarlyStop(CaptureSet set) + "a canceled command does not give its output parameters. " + "Remove CancelOnEarlyStop(), or remove the capture."; - public static string NotProcedure(ICaptureSource source) - => source.Kind == CaptureKind.Return - ? $"{source.Display} needs a stored procedure: " - + NoReturnCodeInText - + CallByName - + OrRemoveTheCapture - : $"{source.Display} reads the return code into the ReturnValue " - + $"member of {source.Model}, " - + "which needs a stored procedure: " - + NoReturnCodeInText - + CallByName - + "or give the member [Column(\"name\")] to read an output " - + "parameter instead."; - public static string NotDelivered(ICaptureSource source) => (source.Kind == CaptureKind.Return ? $"The return code of {source.Display} was never delivered" diff --git a/Source/Core/Compatibility/DictionaryTryAdd.cs b/Source/Core/Compatibility/DictionaryTryAdd.cs new file mode 100644 index 00000000..200c3b53 --- /dev/null +++ b/Source/Core/Compatibility/DictionaryTryAdd.cs @@ -0,0 +1,28 @@ +#if NETSTANDARD2_0 +namespace System.Collections.Generic; + +// Polyfill for Dictionary.TryAdd, which is in-box from +// netstandard2.1. On every other target framework this file is not compiled, +// so the in-box instance method is the one that is called. +internal static class DictionaryTryAddExtensions +{ + /// + /// Adds the key and value if the key is not in the dictionary yet. + /// + /// if the pair was added; if the key was already there, in which case the dictionary is unchanged. + public static bool TryAdd( + this Dictionary dictionary, + TKey key, + TValue value) + where TKey : notnull + { + if (dictionary.ContainsKey(key)) + { + return false; + } + + dictionary.Add(key, value); + return true; + } +} +#endif diff --git a/Source/Core/Core/RowMap.cs b/Source/Core/Core/RowMap.cs index 52dfe7da..146e0083 100644 --- a/Source/Core/Core/RowMap.cs +++ b/Source/Core/Core/RowMap.cs @@ -910,11 +910,7 @@ ValueMappingException OrderMismatch(Slot slot, string expected, string found) if (filled[p] || _named[p] || _slots[p].ColumnName is not null || _slots[p].NotMapped) continue; index ??= new(_columns.Length, new IgnoreCaseAndUnderscores()); -#if NETSTANDARD2_0 - if (!index.ContainsKey(name)) index.Add(name, p); -#else index.TryAdd(name, p); -#endif } return index; diff --git a/Source/Core/DbNonQuery.cs b/Source/Core/DbNonQuery.cs index 8a02d02e..40851a23 100644 --- a/Source/Core/DbNonQuery.cs +++ b/Source/Core/DbNonQuery.cs @@ -71,7 +71,7 @@ public DbNonQuery Params() /// The model the outputs are read into. /// The definition, to be run with ExecuteOutputAsync. /// - /// has no member to read, is a single value, has a member without its type name, or reads the return code of a text definition. + /// has no member to read, is a single value, or has a member without its type name. /// The message names the definition and the model. /// public OutputDbNonQuery Output() @@ -248,7 +248,7 @@ public BoundParams Using( /// The model the outputs are read into. /// The definition, to be run with ExecuteOutputAsync. /// - /// has no member to read, is a single value, has a member without its type name, or reads the return code of a text definition. + /// has no member to read, is a single value, or has a member without its type name. /// The message names the definition and the model. /// public OutputDbNonQuery Output() diff --git a/Source/Core/ExpressiveCommandBase.Capture.cs b/Source/Core/ExpressiveCommandBase.Capture.cs index 1178d741..52b18d08 100644 --- a/Source/Core/ExpressiveCommandBase.Capture.cs +++ b/Source/Core/ExpressiveCommandBase.Capture.cs @@ -234,9 +234,9 @@ async ValueTask ExecuteCapturedAsync( // Checked here, not at the capture call: the command's type can be // set after a capture is added. - if (run.Set.ReadsReturn && Type != CommandType.StoredProcedure) + if (run.Set.ReadsReturn) { - throw run.Set.NotProcedure(); + ThrowIfNoReturnCode(); } return await ExecutePlainAsync( diff --git a/Source/Core/ExpressiveCommandBase.Output.cs b/Source/Core/ExpressiveCommandBase.Output.cs index 74fbd863..ad001d26 100644 --- a/Source/Core/ExpressiveCommandBase.Output.cs +++ b/Source/Core/ExpressiveCommandBase.Output.cs @@ -29,8 +29,9 @@ public abstract partial class ExpressiveCommandBase /// /// - /// A member named ReturnValue reads a stored procedure's return code. + /// A member named ReturnValue reads the return code. /// + /// /// /// /// @@ -44,8 +45,8 @@ public abstract partial class ExpressiveCommandBase /// /// Before anything runs: has no member to read, is a single value, has a member without its type name or a member of a type - /// that has no database type, or reads the return code of a command that is not a stored procedure. - /// Before the command executes: a member matches no parameter, two match one, or the procedure declares a parameter a ReturnValue member would also match. + /// that has no database type. + /// Before the command executes: a member matches no parameter, two match one, or the procedure or text declares a parameter a ReturnValue member would also match. /// /// /// @@ -59,9 +60,12 @@ public ValueTask ExecuteOutputAsync( CancellationToken cancellationToken = default) { OutputLayout layout = OutputLayout.Get(); - if (layout.HasReturnValue) ThrowUnlessProcedure(layout); RefuseBesideCaptures("ExecuteOutputAsync<{0}>()", layout.Model); + if (layout.HasReturnValue) + { + ThrowIfNoReturnCode(); + } // Thrown synchronously, not through the returned task. CancellationToken.ThrowIfCancellationRequested(); @@ -336,23 +340,28 @@ static bool ReadsOutputs(TState state) && ((OutputRun)(object)state!).Layout.HasOutputParameter; /// - /// Throws when a model reads the return code of a command that is not a stored procedure. + /// Throws when this command, run by its provider package, has no return code to read. /// - /// The model's layout. - /// The command is not a stored procedure. - void ThrowUnlessProcedure(OutputLayout layout) + /// + /// Called before anything runs by each call that reads the return code. Does nothing here: the provider reports what ADO.NET reports for the command's type. + /// + /// The provider package refuses a return code on this command. + internal virtual void ThrowIfNoReturnCode() { - if (Type == CommandType.StoredProcedure) return; + } - string display = OutputLayout.ReturnValue; - foreach (OutputMember member in layout.Members) + // A call that is not itself a capture's run: a capture on the command + // completes with the refusal, as it does for any refusal at the call. + void ThrowIfNoReturnCodeAtCall() + { + try { - if (member.IsReturnValue) display = member.Display; + ThrowIfNoReturnCode(); + } + catch (InvalidOperationException ex) when (_captures is { } captures) + { + throw captures.Refuse(ex); } - - throw new InvalidOperationException( - $"{display} reads a stored procedure's return code, but the command is not a stored procedure (it is {Type}), and a command of another type has no return code to read: the provider reports 0. " - + "Set CommandType.StoredProcedure to call a procedure, or read an output parameter (declared @name OUTPUT in the text) into a member of another name."); } // The matching and the adding of the output parameters are one path for diff --git a/Source/Core/ExpressiveCommandBase.cs b/Source/Core/ExpressiveCommandBase.cs index e11fdf15..125da88c 100644 --- a/Source/Core/ExpressiveCommandBase.cs +++ b/Source/Core/ExpressiveCommandBase.cs @@ -1571,6 +1571,9 @@ void IExecuteCommandSync.Execute(Action action) T IExecuteCommandSync.Execute(Func transform) => Execute(transform); + void IExecuteCommandSync.ThrowIfNoReturnCode() + => ThrowIfNoReturnCodeAtCall(); + ValueTask IExecuteCommand.ExecuteAsync(Func handler) => ExecuteAsync(handler); @@ -1984,6 +1987,7 @@ ValueTask IExecuteReader.ExecuteReaderAsync(Func // A capture of the return code and this would read it twice: refused, // and the capture completed with the refusal. _captures?.ThrowIfReturnBeside(cancellationToken); + ThrowIfNoReturnCodeAtCall(); // Thrown synchronously, not through the returned task: // both tokens are checked before anything is linked (a capture on the @@ -2023,10 +2027,9 @@ public ValueTask ExecuteReturnAsync( { // A model cannot hold the return code: thrown at the call, before anything runs. ReturnCode.ThrowUnlessScalar(); - return ReturnAsync(cancellationToken); + return ReturnAsync(ExecuteReturnAsync(cancellationToken)); } - async ValueTask ReturnAsync(CancellationToken cancellationToken) - => RowMap.ConvertScalar( - await ExecuteReturnAsync(cancellationToken).ConfigureAwait(false)); + static async ValueTask ReturnAsync(ValueTask run) + => RowMap.ConvertScalar(await run.ConfigureAwait(false)); } diff --git a/Source/Core/Extensions/DataRecord.cs b/Source/Core/Extensions/DataRecord.cs index d0ed53af..4174d42d 100644 --- a/Source/Core/Extensions/DataRecord.cs +++ b/Source/Core/Extensions/DataRecord.cs @@ -244,6 +244,9 @@ static IEnumerable EnumerateValuesFromOrdinalsCore(IDataRecord record, i /// An enumerable of mappings, where each name is the column's actual name in the record. /// /// Use or instead when a missing column should be an error. + /// + /// A name that more than one column has gets the first of those columns, as does. Alias the column in SQL to read another. + /// /// /// or is . /// A requested name is , empty, or white space. It can be thrown when the result is enumerated rather than when this method is called. @@ -260,20 +263,35 @@ public static IEnumerable MatchingOrdinals(this IDataRecord recor if (sort) { var requested = new HashSet(requestedNames, StringComparer.OrdinalIgnoreCase); - // Return the actual columns, in record order, whose names were requested. - return actual.Where(m => requested.Contains(m.Name)); + // Return the first actual column, in record order, of each requested name. + return FirstColumnOfEachRequestedName(actual, requested); } else { // Map actual columns case-insensitively so the requested order can be preserved. + // The first column of a name stays; a later column of the same name is skipped. var actualColumns = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (ColumnOrdinal m in actual) - actualColumns[m.Name] = m; + actualColumns.TryAdd(m.Name, m); return requestedNames .Where(actualColumns.ContainsKey) .Select(c => actualColumns[c]); } + static IEnumerable FirstColumnOfEachRequestedName( + IEnumerable actual, + HashSet requested) + { + var seen = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (ColumnOrdinal m in actual) + { + if (requested.Contains(m.Name) && seen.Add(m.Name)) + { + yield return m; + } + } + } + static IEnumerable ValidateColumnNames(IEnumerable names) { foreach (string c in names) diff --git a/Source/Core/MappedQuery.Capture.cs b/Source/Core/MappedQuery.Capture.cs index 7be09144..f3644b66 100644 --- a/Source/Core/MappedQuery.Capture.cs +++ b/Source/Core/MappedQuery.Capture.cs @@ -60,15 +60,12 @@ public MappedQueryCore WithCapture(ICaptureSource source) EnsureCommand(); if (_call.IsBound) { - // A definition's kind is immutable, so the return code is checked - // here; a command's type can change, so its check is at the run. // A query from a definition has no command: its captures are its // own, with nothing to combine and no reader to refuse. return new( null, _call, _source, _skip, _take, Options, Config, - CaptureSet.WithOnDefinition( - _captures as CaptureSet, source, _call.Definition.Kind)); + CaptureSet.WithOnQuery(_captures as CaptureSet, source)); } if (_command is not ICaptureRunner runner) diff --git a/Source/Core/Output.docs.xml b/Source/Core/Output.docs.xml index 2384cbcd..f10cf747 100644 --- a/Source/Core/Output.docs.xml +++ b/Source/Core/Output.docs.xml @@ -64,6 +64,14 @@ + + + A return code comes from a stored procedure called by name. + On a text command the provider reports what ADO.NET reports (SQL Server: 0, and RETURN n in text is a server error); the command of the SQL Server package refuses a text command with , a definition run on a SqlConnection does not. + From text, read the code with EXEC @r = dbo.p and an output parameter. + + + A named form never reads the return code: "ReturnValue" there names a declared parameter, @@ -177,7 +185,6 @@ At the call: is a (use the form with a precision and scale) or a model that cannot be read from output parameters (no member to set); - or a ReturnValue member reads the return code of a definition that is not a stored procedure; 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). @@ -232,17 +239,14 @@ The type the return code converts to: , a nullable or wider integer, or an enum. The capture: await it after the terminal. - At the call: is a model; or the definition is text, which has no return code; - or another capture reads the return code. + At the call: is a model, or another capture reads the return code. The command, which carries the capture; its next async terminal fills it. - - A capture of the return code (CaptureReturn, or a model with a ReturnValue member) is refused when the run starts if the command is not a stored procedure, which has no return code: the type can be set after the capture, so the run, not the call, decides. - + The capture adds its output parameters when the terminal runs the command, and is complete when the terminal's task is. A query that Map made from this command uses the command's captures too; the first run, by either route, fills them. @@ -262,8 +266,8 @@ A copy of the query that carries the capture; its async terminal fills it. + - A capture of the return code is refused when the run starts if the command is not a stored procedure, and at the call on a text definition. The capture belongs to the copy, which also fills every capture its command has when the run starts, including one added to the command after this call; the first run fills them. A query made from a definition has no command: it fills its own captures. A stream or a buffer takes the command's captures when it is made: a capture added to the command after that is not part of its run. @@ -400,8 +404,9 @@ - is checked when this is called, and so is the definition: a text definition has no return code, and a capture of the return code on the call would read it twice. + is checked when this is called, and so is a capture of the return code on the call, which would read it twice. A capture of output parameters beside it runs. + diff --git a/Source/Core/OutputBinding.cs b/Source/Core/OutputBinding.cs index c5b329fe..cd7c33c0 100644 --- a/Source/Core/OutputBinding.cs +++ b/Source/Core/OutputBinding.cs @@ -96,8 +96,9 @@ public static void Resolve( OutputMember member = layout.Members[i]; if (member.IsReturnValue) { - // Only a stored procedure gets here (checked at the call): no - // declared parameter may also answer to the name. + // The return code is read, not a parameter: no declared + // parameter (a procedure's, or a marker of a text) may also + // answer to the name. // CaptureReturn asks for the return code itself, not by a // member's name, so nothing can be mistaken for it. if (!member.Named diff --git a/Source/Core/OutputDbNonQuery.cs b/Source/Core/OutputDbNonQuery.cs index ab21fc81..ce8fef46 100644 --- a/Source/Core/OutputDbNonQuery.cs +++ b/Source/Core/OutputDbNonQuery.cs @@ -39,14 +39,6 @@ public static DbQuery Model(DbQuery definition) OutputArguments.ModelCall(OutputForm.Definition, model), static () => OutputLayout.Get(OutputForm.Definition)); - if (layout.HasReturnValue && definition.Kind != CommandType.StoredProcedure) - { - string member = layout.Members.First(static m => m.IsReturnValue).Display; - throw new InvalidOperationException( - $"Output<{model}>() on {Describe(definition)} reads the return code through {member}, but a text definition has no return code: the provider reports 0. " - + "Declare the definition with DbNonQuery.Procedure(name), or give the member [Column(\"name\")] to read an output parameter declared @name OUTPUT in the text."); - } - return definition.WithOutput(layout); } diff --git a/Source/Core/Synchronous/Interfaces.cs b/Source/Core/Synchronous/Interfaces.cs index 66f5d8ed..6b90cc7a 100644 --- a/Source/Core/Synchronous/Interfaces.cs +++ b/Source/Core/Synchronous/Interfaces.cs @@ -37,6 +37,9 @@ internal interface IExecuteCommandSync : IExecuteCommand /// Executes the command, passes it to the transform and returns the result. T Execute(Func transform); + + /// Throws before anything runs when the provider package knows the command has no return code to read. + void ThrowIfNoReturnCode(); } /// An that can run work against its typed command on the calling thread. diff --git a/Source/Core/Synchronous/SyncExpressiveExtensions.cs b/Source/Core/Synchronous/SyncExpressiveExtensions.cs index 89b8aaeb..dc6f52aa 100644 --- a/Source/Core/Synchronous/SyncExpressiveExtensions.cs +++ b/Source/Core/Synchronous/SyncExpressiveExtensions.cs @@ -92,21 +92,32 @@ public static T ExecuteScalar( /// does, and returns the value of /// that parameter. /// + /// + /// + /// /// The command to execute. /// The value from the return parameter. public static object? ExecuteReturn(this IExecuteCommand command) - => command.AsSync().Execute(static cmd => + { + IExecuteCommandSync sync = command.AsSync(); + sync.ThrowIfNoReturnCode(); + + return sync.Execute(static cmd => { IDbDataParameter returnParameter = cmd.AddReturnParameter(); cmd.ExecuteNonQuery(); return returnParameter.Value; }); + } /// /// Executes the command with a return parameter, as /// does, and returns the value of /// that parameter converted to . /// + /// + /// + /// /// The type to convert the value to. /// The command to execute. /// diff --git a/Source/MSSqlClient/ExpressiveSqlCommand.cs b/Source/MSSqlClient/ExpressiveSqlCommand.cs index 325ee094..a839c012 100644 --- a/Source/MSSqlClient/ExpressiveSqlCommand.cs +++ b/Source/MSSqlClient/ExpressiveSqlCommand.cs @@ -12,6 +12,10 @@ namespace Open.Database.Extensions; /// /// Each execution takes a connection, opens it only if needed, runs the command, and releases the connection. A connection supplied directly is closed again only if this execution opened it and is never disposed; a connection from a factory is disposed, and one from a pool is given back. /// +/// +/// A return code comes from a stored procedure called by name: ExecuteReturn, ExecuteReturnAsync, a ReturnValue member of ExecuteOutputAsync<TOut>() and CaptureReturn throw on a text command, before anything runs. +/// From text, read the code with EXEC @r = dbo.p and an output parameter. +/// /// /// /// @@ -221,4 +225,27 @@ static async Task> ReadNamesAsync(SqlDataReader reader, C /// internal override bool IsLibraryCommand => GetType() == typeof(ExpressiveSqlCommand); + + /// + /// The message of the refusal of a return code on a text command. + /// + internal const string _noReturnCodeInText + = "A return code is read from a stored procedure called by name: " + + "on a text command SQL Server reports 0, and RETURN n in text is a " + + "server error. Call the procedure with StoredProcedure(name) to " + + "read its return code, or in text use EXEC @r = dbo.p with an " + + "output parameter."; + + /// + /// Throws when the command is not a stored procedure, which is the only + /// command SQL Server gives a return code. + /// + /// The command is text. + internal override void ThrowIfNoReturnCode() + { + if (Type != CommandType.StoredProcedure) + { + throw new InvalidOperationException(_noReturnCodeInText); + } + } } diff --git a/Source/MSSqlClient/Open.Database.Extensions.MSSqlClient.csproj b/Source/MSSqlClient/Open.Database.Extensions.MSSqlClient.csproj index d2669e15..85e1d3f6 100644 --- a/Source/MSSqlClient/Open.Database.Extensions.MSSqlClient.csproj +++ b/Source/MSSqlClient/Open.Database.Extensions.MSSqlClient.csproj @@ -31,4 +31,8 @@ + + + + diff --git a/Tests/Open.Database.Extensions.Core.Tests/CaptureDefinitionLocalDbTests.cs b/Tests/Open.Database.Extensions.Core.Tests/CaptureDefinitionLocalDbTests.cs index 08c69592..ee6af98c 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/CaptureDefinitionLocalDbTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/CaptureDefinitionLocalDbTests.cs @@ -405,22 +405,6 @@ public static async Task ExecuteReturnAsync_BesideAModelCapture_OnADefinition_Re Assert.Equal(new Page(8, 5), await model); } - [Fact] - public static void CaptureReturn_OnATextDefinition_ThrowsAtTheCaptureCall() - { - var connection = new SqlConnection("Server=nowhere"); - BoundCall call = DbNonQuery.Text("select 1").Using(connection); - MappedQuery query = DbQuery.Text("select 1").Map().Using(connection); - - var onWrite = Assert.Throws( - () => call.CaptureReturn(out DbCapture _)); - var onQuery = Assert.Throws( - () => query.CaptureReturn(out DbCapture _)); - - Assert.Contains("needs a stored procedure", onWrite.Message); - Assert.Contains("needs a stored procedure", onQuery.Message); - } - [Fact] public static void TheCaptureSet_IsPartOfTheEquality_ByReference_AndNoCaptureEqualityIsUnchanged() { diff --git a/Tests/Open.Database.Extensions.Core.Tests/CaptureTests.cs b/Tests/Open.Database.Extensions.Core.Tests/CaptureTests.cs index 466a1591..86ee7185 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/CaptureTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/CaptureTests.cs @@ -1163,44 +1163,6 @@ public static async Task ACommandTypeSetAfterCaptureReturn_IsHonored() Assert.Equal(7, await code); } - [Fact] - public static async Task AReturnCode_OnATextCommand_IsRefusedAtTheRun() - { - var c = new CaptureConnection(("", 7)); - var command = c.Command("select 1") - .CaptureReturn(out DbCapture code); - - Contains( - await Assert.ThrowsAsync( - async () => await command.ExecuteNonQueryAsync(Token)), - "CaptureReturn needs a stored procedure", - "StoredProcedure(…)"); - Contains( - await Assert.ThrowsAsync( - async () => await code), - "needs a stored procedure"); - Assert.Equal(0, c.Executed); - } - - [Fact] - public static async Task AModelWithAReturnValue_OnATextCommand_IsRefusedAtTheRun() - { - var c = new CaptureConnection(("Count", 1), ("", 7)); - MappedQuery query = c.Command("select 1") - .Map() - .CaptureOutput(out DbCapture touched); - - Contains( - await Assert.ThrowsAsync( - async () => await query.ToListAsync(Token)), - "the ReturnValue member of Touched, which needs a stored procedure"); - Contains( - await Assert.ThrowsAsync( - async () => await touched), - "which needs a stored procedure"); - Assert.Equal(0, c.Executed); - } - // ---- ExecuteReturnAsync with a model --------------------------------- // Takes the value task as an argument: the call under test must throw diff --git a/Tests/Open.Database.Extensions.Core.Tests/DuplicateColumnNameTests.cs b/Tests/Open.Database.Extensions.Core.Tests/DuplicateColumnNameTests.cs new file mode 100644 index 00000000..c07d7404 --- /dev/null +++ b/Tests/Open.Database.Extensions.Core.Tests/DuplicateColumnNameTests.cs @@ -0,0 +1,97 @@ +namespace Open.Database.Extensions.Tests; + +#nullable enable + +[ExcludeFromCodeCoverage] +public static class DuplicateColumnNameTests +{ + // SELECT 1 AS Id, 2 AS Id: GetOrdinal of a provider returns the first. + static IDataRecord PositionedRecord() + { + IDataReader reader = FakeReader.Create(["Id", "Id", "Name"], [1, 2, "x"]); + Assert.True(reader.Read()); + return reader; + } + + [Fact] + public static void GetOrdinalMapping_TakesTheFirstColumn() + => Assert.Equal( + [new ColumnOrdinal("Id", 0)], + PositionedRecord().GetOrdinalMapping(["Id"])); + + [Fact] + public static void MatchingOrdinals_Unsorted_TakesTheFirstColumn() + => Assert.Equal( + [new ColumnOrdinal("Id", 0)], + PositionedRecord() + .MatchingOrdinals(["Id"], sort: false) + .ToArray()); + + [Fact] + public static void MatchingOrdinals_Sorted_TakesTheFirstColumn() + => Assert.Equal( + [new ColumnOrdinal("Id", 0)], + PositionedRecord() + .MatchingOrdinals(["Id"], sort: true) + .ToArray()); + + [Fact] + public static void MatchingOrdinals_SortedAndUnsorted_GiveTheSameColumns() + { + IDataRecord record = PositionedRecord(); + + Assert.Equal( + record.MatchingOrdinals(["Id", "Name"], sort: false).ToArray(), + record.MatchingOrdinals(["Id", "Name"], sort: true).ToArray()); + } + + [Fact] + public static void MatchingOrdinals_Sorted_CanBeEnumeratedTwice() + { + IEnumerable matches + = PositionedRecord().MatchingOrdinals(["Id", "Name"], sort: true); + + ColumnOrdinal[] expected = [new("Id", 0), new("Name", 2)]; + + Assert.Equal(expected, matches.ToArray()); + Assert.Equal(expected, matches.ToArray()); + } + + [Fact] + public static void MatchingOrdinals_Unsorted_KeepsTheRequestedOrder() + => Assert.Equal( + [new ColumnOrdinal("Name", 2), new ColumnOrdinal("Id", 0)], + PositionedRecord() + .MatchingOrdinals(["Name", "Id"], sort: false) + .ToArray()); + + [Fact] + public static void MatchingOrdinals_Sorted_KeepsTheRecordOrder() + => Assert.Equal( + [new ColumnOrdinal("Id", 0), new ColumnOrdinal("Name", 2)], + PositionedRecord() + .MatchingOrdinals(["Name", "Id"], sort: true) + .ToArray()); + + [Fact] + public static void MatchingOrdinals_Unsorted_NamesDifferingInCase_AreOneName() + { + IDataReader reader = FakeReader.Create(["ID", "id"], [1, 2]); + Assert.True(reader.Read()); + + Assert.Equal( + [new ColumnOrdinal("ID", 0)], + reader.MatchingOrdinals(["Id"], sort: false).ToArray()); + } + + [Fact] + public static void MatchingOrdinals_Sorted_NamesDifferingInCase_AreOneName() + { + IDataReader reader = FakeReader.Create(["ID", "id"], [1, 2]); + Assert.True(reader.Read()); + + Assert.Equal( + [new ColumnOrdinal("ID", 0)], + reader.MatchingOrdinals(["Id"], sort: true).ToArray()); + } +} diff --git a/Tests/Open.Database.Extensions.Core.Tests/OutputDefinitionTests.cs b/Tests/Open.Database.Extensions.Core.Tests/OutputDefinitionTests.cs index 35957465..dc11132f 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/OutputDefinitionTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/OutputDefinitionTests.cs @@ -146,36 +146,12 @@ public static void ANameThatIsNotOne_IsRefusedWithTheFix(string? name) Assert.Contains("Output(\"total\")", ex.Message); } - [Fact] - public static void TheReturnCode_OnATextDefinition_IsRefusedWhenDeclared() - { - var ex = Assert.Throws( - () => DbNonQuery.Text("select 1").Output()); - - Assert.Contains("WithReturn.ReturnValue", ex.Message); - Assert.Contains("a text definition has no return code", ex.Message); - Assert.Contains("DbNonQuery.Procedure(name)", ex.Message); - } - [Fact] public static void TheReturnCode_OnAProcedureDefinition_IsAccepted() => Assert.NotNull( DbNonQuery.Procedure("dbo.AddPost").Output()); #pragma warning disable CA2012 // The call throws before it returns a ValueTask. - [Fact] - public static void ExecuteReturnAsync_OnATextDefinition_ThrowsAtTheCallBeforeAnyConnection() - { - var connection = new SqlConnection("Server=nowhere"); - BoundCall call = DbNonQuery.Text("select 1").Using(connection); - - var ex = Assert.Throws( - () => call.ExecuteReturnAsync(Token)); - - Assert.Contains("a text definition has no return code", ex.Message); - Assert.Contains("DbNonQuery.Procedure(name)", ex.Message); - Assert.Equal(System.Data.ConnectionState.Closed, connection.State); - } [Fact] public static void ExecuteReturnAsync_WithAModel_ThrowsAtTheCall() diff --git a/Tests/Open.Database.Extensions.Core.Tests/OutputParameterTests.cs b/Tests/Open.Database.Extensions.Core.Tests/OutputParameterTests.cs index 83d7aebe..96352e99 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/OutputParameterTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/OutputParameterTests.cs @@ -537,13 +537,6 @@ public static async Task ANotMappedMember_IsNotAnOutput() Assert.Equal("Count", Assert.Single(c.Last!.All).ParameterName); } - [Fact] - public static void AReturnValueMember_OnATextCommand_ThrowsAtTheCall() - => ThrowsAtTheCall( - c => c.Command("exec dbo.Touch @Count output").ExecuteOutputAsync(Token).AsTask(), - "Touched.ReturnValue reads a stored procedure's return code, but the command is not a stored procedure (it is Text)", - "Set CommandType.StoredProcedure to call a procedure"); - [Fact] public static void TheNamedForm_TakesOneValueOfAType_ThatNeedsNoDeclaration() { diff --git a/Tests/Open.Database.Extensions.Core.Tests/ReturnOnTextTests.cs b/Tests/Open.Database.Extensions.Core.Tests/ReturnOnTextTests.cs new file mode 100644 index 00000000..ffb41a50 --- /dev/null +++ b/Tests/Open.Database.Extensions.Core.Tests/ReturnOnTextTests.cs @@ -0,0 +1,241 @@ +#nullable enable + +namespace Open.Database.Extensions.Tests; + +// A return code read on a text command or a text definition: Core runs it and +// returns what the provider reports (here the value the fake sets on the +// return parameter), and does not check the command's type. A provider +// package that is certain can refuse it (the SQL Server package does). +// What stays refused: reading the return code twice, and a model for it. +[ExcludeFromCodeCoverage] +public static class ReturnOnTextTests +{ + static CancellationToken Token + => TestContext.Current.CancellationToken; + + public sealed record Row(int Id); + + public sealed record OnlyReturn(int ReturnValue); + + public sealed record Touched(int Count, int ReturnValue); + + static CaptureConnection Connection() + => new(("", 7)); + + // ---- a text definition ---- + + [Fact] + public static async Task ExecuteReturnAsync_OnATextDefinition_RunsAndReturnsTheCode() + { + var c = Connection(); + + int code = await DbNonQuery.Text("select 1") + .Using(c) + .ExecuteReturnAsync(Token); + + Assert.Equal(7, code); + Assert.Equal(1, c.Executed); + } + + [Fact] + public static void AReturnValueMember_OnATextDefinition_IsDeclared() + => Assert.NotNull(DbNonQuery.Text("select 1").Output()); + + [Fact] + public static async Task AReturnValueMember_OnATextDefinition_ReadsTheCode() + { + var c = Connection(); + + OnlyReturn model = await DbNonQuery.Text("select 1") + .Output() + .Using(c) + .ExecuteOutputAsync(Token); + + Assert.Equal(7, model.ReturnValue); + Assert.Equal(1, c.Executed); + } + + [Fact] + public static async Task CaptureReturn_OnATextDefinition_FillsTheCapture() + { + var c = Connection(); + var write = DbNonQuery.Text("select 1") + .Using(c) + .CaptureReturn(out DbCapture onWrite); + var query = DbQuery.Text("select 1") + .Map() + .Using(c) + .CaptureReturn(out DbCapture onQuery); + + await write.ExecuteNonQueryAsync(Token); + await query.ToListAsync(Token); + + Assert.Equal(7, await onWrite); + Assert.Equal(7, await onQuery); + Assert.Equal(2, c.Executed); + } + + [Fact] + public static async Task AModelWithAReturnValue_CapturedOnATextDefinition_FillsTheCapture() + { + var c = Connection(); + var write = DbNonQuery.Text("select 1") + .Using(c) + .CaptureOutput(out DbCapture model); + + await write.ExecuteNonQueryAsync(Token); + + Assert.Equal(7, (await model).ReturnValue); + } + + // ---- a text command ---- + + [Fact] + public static async Task AModelWithAReturnValue_OnATextCommand_ReadsTheCode() + { + var c = Connection(); + + OnlyReturn model = await c.Command("select 1") + .ExecuteOutputAsync(Token); + + Assert.Equal(7, model.ReturnValue); + Assert.Equal(1, c.Executed); + } + + [Fact] + public static async Task CaptureReturn_OnATextCommand_FillsTheCapture() + { + var c = Connection(); + var command = c.Command("select 1") + .CaptureReturn(out DbCapture code); + + await command.ExecuteNonQueryAsync(Token); + + Assert.Equal(7, await code); + Assert.Equal(1, c.Executed); + } + + [Fact] + public static async Task CaptureReturn_OnAMappedQueryOfATextCommand_FillsTheCapture() + { + var c = Connection(); + MappedQuery query = c.Command("select 1") + .Map() + .CaptureReturn(out DbCapture code); + + await query.ToListAsync(Token); + + Assert.Equal(7, await code); + Assert.Equal(1, c.Executed); + } + + [Fact] + public static async Task AModelWithAReturnValue_CapturedOnATextCommand_FillsTheCapture() + { + var c = Connection(); + var command = c.Command("select 1") + .CaptureOutput(out DbCapture model); + + await command.ExecuteNonQueryAsync(Token); + + Assert.Equal(7, (await model).ReturnValue); + } + + [Fact] + public static async Task AnOutputAndAReturnValue_CapturedOnATextQuery_FillBoth() + { + var c = new CaptureConnection(("Count", 1), ("", 7)); + MappedQuery query = c.Command("select 1") + .Map() + .CaptureOutput(out DbCapture touched); + + await query.ToListAsync(Token); + + Assert.Equal(new Touched(1, 7), await touched); + Assert.Equal(1, c.Executed); + } + + // ---- unchanged: these ran on text before ---- + + [Fact] + public static async Task ExecuteReturnAsync_OnATextCommand_ReturnsTheCode() + { + var c = Connection(); + + Assert.Equal(7, await c.Command("select 1").ExecuteReturnAsync(Token)); + Assert.Equal(7, await c.Command("select 1").ExecuteReturnAsync(Token)); + Assert.Equal(2, c.Executed); + } + + [Fact] + public static void ExecuteReturn_OnATextCommand_ReturnsTheCode() + { + var c = Connection(); + + Assert.Equal(7, c.Command("select 1").ExecuteReturn()); + Assert.Equal(7, c.Command("select 1").ExecuteReturn()); + Assert.Equal(2, c.Executed); + } + + // ---- unchanged: still refused ---- + + [Fact] + public static async Task ACaptureOfTheReturnCode_BesideExecuteReturnAsync_IsRefused() + { + var c = Connection(); + var command = c.Command("select 1") + .CaptureReturn(out DbCapture code); + + await Assert.ThrowsAsync( + async () => await command.ExecuteReturnAsync(Token)); + + await Assert.ThrowsAsync( + async () => await code); + Assert.Equal(0, c.Executed); + } + + [Fact] + public static async Task ACaptureOfTheReturnCode_BesideExecuteReturnAsync_OnADefinition_IsRefused() + { + var c = Connection(); + var call = DbNonQuery.Text("select 1") + .Using(c) + .CaptureReturn(out DbCapture code); + + await Assert.ThrowsAsync( + async () => await call.ExecuteReturnAsync(Token)); + + await Assert.ThrowsAsync( + async () => await code); + Assert.Equal(0, c.Executed); + } + +#pragma warning disable CA2012 // The call throws before it returns a ValueTask. + [Fact] + public static void AModelAsTheReturnCode_IsRefusedAtTheCall() + { + var c = Connection(); + + Assert.Throws( + () => c.Command("select 1").ExecuteReturnAsync(Token)); + Assert.Throws( + () => DbNonQuery.Text("select 1") + .Using(c) + .ExecuteReturnAsync(Token)); + Assert.Equal(0, c.Executed); + } +#pragma warning restore CA2012 + + // A text marker that a ReturnValue member's name also matches is + // ambiguous: the member reads one or the other. + [Fact] + public static async Task AReturnValueMember_BesideATextMarkerOfThatName_IsRefused() + { + var c = Connection(); + + await Assert.ThrowsAsync( + async () => await c.Command("exec dbo.Touch @ReturnValue output") + .ExecuteOutputAsync(Token)); + Assert.Equal(0, c.Executed); + } +} diff --git a/Tests/Open.Database.Extensions.Core.Tests/SqlServerReturnOnTextTests.cs b/Tests/Open.Database.Extensions.Core.Tests/SqlServerReturnOnTextTests.cs new file mode 100644 index 00000000..9af36d4a --- /dev/null +++ b/Tests/Open.Database.Extensions.Core.Tests/SqlServerReturnOnTextTests.cs @@ -0,0 +1,153 @@ +extern alias mssql; + +using Microsoft.Data.SqlClient; +using Expressive = mssql::Open.Database.Extensions.ExpressiveSqlCommand; + +#nullable enable + +namespace Open.Database.Extensions.Tests; + +// The SQL Server package refuses a return code on a text command, at the call +// and before a connection is opened or taken (Core, which does not, is in +// ReturnOnTextTests). A stored procedure still gives its return code, and a +// text definition on a SqlConnection is Core's: SQL Server reports 0 for it. +[ExcludeFromCodeCoverage] +[Collection("LocalDB DDL")] +public static class SqlServerReturnOnTextTests +{ + static CancellationToken Token + => TestContext.Current.CancellationToken; + + // Never opened: nothing here touches a server unless a test says so. + const string UnopenedConnectionString + = "Server=.;Integrated Security=true;Encrypt=False"; + + public sealed record OnlyReturn(int ReturnValue); + + static Expressive Text(SqlConnection connection) + => new(connection, CommandType.Text, "select 1"); + + static void AssertRefused(Exception? exception, SqlConnection connection) + { + var refused = Assert.IsType(exception); + Assert.Equal(Expressive._noReturnCodeInText, refused.Message); + Assert.Equal(ConnectionState.Closed, connection.State); + } + +#pragma warning disable CA2012 // The call throws before it returns a ValueTask. + [Fact] + public static void ExecuteReturnAsync_OnText_ThrowsAtTheCallBeforeAnyConnection() + { + using var connection = new SqlConnection(UnopenedConnectionString); + + AssertRefused( + Record.Exception( + () => Text(connection).ExecuteReturnAsync(Token)), + connection); + AssertRefused( + Record.Exception( + () => Text(connection).ExecuteReturnAsync(Token)), + connection); + } + + [Fact] + public static void ExecuteOutputAsync_WithAReturnValueMember_OnText_ThrowsAtTheCall() + { + using var connection = new SqlConnection(UnopenedConnectionString); + + AssertRefused( + Record.Exception( + () => Text(connection).ExecuteOutputAsync(Token)), + connection); + } +#pragma warning restore CA2012 + + [Fact] + public static void ExecuteReturn_OnText_Throws() + { + using var connection = new SqlConnection(UnopenedConnectionString); + + AssertRefused( + Record.Exception(() => Text(connection).ExecuteReturn()), + connection); + AssertRefused( + Record.Exception(() => Text(connection).ExecuteReturn()), + connection); + } + + [Fact] + public static async Task CaptureReturn_OnText_ThrowsAtTheRun_AndCompletesTheCapture() + { + await using var connection = new SqlConnection(UnopenedConnectionString); + var command = Text(connection) + .CaptureReturn(out DbCapture code); + + AssertRefused( + await Record.ExceptionAsync( + async () => await command.ExecuteNonQueryAsync(Token)), + connection); + AssertRefused( + await Record.ExceptionAsync(async () => await code), + connection); + } + +#pragma warning disable CA2012 // The call throws before it returns a ValueTask. + [Fact] + public static async Task AnOutputCapture_ThenExecuteReturnAsync_OnText_IsCompletedWithTheRefusal() + { + await using var connection = new SqlConnection(UnopenedConnectionString); + var command = Text(connection) + .CaptureOutput(out DbCapture total, "total"); + + AssertRefused( + Record.Exception(() => command.ExecuteReturnAsync(Token)), + connection); + AssertRefused( + await Record.ExceptionAsync(async () => await total), + connection); + } +#pragma warning restore CA2012 + + [Fact] + public static async Task AStoredProcedure_GivesItsReturnCode() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure + = LocalDbFixture.CreateProcedureWithBody( + "", + "set nocount on; return 5;", + "ode_rt"); + await using SqlConnection connection = LocalDbFixture.Create(); + await connection.OpenAsync(Token); + string name = "dbo." + procedure.Name; + + Assert.Equal( + 5, + await new Expressive(connection, CommandType.StoredProcedure, name) + .ExecuteReturnAsync(Token)); + Assert.Equal( + 5, + new Expressive(connection, CommandType.StoredProcedure, name) + .ExecuteReturn()); + } + + // What the remarks say of a text definition on a SqlConnection: SQL Server + // reports 0, and RETURN n in text is a server error. + [Fact] + public static async Task ATextDefinition_OnSqlServer_ReportsZero_AndAReturnInTextIsAServerError() + { + LocalDbFixture.SkipUnlessAvailable(); + await using SqlConnection connection = LocalDbFixture.Create(); + await connection.OpenAsync(Token); + + Assert.Equal( + 0, + await DbNonQuery.Text("select 1") + .Using(connection) + .ExecuteReturnAsync(Token)); + await Assert.ThrowsAsync( + async () => await DbNonQuery.Text("return 5") + .Using(connection) + .ExecuteReturnAsync(Token)); + } +} diff --git a/docsite/articles/expressive-commands.md b/docsite/articles/expressive-commands.md index 5b981fcd..3a1f44ed 100644 --- a/docsite/articles/expressive-commands.md +++ b/docsite/articles/expressive-commands.md @@ -203,7 +203,7 @@ To get the id an insert generated, select it in the same command and read it wit ### Return values and output parameters -`ExecuteReturnAsync()` runs the command and returns the value of its return-value parameter, which it adds itself. As with `ExecuteScalarAsync()`, the value is converted to `T` the way `Map()` converts a column: a NULL is `null` for a nullable `T` and throws `ValueMappingException` for a non-nullable value type. A token that is already cancelled fails the call with `OperationCanceledException` before anything runs. A SQL Server stored procedure returns an `int`, its `RETURN` code. Declared once, as a `DbNonQuery`, and read on each call (a text definition has no return code, so `ExecuteReturnAsync()` on one throws before any connection is used): +`ExecuteReturnAsync()` runs the command and returns the value of its return-value parameter, which it adds itself. As with `ExecuteScalarAsync()`, the value is converted to `T` the way `Map()` converts a column: a NULL is `null` for a nullable `T` and throws `ValueMappingException` for a non-nullable value type. A token that is already cancelled fails the call with `OperationCanceledException` before anything runs. A SQL Server stored procedure returns an `int`, its `RETURN` code. A return code comes from a stored procedure called by name: on a text command the provider reports what ADO.NET reports (SQL Server: 0, and `RETURN n` in text is a server error), and the SQL Server package's command refuses it with `InvalidOperationException`. From text, read the code with `EXEC @r = dbo.p` and an output parameter. Declared once, as a `DbNonQuery`, and read on each call: [!code-csharp[](../samples/OutputParameters.cs#sql_server_output_def_return)] @@ -227,7 +227,7 @@ An ad hoc command does the same: `ExecuteOutputAsync()` runs the command a - **Names.** A member finds its parameter as `AddParam(value)` does: through the four tiers when the names are known (a procedure's, or a text's `@name` markers, so `exec dbo.AddPost @id output` works too), else under its own name. `[Column("name")]` names the parameter exactly. A member that matches no parameter, or two members on one parameter, throw `InvalidOperationException` before the command runs. - **Direction.** A member whose parameter got a value (`AddParam`, `AddParams`) is sent as InputOutput; any other as Output. -- **Return code.** A member named `ReturnValue` reads a stored procedure's return code. On a text command it throws, and so does a procedure that declares a parameter that name would also match: name that member with `[Column]`. +- **Return code.** A member named `ReturnValue` reads the return code, which a stored procedure called by name gives (see [Return values and output parameters](#return-values-and-output-parameters) for text). A procedure or text that declares a parameter that name would also match throws: name that member with `[Column]`. - **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.** `Output("name")` on a definition (`ExecuteOutputAsync("name")` on a command) 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: `Output("total", 19, 4)` for a `decimal(19,4)`, or `OutputDecimal("total", 19, 4)`, which gives a `decimal?` (on a command, `ExecuteOutputAsync("total", 19, 4)` and `ExecuteOutputDecimalAsync("total", 19, 4)`). A NULL throws for a `decimal` and is `null` for a `decimal?`, so use the nullable form when the parameter can be NULL. Without the precision and scale a `decimal` throws when the definition is declared (before the command runs, on a command), and only a `decimal` takes them. `ExecuteReturnAsync()` checks its `T` when it is called. - **Not delivered.** An Output parameter still empty after the call means the response never completed: the call throws `InvalidOperationException`, never a NULL. @@ -286,7 +286,7 @@ A write and a scalar capture the same way, and their terminal returns the rows a [!code-csharp[](../samples/OutputParameters.cs#sql_server_output_def_capture_write)] -The return code needs a stored procedure. On a definition made with `DbNonQuery.Text` or `DbQuery.Text` the capture call throws; on a command, whose type can be set after the capture, it is checked when the command runs: +The return code comes from a stored procedure called by name; on text the provider reports what ADO.NET reports (see [Return values and output parameters](#return-values-and-output-parameters)): [!code-csharp[](../samples/OutputParameters.cs#sql_server_output_def_capture_return)] diff --git a/docsite/articles/release-notes.md b/docsite/articles/release-notes.md index 613b8762..e389f83b 100644 --- a/docsite/articles/release-notes.md +++ b/docsite/articles/release-notes.md @@ -6,6 +6,10 @@ Version 11 is `11.0.0-rc.18`. For moving a 10.x codebase, read [Coming from earl ### Changes since rc.17 +- **Changed: a return code read on a text command or a text definition no longer throws.** `ExecuteReturnAsync()` on a call of a `DbNonQuery.Text` definition, a `ReturnValue` member in `ExecuteOutputAsync()` on a text command or in `Output()` on a text definition, and `CaptureReturn` (or a captured model with a `ReturnValue` member) on a text command or a text definition threw `InvalidOperationException` ("needs a stored procedure"); they now run and give what the provider reports for a text command (SQL Server: 0, and `RETURN n` in text is a server error). A return code comes from a stored procedure called by name; from text, read it with `EXEC @r = dbo.p` and an output parameter. The command of the SQL Server package is the exception: the next item. +- **Changed: the SQL Server command refuses a return code on a text command.** On an `ExpressiveSqlCommand` whose type is text, `ExecuteReturnAsync()`, `ExecuteReturnAsync()` and `ExecuteReturn()` ran and gave 0 (`RETURN n` in text was a server error), and a `ReturnValue` member in `ExecuteOutputAsync()` and `CaptureReturn` threw `InvalidOperationException` with a message about stored procedures; all of them now throw `InvalidOperationException` before a connection is used, and the message says to call the procedure by name or to read the code with `EXEC @r = dbo.p` and an output parameter. A stored procedure called by name is unchanged, and so is a definition (`DbNonQuery.Text`) on a `SqlConnection`, which gives what SQL Server reports. +- **Changed: `ExecuteReturnAsync()` on a command refuses at the call.** A token that is already canceled, a capture of the return code beside the call, and the refusals above are thrown by the call itself, as `ExecuteReturnAsync()` already did, instead of by the returned task. +- **Changed: `MatchingOrdinals` takes the first column of a name that more than one column has.** With duplicate names in a result set, `MatchingOrdinals(sort: false)` gave the last of the columns and `MatchingOrdinals(sort: true)` gave all of them; both now give the first one, as `GetOrdinal` does, so the two modes agree and a name is one column. To read another column of the same name, alias it in SQL. - **Removed: the protected `PrepareCommand(TConnection)` and `ConnectionProvider` of `ExpressiveCommandBase`.** A class of your own that derives from `ExpressiveCommandBase` and called one of them no longer compiles. There is no replacement: a terminal builds the command when it runs, and a subclass that needs the connection, pool or factory keeps its own reference to what it passed to the base constructor. - **Changed: a procedure with a schema in its name has its parameter names read once per server and database, not once per source of connections.** A command or query of the library's own types that runs on a `DbConnection` which reports both its server (`DataSource`) and its `Database` finds the names of `dbo.get_author` there, whichever connection, factory, pool or transaction it was made from, so a connection created for each call no longer asks the database every time. The names are kept for the life of the process, for connections of one kind of provider (one connection class); up to 1024 procedures are shared, and past that new names stay with their source and nothing is dropped. A name without a schema, an answer of no names, a connection that reports no server or no database, and a command class of your own stay with the source of the connections, as before. The parameter modes and scales that the output-parameter check reads are shared the same way. What to know: every login of the process sees the names (a name that matches no parameter throws with the list of what the procedure declares); a server is told by the name it reports; a test fake that reports a fixed server name shares names with every other such fake, so give each its own name or none; and a failure that forgets the names forgets them for every connection. See [Parameter names are read once](expressive-commands.md#parameter-names-are-read-once). - **Fixed: a command made from a factory, a pool or a function read a procedure's parameter names again for every command.** A command made from a factory or pool that implements only the non-generic interface, or from a `Func` or a `Func` through `Command` or `StoredProcedure`, kept a separate cache per command, so the first run of every command asked the database for the names. Commands made from the same factory, pool or function now share one cache. Different factories, pools and functions still do not share. A function is told apart by the object its method belongs to: lambdas that capture nothing, in one class, are one source and share; a lambda that captures a local variable or a parameter and is built again for each call is a new source each time, so keep one factory for the application.