From b5abd05e768b29009a76f8bf39c982168df85783 Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Wed, 2 Dec 2026 09:19:50 -0800 Subject: [PATCH 01/17] Definitions can declare and read output parameters A DbNonQuery definition now declares what it reads back: Output() for a model, Output(name) and Output(name, precision, scale) for one value, and OutputDecimal for a nullable decimal; the same on the typed-parameters form. The result is an OutputDbNonQuery that is bound with Using and run with ExecuteOutputAsync. The outputs are checked when the definition is declared, and every message names the definition and the model and gives the fix. A bound write also gets ExecuteReturnAsync, checked at the call. A definition's call matches and adds its outputs through the code the commands use (now OutputBinding), so the rules are the same. Named outputs of a definition match the way AddParam names match (exact, ignoring case, ignoring case and underscores, after a common prefix). The runner that fills captures from a definition's call is added here and used by the next change. Co-Authored-By: Claude Sonnet 5.5 --- Source/Core/BoundCall.cs | 65 +++ Source/Core/Capture.cs | 7 +- Source/Core/DbNonQuery.cs | 145 +++++- Source/Core/DbQuery.cs | 48 +- Source/Core/DbQueryRunner.Output.cs | 440 ++++++++++++++++ Source/Core/DbQueryRunner.cs | 2 +- Source/Core/ExpressiveCommandBase.Output.cs | 216 +------- Source/Core/Output.docs.xml | 55 ++ Source/Core/OutputBinding.cs | 339 +++++++++++++ Source/Core/OutputDbNonQuery.cs | 269 ++++++++++ Source/Core/OutputLayout.cs | 241 ++++++--- Source/Core/PublicAPI.Unshipped.txt | 28 ++ .../OutputDefinitionTests.cs | 476 ++++++++++++++++++ 13 files changed, 2040 insertions(+), 291 deletions(-) create mode 100644 Source/Core/DbQueryRunner.Output.cs create mode 100644 Source/Core/OutputBinding.cs create mode 100644 Source/Core/OutputDbNonQuery.cs create mode 100644 Tests/Open.Database.Extensions.Core.Tests/OutputDefinitionTests.cs diff --git a/Source/Core/BoundCall.cs b/Source/Core/BoundCall.cs index 332ae864..8d9ba582 100644 --- a/Source/Core/BoundCall.cs +++ b/Source/Core/BoundCall.cs @@ -11,6 +11,13 @@ namespace Open.Database.Extensions; /// public readonly struct NonQueryKind; +/// +/// Marks a chain that writes and reads output parameters: it ends in +/// ExecuteOutputAsync. +/// +/// What the outputs are read as. +public readonly struct OutputKind; + /// /// A scalar query or a write bound to where its connections come from, with /// the values added so far. @@ -287,4 +294,62 @@ public static ValueTask ExecuteNonQueryAsync( call.Call.SourceCore, call.Call.Params, cancellationToken); + + /// + /// Runs the write and reads its output parameters (and return code) as the + /// definition declared with Output. + /// + /// + /// + /// + /// What the outputs are read as. + /// The bound call. + /// + /// A task that represents the asynchronous operation; its result is the model, or the one value. + /// Before the command executes: an output matches no parameter, or two match one, or is a value, which is bound to nothing. + /// A value does not convert, or is NULL and the type does not take it. + /// is canceled. + public static ValueTask ExecuteOutputAsync( + this BoundCall> call, + CancellationToken cancellationToken = default) + => DbQueryRunner.OutputAsync( + call.Call.Definition, + call.Call.SourceCore, + call.Call.Params, + cancellationToken); + + /// + /// Runs the write and returns the stored procedure's return code, converted + /// to . + /// + /// + /// + /// + /// The type of the return code: a single value such as . + /// 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. + /// is canceled. + public static ValueTask ExecuteReturnAsync( + this BoundCall call, + CancellationToken cancellationToken = default) + { + // 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."); + } + + return DbQueryRunner.ReturnAsync( + definition, + call.Call.SourceCore, + call.Call.Params, + null, + cancellationToken); + } } diff --git a/Source/Core/Capture.cs b/Source/Core/Capture.cs index 17c77705..9bc663c6 100644 --- a/Source/Core/Capture.cs +++ b/Source/Core/Capture.cs @@ -873,7 +873,12 @@ static NamedCapture Decimal( scale, OutputForm.Capture); return new NamedCapture( - OutputValue.Shaped(name, precision, scale, display), + OutputValue.Shaped( + name, + precision, + scale, + display, + OutputForm.Capture), name, display); } diff --git a/Source/Core/DbNonQuery.cs b/Source/Core/DbNonQuery.cs index e712ce1a..bfeaaa07 100644 --- a/Source/Core/DbNonQuery.cs +++ b/Source/Core/DbNonQuery.cs @@ -26,7 +26,10 @@ namespace Open.Database.Extensions; /// For rows use , and for one value /// . /// The connection is opened late and released as releases -/// it. Output and return parameters are not supported. +/// it. +/// Outputs are read by (a model) or +/// (one value), and the return code by +/// ExecuteReturnAsync on the bound call. /// /// public sealed class DbNonQuery : IEquatable @@ -58,6 +61,76 @@ public DbNonQuery Params() where TParams : struct, IEquatable => new(_definition.Params()); + /// + /// Declares that the definition reads its output parameters and return code + /// into a . + /// + /// + /// + /// + /// 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. + /// The message names the definition and the model. + /// + public OutputDbNonQuery Output() + => new(OutputDefinitions.Model(_definition)); + + /// + /// Declares that the definition reads one output parameter, converted to + /// . + /// + /// + /// + /// + /// The type of the value. + /// + /// The definition, to be run with ExecuteOutputAsync. + /// is not a single value, is a , or has no database type. + public OutputDbNonQuery Output(string name) + => new(OutputDefinitions.Named(_definition, name)); + + /// + /// Declares that the definition reads one output + /// parameter of the given precision and scale, converted to + /// . + /// + /// + /// + /// + /// , or a of it. + /// + /// The precision, from 1 to 38. + /// The scale, up to the precision. + /// The definition, to be run with ExecuteOutputAsync. + /// is not a . + /// The precision or the scale is not a decimal's. + public OutputDbNonQuery Output( + string name, + byte precision, + byte scale) + => new(OutputDefinitions.Shaped(_definition, name, precision, scale)); + + /// + /// Declares that the definition reads one output + /// parameter of the given precision and scale, as a + /// of . + /// + /// + /// + /// + /// + /// The precision, from 1 to 38. + /// The scale, up to the precision. + /// The definition, to be run with ExecuteOutputAsync; NULL reads as . + /// The precision or the scale is not a decimal's. + public OutputDbNonQuery OutputDecimal( + string name, + byte precision, + byte scale) + => new(OutputDefinitions.Decimal(_definition, name, precision, scale)); + /// /// The write, bound. public BoundCall Using(DbConnection connection) @@ -170,4 +243,74 @@ public BoundParams Using( where TConnection : DbConnection // DbQuery.Using throws ArgumentNullException for a null source. => new(_definition.Using(factory)); + + /// + /// Declares that the definition reads its output parameters and return code + /// into a . + /// + /// + /// + /// + /// 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. + /// The message names the definition and the model. + /// + public OutputDbNonQuery Output() + => new(new DbQuery(OutputDefinitions.Model(_definition.Definition))); + + /// + /// Declares that the definition reads one output parameter, converted to + /// . + /// + /// + /// + /// + /// The type of the value. + /// + /// The definition, to be run with ExecuteOutputAsync. + /// is not a single value, is a , or has no database type. + public OutputDbNonQuery Output(string name) + => new(new DbQuery(OutputDefinitions.Named(_definition.Definition, name))); + + /// + /// Declares that the definition reads one output + /// parameter of the given precision and scale, converted to + /// . + /// + /// + /// + /// + /// , or a of it. + /// + /// The precision, from 1 to 38. + /// The scale, up to the precision. + /// The definition, to be run with ExecuteOutputAsync. + /// is not a . + /// The precision or the scale is not a decimal's. + public OutputDbNonQuery Output( + string name, + byte precision, + byte scale) + => new(new DbQuery(OutputDefinitions.Shaped(_definition.Definition, name, precision, scale))); + + /// + /// Declares that the definition reads one output + /// parameter of the given precision and scale, as a + /// of . + /// + /// + /// + /// + /// + /// The precision, from 1 to 38. + /// The scale, up to the precision. + /// The definition, to be run with ExecuteOutputAsync; NULL reads as . + /// The precision or the scale is not a decimal's. + public OutputDbNonQuery OutputDecimal( + string name, + byte precision, + byte scale) + => new(new DbQuery(OutputDefinitions.Decimal(_definition.Definition, name, precision, scale))); } diff --git a/Source/Core/DbQuery.cs b/Source/Core/DbQuery.cs index 84bd3b07..ae69e0db 100644 --- a/Source/Core/DbQuery.cs +++ b/Source/Core/DbQuery.cs @@ -37,14 +37,35 @@ namespace Open.Database.Extensions; /// public sealed class DbQuery : IEquatable { - DbQuery(string text, CommandType kind, int timeout, NameSet? textNames) + DbQuery( + string text, + CommandType kind, + int timeout, + NameSet? textNames, + OutputLayout? output = null) { CommandText = text; Kind = kind; Timeout = timeout; TextNames = textNames; + Output = output; } + /// + /// Gets the output parameters a definition made by Output reads, or + /// . + /// + // Immutable and kept by the definition, so every call of it shares one. + // A model, a name and a precision and scale are judged when the definition + // is declared. + internal OutputLayout? Output { get; } + + /// Returns the definition with the outputs it reads. + /// The outputs. + /// The new definition; this one is not changed. + internal DbQuery WithOutput(OutputLayout layout) + => new(CommandText, Kind, Timeout, TextNames, layout); + /// /// Gets the @name markers of a text definition, found once when it /// is made; for a procedure. @@ -180,7 +201,7 @@ static string Checked(string text, string paramName) /// /// The new definition. public DbQuery SetTimeout(ushort seconds) - => new(CommandText, Kind, seconds, TextNames); + => new(CommandText, Kind, seconds, TextNames, Output); /// /// Maps each row to a by column name (a single value such as @@ -382,15 +403,16 @@ public override int GetHashCode() public sealed class DbQuery where TParams : struct, IEquatable { - readonly DbQuery _definition; + // The definition without the type of its values. + internal DbQuery Definition { get; } - internal DbQuery(DbQuery definition) => _definition = definition; + internal DbQuery(DbQuery definition) => Definition = definition; /// Maps each row to a by column name, and returns the mapped definition. /// The type each row is mapped to. /// The mapped definition, whose parameters are the struct. public MappedDbQuery Map() - => new(_definition.Map()); + => new(Definition.Map()); /// Maps each row to a with a map the caller declared, and returns the mapped definition. /// The type each row is mapped to. @@ -399,7 +421,7 @@ public MappedDbQuery Map() // A bare null does not compile here (it also fits the selector overload): // write (RowMap?)null. public MappedDbQuery Map(RowMap? map) - => new(_definition.Map(map)); + => new(Definition.Map(map)); /// Maps each row with a selector, and returns the mapped definition. /// The type each row is mapped to. @@ -408,17 +430,17 @@ public MappedDbQuery Map(RowMap? map) /// is . public MappedDbQuery Map(Func selector) // DbQuery.Map throws ArgumentNullException for a null selector. - => new(_definition.Map(selector)); + => new(Definition.Map(selector)); /// /// The mapped definition, whose parameters are the struct. public MappedDbQuery AsObjectArrays() - => new(_definition.AsObjectArrays()); + => new(Definition.AsObjectArrays()); /// /// The mapped definition, whose parameters are the struct. public MappedDbQuery AsDictionaryRows() - => new(_definition.AsDictionaryRows()); + => new(Definition.AsDictionaryRows()); /// /// The scalar definition, whose parameters are the struct. @@ -428,14 +450,14 @@ public ScalarDbQuery Scalar() /// public DbQueryUsing Using(DbConnection connection) => new( - _definition, + Definition, connection ?? throw new ArgumentNullException( nameof(connection))); /// public DbQueryUsing Using(DbTransaction transaction) => new( - _definition, + Definition, transaction ?? throw new ArgumentNullException( nameof(transaction))); @@ -444,7 +466,7 @@ public DbQueryUsing Using( IDbConnectionPool pool) where TConnection : DbConnection => new( - _definition, + Definition, pool ?? throw new ArgumentNullException( nameof(pool))); @@ -453,7 +475,7 @@ public DbQueryUsing Using( IDbConnectionFactory factory) where TConnection : DbConnection => new( - _definition, + Definition, factory ?? throw new ArgumentNullException( nameof(factory))); } diff --git a/Source/Core/DbQueryRunner.Output.cs b/Source/Core/DbQueryRunner.Output.cs new file mode 100644 index 00000000..a1f24ab4 --- /dev/null +++ b/Source/Core/DbQueryRunner.Output.cs @@ -0,0 +1,440 @@ +namespace Open.Database.Extensions; + +// The runs of a definition's call that read output parameters: the outputs of +// an Output() definition, and the captures of a call. A call without +// either never comes here: it runs the methods of DbQueryRunner.cs, which are +// untouched. +static partial class DbQueryRunner +{ + /// + /// The layout of the return code of ExecuteReturnAsync<T>, per + /// type. + /// + /// The type of the return code. + static class ReturnOutput + { + public static readonly OutputLayout Layout = ReturnLayout( + $"ExecuteReturnAsync<{Shape.TypeName(typeof(T))}>()"); + } + + static OutputLayout ReturnLayout(string display) + => new( + display, + [new OutputMember(OutputLayout.ReturnValue, display, named: true)], + [0], + [OutputLayout.ReturnValue]); + + // The captures' values one after another, then the return code. + static OutputLayout WithReturn(OutputLayout layout) + { + string display = "ExecuteReturnAsync<>()"; + return new( + layout.Model, + layout.Members.Add( + new OutputMember(OutputLayout.ReturnValue, display, named: true)), + new int[layout.Members.Length + 1], + []); + } + + // As Make, then the outputs: resolved with the names and added after the + // values, which a value of the same name turns into InputOutput. + static DbCommand MakeWithOutput( + DbConnection connection, + DbTransaction? transaction, + DbQuery definition, + ParamList call, + NameSet? names, + OutputRun output) + { + DbCommand command = connection.CreateCommand(); + try + { + command.Transaction = transaction; + command.CommandText = definition.CommandText; + command.CommandType = definition.Kind; + if (definition.Timeout >= 0) + command.CommandTimeout = definition.Timeout; + call.BindAll(command, definition, names); + OutputBinding.Resolve( + output, + names, + definition.Kind, + definition.CommandText); + OutputBinding.Add( + command, + output, + new OutputBinding.CommandInputs(command)); + return command; + } + catch + { + command.Dispose(); + throw; + } + } + + /// + /// Asynchronously runs the output model or the one named output of a + /// definition made by Output. + /// + /// The type read. + /// The definition, with its outputs. + /// The connection, transaction, pool or factory. + /// The bound parameters. + /// + /// A task that represents the asynchronous operation; its result is the value. + public static ValueTask OutputAsync( + DbQuery definition, + object source, + ParamList call, + CancellationToken cancellationToken) + { + OutputLayout layout = definition.Output + ?? throw new InvalidOperationException( + "This call's definition declares no outputs: make it with Output()."); + return ExecuteWithOutputAsync( + definition, + source, + call, + new OutputRun(layout), + static (command, token) => command.ExecuteNonQueryAsync(token), + static (_, run) => run.Layout.Members[0].Named + ? Single(run) + : run.Map(), + cancellationToken); + } + + // A decimal read as decimal (not decimal?) refuses NULL with the message of + // the declared form. + static T Single(OutputRun run) + { + object? value = run.Value(0); + return typeof(T) == typeof(decimal) && value is DBNull + ? throw OutputArguments.DecimalNull( + run.Layout.Members[0].Name, + OutputForm.Definition) + : run.Single(); + } + + /// + /// Asynchronously runs a write and reads the return code. + /// + /// The type of the return code. + /// The definition. + /// The connection, transaction, pool or factory. + /// The bound parameters. + /// + /// The captures beside it, or . + /// A task that represents the asynchronous operation; its result is the return code. + public static ValueTask ReturnAsync( + DbQuery definition, + object source, + ParamList call, + CaptureSet? captures, + CancellationToken cancellationToken) + => captures is null + ? ExecuteWithOutputAsync( + definition, + source, + call, + new OutputRun(ReturnOutput.Layout), + static (command, token) => command.ExecuteNonQueryAsync(token), + static (_, run) => run.Single(), + cancellationToken) + : CapturedAsync( + definition, + source, + call, + captures, + readReturn: true, + static (command, token) => command.ExecuteNonQueryAsync(token), + static (_, run) => RowMap.ConvertScalar( + run.Value(run.Layout.Members.Length - 1)), + cancellationToken); + + /// Asynchronously runs a write that fills captures. + /// The definition. + /// The connection, transaction, pool or factory. + /// The bound parameters. + /// + /// The captures. + /// A task that represents the asynchronous operation; its result is the number of rows affected. + public static ValueTask NonQueryCapturedAsync( + DbQuery definition, + object source, + ParamList call, + CaptureSet captures, + CancellationToken cancellationToken) + => CapturedAsync( + definition, + source, + call, + captures, + readReturn: false, + static (command, token) => command.ExecuteNonQueryAsync(token), + static (count, _) => count, + cancellationToken); + + /// Asynchronously runs a scalar query that fills captures. + /// The type of the value. + /// The definition. + /// The connection, transaction, pool or factory. + /// The bound parameters. + /// The captures. + /// + /// A task that represents the asynchronous operation; its result is the value. + public static ValueTask ScalarCapturedAsync( + DbQuery definition, + object source, + ParamList call, + CaptureSet captures, + CancellationToken cancellationToken) + => CapturedAsync( + definition, + source, + call, + captures, + readReturn: false, + static (command, token) => command.ExecuteScalarAsync(token), + static (value, _) => RowMap.ConvertScalar( + value, + nameof(BoundCallExtensions.ExecuteScalarAsync)), + cancellationToken); + + // Claims the captures, runs, and completes every capture on every exit: + // the claim is the first statement, reached synchronously from the + // terminal. + static async ValueTask CapturedAsync( + DbQuery definition, + object source, + ParamList call, + CaptureHolder captures, + bool readReturn, + Func> execute, + Func convert, + CancellationToken cancellationToken) + { + CaptureRun run = captures.Start(cancellationToken); + try + { + OutputLayout layout = readReturn + ? WithReturn(run.Set.Layout) + : run.Set.Layout; + return await ExecuteWithOutputAsync( + definition, + source, + call, + new OutputRun(layout), + execute, + (value, output) => + { + // The conversion happens once, in each capture; its + // failure is the capture's, never the terminal's. + run.Deliver(output); + return convert(value, output); + }, + cancellationToken) + .ConfigureAwait(false); + } + catch (Exception ex) + { + run.Fail(ex); + throw; + } + finally + { + run.Backstop(); + } + } + + // A scalar and a write that read outputs: the run of ExecuteAsync, with + // the outputs resolved and copied off the command before it is disposed. + static async ValueTask ExecuteWithOutputAsync( + DbQuery definition, + object source, + ParamList call, + OutputRun output, + Func> execute, + Func convert, + CancellationToken cancellationToken) + { + // Cancelled awaited tasks throw, so this does too. + cancellationToken.ThrowIfCancellationRequested(); + output.Token = cancellationToken; + + TValue value; + // The run is a block of its own, so everything is released at its end. + { + Lease lease = await Lease + .OpenAsync(source, cancellationToken) + .ConfigureAwait(false); + await using var leaseDisposal = lease.ConfigureAwait(false); + NameSet? names = null; + DbCommand built; + try + { + names = await ResolveAsync( + definition, + source, + lease.Connection, + cancellationToken) + .ConfigureAwait(false); + built = MakeWithOutput( + lease.Connection, + lease.Transaction, + definition, + call, + names, + output); + } + catch (Exception ex) when (ProcedureParameterNames.ForgetUnlessCanceled(names, ex)) + { + throw; + } + +#if NETSTANDARD2_0 + using DbCommand command = built; +#else + DbCommand command = built; + await using var commandDisposal = command.ConfigureAwait(false); +#endif + try + { + value = await execute(command, cancellationToken) + .ConfigureAwait(false); + output.Snapshot(); + } + catch (DbException) when (ProcedureParameterNames.Forget(names)) + { + throw; + } + } + + return convert(value, output); + } + + /// + /// Asynchronously runs the query of a definition's call, passes the reader + /// to a function and fills captures. + /// + /// The type of the state passed to the function. + /// The type of the result. + /// The definition. + /// The connection, transaction, pool or factory. + /// The bound parameters. + /// + /// The captures: a set to claim, or a run a stream or a buffer has claimed. + /// The state to pass to . + /// The function that reads the reader. + /// The behavior to run the reader with. + /// A task that represents the asynchronous operation; its result is the result of . + public static async ValueTask RunCapturedAsync( + DbQuery definition, + object source, + ParamList call, + CaptureHolder captures, + TState state, + Func> transform, + CommandBehavior behavior, + CancellationToken cancellationToken) + { + CaptureRun run = captures.Start(cancellationToken); + try + { + // Cancelled awaited tasks throw, so this does too. + cancellationToken.ThrowIfCancellationRequested(); + var output = new OutputRun(run.Set.Layout) + { + Token = cancellationToken, + }; + + TResult result; + { + Lease lease = await Lease + .OpenAsync(source, cancellationToken) + .ConfigureAwait(false); + await using var leaseDisposal = lease.ConfigureAwait(false); + NameSet? names = null; + DbCommand built; + try + { + names = await ResolveAsync( + definition, + source, + lease.Connection, + cancellationToken) + .ConfigureAwait(false); + built = MakeWithOutput( + lease.Connection, + lease.Transaction, + definition, + call, + names, + output); + } + catch (Exception ex) when (ProcedureParameterNames.ForgetUnlessCanceled(names, ex)) + { + throw; + } + +#if NETSTANDARD2_0 + using DbCommand command = built; +#else + DbCommand command = built; + await using var commandDisposal = command.ConfigureAwait(false); +#endif + try + { + ReaderAbandon.ArmFor(transform, command); + CommandBehavior b = lease.Behavior(behavior); + try + { + // The reader is closed before the outputs are copied. + { +#if NETSTANDARD2_0 + using DbDataReader reader = await command + .ExecuteReaderAsync(b, cancellationToken) + .ConfigureAwait(false); +#else + DbDataReader reader = await command + .ExecuteReaderAsync(b, cancellationToken) + .ConfigureAwait(false); + await using var readerDisposal = reader.ConfigureAwait(false); +#endif + result = await transform(reader, state) + .ConfigureAwait(false); + } + + output.Snapshot(); + } + catch (OperationCanceledException) when (run.StoppedByConsumer) + { + // The consumer stopped early (a break, a dispose): the + // outputs are there because closing the reader drained + // the rest of the response, and the stream's own stop + // is not the caller's failure. + output.Snapshot(); + run.Deliver(output); + throw; + } + } + catch (DbException) when (ProcedureParameterNames.Forget(names)) + { + throw; + } + } + + run.Deliver(output); + return result; + } + catch (Exception ex) + { + run.Fail(ex); + throw; + } + finally + { + run.Backstop(); + } + } +} diff --git a/Source/Core/DbQueryRunner.cs b/Source/Core/DbQueryRunner.cs index 55a47d76..f47ed595 100644 --- a/Source/Core/DbQueryRunner.cs +++ b/Source/Core/DbQueryRunner.cs @@ -12,7 +12,7 @@ namespace Open.Database.Extensions; /// A connection of the caller's is closed again if the run opened it, and stays open if it was open; /// one from a factory is disposed and one from a pool is given back (see ). /// -static class DbQueryRunner +static partial class DbQueryRunner { /// /// Makes the exception thrown when a default (unbound) value is used. diff --git a/Source/Core/ExpressiveCommandBase.Output.cs b/Source/Core/ExpressiveCommandBase.Output.cs index 8ec985a3..8d8a39ae 100644 --- a/Source/Core/ExpressiveCommandBase.Output.cs +++ b/Source/Core/ExpressiveCommandBase.Output.cs @@ -350,222 +350,48 @@ void ThrowUnlessProcedure(OutputLayout layout) + "Set CommandType.StoredProcedure to call a procedure, or read an output parameter (declared @name OUTPUT in the text) into a member of another name."); } - /// - /// Names the command for the messages: a procedure's name, or the command text. - /// - /// The name. - string Where() - => Type == CommandType.StoredProcedure - ? Command - : "the command text"; - + // The matching and the adding of the output parameters are one path for + // commands and for the calls of definitions: OutputBinding. /// /// Resolves the parameter each output member stands for, while the call is built. /// - /// - /// It runs inside the build step, so a failure here forgets a procedure's kept names as any failure to build does. - /// An output member merges with an input of the same name (see ); only two outputs can collide. - /// /// The call's output parameters. /// The names of the procedure or of the text's markers, or when they are not known. - /// - /// A member matches no parameter, two match one, or a declared parameter matches a ReturnValue member. - /// void ResolveOutputs(OutputRun run, NameSet? names) - { - OutputLayout layout = run.Layout; - - // A text that is not interned has no remembered set: its markers are read for this call. - NameSet? real = names ?? (Type == CommandType.Text ? new NameSet(SqlTextParameters.Parse(Command)) : null); - bool known = real is { Names.Length: > 0 }; - string where = Where(); - run.Where = where; - - var resolved = new string?[layout.Members.Length]; - for (int i = 0; i < resolved.Length; i++) - { - 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. - // CaptureReturn asks for the return code itself, not by a - // member's name, so nothing can be mistaken for it. - if (!member.Named - && known - && real!.Match( - OutputLayout.ReturnValue, - Command, - member.Display) is { } declared) - { - throw new InvalidOperationException( - $"{member.Display} reads the return code, but {where} also declares the parameter '{declared}', which the name {OutputLayout.ReturnValue} matches, so it is unclear which one to read. " - + $"To read that parameter, give the member [Column(\"{declared}\")]; to read the return code, rename the procedure's parameter."); - } - - continue; - } + => OutputBinding.Resolve(run, names, Type, Command); - if (!known) - { - resolved[i] = member.Name; - continue; - } - - resolved[i] = (member.Exact - ? real!.Find(member.Name)?.Real - : member.Named - ? real!.MatchName( - member.Name, - Command, - member.Display, - "Pass the exact parameter name, naming one of those two.") - : real!.Match(member.Name, Command, member.Display)) - ?? throw NoOutputMatch(member, real.Names, where); - } - - // Two members that resolve to one parameter would read the same value under two meanings. - for (int i = 0; i < resolved.Length; i++) - { - if (resolved[i] is not { } first) continue; - for (int j = i + 1; j < resolved.Length; j++) - { - if (resolved[j] is not { } second || !DbQueryBinding.SameName(first, second)) continue; - - throw new InvalidOperationException( - $"{layout.Members[i].Display} and {layout.Members[j].Display} both resolve to the output parameter '{first}' of {where}, so one value would be read under two meanings. " - + (layout.Members[i].Named || layout.Members[j].Named - ? "Name one of them exactly as the parameter is declared (a name that matches exactly wins over one that matches only ignoring case or underscores), or drop one." - : "Name each member's parameter with [Column(\"name\")], or remove one of them.")); - } - } - - run.Names = resolved; - } - - static InvalidOperationException NoOutputMatch( - OutputMember member, - ImmutableArray real, - string where) - { - string declared = string.Join(", ", real); - if (member.Named) - { - // A decimal reaches here through the form that takes a precision and scale; any other type through the plain named form. - bool capture = member.Form == OutputForm.Capture; - string call = member.Wire!.Type == DbType.Decimal - ? capture - ? "Pass one of those names to CaptureOutput(name, " - + "precision, scale, out …) or CaptureOutputDecimal(name, " - + "precision, scale, out …)" - : "Pass one of those names to " - + "ExecuteOutputAsync(name, precision, scale) " - + "or ExecuteOutputDecimalAsync(name, precision, scale)" - : capture - ? "Pass one of those names to CaptureOutput(name, out …)" - : "Pass one of those names to ExecuteOutputAsync(name)"; - - return new( - $"{member.Display} is not a parameter of {where}, which declares: {declared}. " - + call + ", or add the parameter to the procedure (or its @name marker to the text)."); - } - - if (member.Exact) - { - return new( - $"{member.Display} names its parameter '{member.Name}' with [Column], but {where} declares no parameter of that name (it declares: {declared}). " - + "Change the [Column] name to one it declares, or add the parameter."); - } - - return new( - $"{member.Display} has no matching parameter on {where} (tried {string.Join(", ", ParameterNames.Candidates(member.Name))}; it declares: {declared}). " - + $"Add a parameter named {member.Name} to {where}, or name the member's parameter with [Column(\"name\")]."); - } - - // The provider's parameters are already on the command. An output member whose parameter was given a value turns that - // parameter into InputOutput (keeping a type the caller gave), so one name never yields two parameters. /// /// Adds the call's output parameters to the command, or turns the matching input into one. /// /// The command, with the provider's parameters. /// The call's output parameters, resolved. - /// The provider did not add a parameter that was sent. void AddOutputs(TCommand command, OutputRun run) - { - Debug.Assert(run.Names is not null, "The build step resolves the names first."); - OutputLayout layout = run.Layout; - List? send = ActiveSendList; - var parameters = new IDbDataParameter?[layout.Members.Length]; - bool[] pure = new bool[parameters.Length]; - for (int i = 0; i < parameters.Length; i++) - { - OutputMember member = layout.Members[i]; - if (member.IsReturnValue) - { - parameters[i] = command.AddReturnParameter(); - pure[i] = true; - continue; - } - - string name = run.Names![i]!; - OutputWire wire = member.Wire!; - if (Sent(send, name) is { } input) - { - IDbDataParameter parameter = Find(command, input.Name) - ?? throw new InvalidOperationException( - $"{member.Display} reads back the parameter '{input.Name}', which was given a value, but the command's provider did not add it to the command under that name, so there is nothing to read. " - + "Give the value under the name the provider keeps (AddParam(\"name\", value)), or do not give it a value so it is sent as an output only."); - parameter.Direction = ParameterDirection.InputOutput; - if (!input.Type.HasValue) parameter.DbType = wire.Type; - wire.Apply(parameter); - parameters[i] = parameter; - continue; - } - - IDbDataParameter output = command.CreateParameter(); - output.ParameterName = name; - output.Direction = ParameterDirection.Output; - output.DbType = wire.Type; - wire.Apply(output); - command.Parameters.Add(output); - parameters[i] = output; - pure[i] = true; - } - - run.Parameters = parameters; - run.Pure = pure; - } + => OutputBinding.Add(command, run, new SentInputs(ActiveSendList)); /// - /// Finds what is sent under a name, compared without the @ and ignoring case. + /// Finds an input among the values the command sends. /// /// What the call sends, or . - /// The name. - /// The parameter sent under it, or . - static Param? Sent(List? send, string name) + readonly struct SentInputs(List? send) : IInputLookup { - if (send is null) return null; - - foreach (Param p in send) + /// + public bool TryFind(string name, out string inputName, out bool typed) { - if (DbQueryBinding.SameName(p.Name, name)) return p; - } + if (send is not null) + { + foreach (Param p in send) + { + if (!DbQueryBinding.SameName(p.Name, name)) continue; - return null; - } + inputName = p.Name; + typed = p.Type.HasValue; + return true; + } + } - /// - /// Finds the provider's parameter of a name, compared without the @ and ignoring case. - /// - /// The command. - /// The name it was sent under. - /// The parameter, or . - static IDbDataParameter? Find(TCommand command, string name) - { - foreach (object? p in command.Parameters) - { - if (p is IDbDataParameter parameter && DbQueryBinding.SameName(parameter.ParameterName, name)) return parameter; + inputName = name; + typed = false; + return false; } - - return null; } } diff --git a/Source/Core/Output.docs.xml b/Source/Core/Output.docs.xml index 7dc4c543..099edc65 100644 --- a/Source/Core/Output.docs.xml +++ b/Source/Core/Output.docs.xml @@ -304,4 +304,59 @@ it belongs to no call, so every member throws. + + + + + The name of the output parameter, with or without its @, matched to the declared parameters the way the name of AddParam is: exactly, else ignoring case, else ignoring case and underscores, else after one common prefix such as p_ is removed from the declared name. + It is matched when the call runs; here it is only checked to be a name. + + is . + is empty, white space or a bare @. + + + + + The outputs are read as ExecuteOutputAsync<TOut>() reads them from a command: each member Map<TOut>() would read is an output parameter, a member named ReturnValue reads the return code of a stored procedure, and a member needs [Column(TypeName = "decimal(p,s)")]. + The model is checked when the definition is declared, not when it first runs: a definition in a field that cannot be read fails with a whose has the message, which names the definition and the model. + Matching the members to the declared parameters is checked when a call runs. + + + Values added to the call under a member's name make that parameter . + Run the call with ExecuteOutputAsync; a capture does not compile on it, because the call already reads every output. + + + Outputs without rows are declared on ; Scalar<T>() is on . + + + + + + + The type is checked when the definition is declared: a model, a (use the form with a precision and scale, which takes the shape) or a type with no database type throws there. + A read as decimal? gives for NULL. + + + + + + + The non-nullable form (Output<decimal>(name, p, s)) refuses a NULL when the call runs, with a message that says to read it as decimal?; the nullable forms (Output<decimal?>(name, p, s) and OutputDecimal) give . + Use the nullable form when the parameter can be NULL. + + + + + + The call is the one a command's ExecuteOutputAsync runs, with the same matching and wire rules. + NULL, conversion and delivery failures are thrown as the command's are, after the connection is released. + + + + + + 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. + A capture of output parameters beside it runs. + + diff --git a/Source/Core/OutputBinding.cs b/Source/Core/OutputBinding.cs new file mode 100644 index 00000000..1424ee1f --- /dev/null +++ b/Source/Core/OutputBinding.cs @@ -0,0 +1,339 @@ +using System.Diagnostics; + +namespace Open.Database.Extensions; + +/// +/// Finds the parameter that an input already has under a name, for the call +/// that is adding its outputs. +/// +/// +/// A command looks in the values it sends, a definition's call in the +/// parameters that were already put on the provider's command. A struct, so +/// the call that adds the outputs boxes nothing. +/// +interface IInputLookup +{ + /// + /// Finds the input sent under a name, compared without the @ and + /// ignoring case. + /// + /// The name. + /// The name it was sent under. + /// Whether the caller gave it a database type. + /// when an input has the name. + bool TryFind(string name, out string inputName, out bool typed); +} + +/// +/// Matches the output members of a call to the command's parameters and adds +/// them: the one path of the commands and of the definitions' calls. +/// +static class OutputBinding +{ + /// + /// Names the command for the messages: a procedure's name, or the + /// command text. + /// + /// The command's type. + /// The procedure's name or the text. + /// The name. + public static string Where(CommandType type, string commandText) + => type == CommandType.StoredProcedure + ? commandText + : "the command text"; + + /// + /// Resolves the parameter each output member stands for, while the call is + /// built. + /// + /// + /// It runs inside the build step, so a failure here forgets a procedure's + /// kept names as any failure to build does. + /// An output member merges with an input of the same name (see + /// ); only two outputs can collide. + /// + /// The call's output parameters. + /// The names of the procedure or of the text's markers, + /// or when they are not known. + /// The command's type. + /// The procedure's name or the text. + /// + /// A member matches no parameter, two match one, or a declared parameter + /// matches a ReturnValue member. + /// + public static void Resolve( + OutputRun run, + NameSet? names, + CommandType type, + string commandText) + { + OutputLayout layout = run.Layout; + + // A text that is not interned has no remembered set: its markers are + // read for this call. + NameSet? real = names + ?? (type == CommandType.Text + ? new NameSet(SqlTextParameters.Parse(commandText)) + : null); + bool known = real is { Names.Length: > 0 }; + string where = Where(type, commandText); + run.Where = where; + + var resolved = new string?[layout.Members.Length]; + for (int i = 0; i < resolved.Length; i++) + { + 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. + // CaptureReturn asks for the return code itself, not by a + // member's name, so nothing can be mistaken for it. + if (!member.Named + && known + && real!.Match( + OutputLayout.ReturnValue, + commandText, + member.Display) is { } declared) + { + throw new InvalidOperationException( + $"{member.Display} reads the return code, but {where} also declares the parameter '{declared}', which the name {OutputLayout.ReturnValue} matches, so it is unclear which one to read. " + + $"To read that parameter, give the member [Column(\"{declared}\")]; to read the return code, rename the procedure's parameter."); + } + + continue; + } + + if (!known) + { + resolved[i] = member.Name; + continue; + } + + resolved[i] = Find(member, real!, commandText) + ?? throw NoOutputMatch(member, real!.Names, where); + } + + // Two members that resolve to one parameter would read the same value + // under two meanings. + for (int i = 0; i < resolved.Length; i++) + { + if (resolved[i] is not { } first) continue; + for (int j = i + 1; j < resolved.Length; j++) + { + if (resolved[j] is not { } second + || !DbQueryBinding.SameName(first, second)) + { + continue; + } + + throw new InvalidOperationException( + $"{layout.Members[i].Display} and {layout.Members[j].Display} both resolve to the output parameter '{first}' of {where}, so one value would be read under two meanings. " + + (layout.Members[i].Named || layout.Members[j].Named + ? "Name one of them exactly as the parameter is declared (a name that matches exactly wins over one that matches only ignoring case or underscores), or drop one." + : "Name each member's parameter with [Column(\"name\")], or remove one of them.")); + } + } + + run.Names = resolved; + } + + // An exact member ([Column]) names its parameter; the others go through + // the tiers of AddParam's names: a named output over the name it was given + // (or the candidates it carries), a model member over the member's name. + static string? Find(OutputMember member, NameSet real, string commandText) + { + if (member.Exact) return real.Find(member.Name)?.Real; + if (!member.Named) return real.Match(member.Name, commandText, member.Display); + + string fix = member.Form == OutputForm.Execute + ? "Pass the exact parameter name, naming one of those two." + : "Pass the exact name of the parameter."; + + // One candidate, the name as given: remembered by that name. + if (member.Candidates.IsDefault) + { + return real.MatchName( + member.Name, + commandText, + member.Display, + fix); + } + + // Not NameSet.Match: its memo is keyed by the text of an argument + // expression, which AddParam shares, and its candidates include chain + // names. Not MatchName either: its memo answers for one candidate. + return ParameterNames.MatchBareAs( + member.Candidates, + real.Names, + real.BareNames, + member.Name, + commandText, + member.Display, + fix); + } + + /// + /// Makes the exception for a member that matches no parameter. + /// + /// The member. + /// The declared names. + /// The command for the messages. + /// The exception. + static InvalidOperationException NoOutputMatch( + OutputMember member, + ImmutableArray real, + string where) + { + string declared = string.Join(", ", real); + if (member.Named) + { + // A decimal reaches here through the form that takes a precision and + // scale; any other type through the plain named form. + string call = member.Wire!.Type == DbType.Decimal + ? member.Form switch + { + OutputForm.Capture + => "Pass one of those names to CaptureOutput(name, " + + "precision, scale, out …) or CaptureOutputDecimal(name, " + + "precision, scale, out …)", + OutputForm.Definition + => "Pass one of those names to Output(name, " + + "precision, scale) or OutputDecimal(name, precision, " + + "scale)", + _ => "Pass one of those names to " + + "ExecuteOutputAsync(name, precision, scale) " + + "or ExecuteOutputDecimalAsync(name, precision, scale)", + } + : $"Pass one of those names to {OutputArguments.NamedCall(member.Form, "T", "name")}"; + + return new( + $"{member.Display} is not a parameter of {where}, which declares: {declared}. " + + call + ", or add the parameter to the procedure (or its @name marker to the text)."); + } + + if (member.Exact) + { + return new( + $"{member.Display} names its parameter '{member.Name}' with [Column], but {where} declares no parameter of that name (it declares: {declared}). " + + "Change the [Column] name to one it declares, or add the parameter."); + } + + return new( + $"{member.Display} has no matching parameter on {where} (tried {string.Join(", ", ParameterNames.Candidates(member.Name))}; it declares: {declared}). " + + $"Add a parameter named {member.Name} to {where}, or name the member's parameter with [Column(\"name\")]."); + } + + /// + /// Adds the call's output parameters to the command, or turns the matching + /// input into one. + /// + /// + /// The provider's parameters are already on the command. An output member + /// whose parameter was given a value turns that parameter into InputOutput + /// (keeping a type the caller gave), so one name never yields two + /// parameters. + /// + /// How an input is found. + /// The command, with the provider's parameters. + /// The call's output parameters, resolved. + /// Finds the inputs the call sent. + /// The provider did not add a + /// parameter that was sent. + public static void Add( + IDbCommand command, + OutputRun run, + TLookup inputs) + where TLookup : struct, IInputLookup + { + Debug.Assert( + run.Names is not null, + "The build step resolves the names first."); + OutputLayout layout = run.Layout; + var parameters = new IDbDataParameter?[layout.Members.Length]; + bool[] pure = new bool[parameters.Length]; + for (int i = 0; i < parameters.Length; i++) + { + OutputMember member = layout.Members[i]; + if (member.IsReturnValue) + { + parameters[i] = command.AddReturnParameter(); + pure[i] = true; + continue; + } + + string name = run.Names![i]!; + OutputWire wire = member.Wire!; + if (inputs.TryFind(name, out string inputName, out bool typed)) + { + IDbDataParameter parameter = FindParameter(command, inputName) + ?? throw new InvalidOperationException( + $"{member.Display} reads back the parameter '{inputName}', which was given a value, but the command's provider did not add it to the command under that name, so there is nothing to read. " + + "Give the value under the name the provider keeps (AddParam(\"name\", value)), or do not give it a value so it is sent as an output only."); + parameter.Direction = ParameterDirection.InputOutput; + if (!typed) parameter.DbType = wire.Type; + wire.Apply(parameter); + parameters[i] = parameter; + continue; + } + + IDbDataParameter output = command.CreateParameter(); + output.ParameterName = name; + output.Direction = ParameterDirection.Output; + output.DbType = wire.Type; + wire.Apply(output); + command.Parameters.Add(output); + parameters[i] = output; + pure[i] = true; + } + + run.Parameters = parameters; + run.Pure = pure; + } + + /// + /// Finds the provider's parameter of a name, compared without the + /// @ and ignoring case. + /// + /// The command. + /// The name it was sent under. + /// The parameter, or . + static IDbDataParameter? FindParameter( + IDbCommand command, + string name) + { + foreach (object? p in command.Parameters) + { + if (p is IDbDataParameter parameter + && DbQueryBinding.SameName(parameter.ParameterName, name)) + { + return parameter; + } + } + + return null; + } + + /// + /// Finds an input among the parameters a definition's call put on the + /// provider's command: a value given to the call is an input of unknown + /// type, which an output of the same name turns into InputOutput. + /// + /// The command, built with the call's values. + public readonly struct CommandInputs(IDbCommand command) : IInputLookup + { + /// + public bool TryFind(string name, out string inputName, out bool typed) + { + typed = false; + if (FindParameter(command, name) is { } found) + { + inputName = found.ParameterName; + return true; + } + + inputName = name; + return false; + } + } +} diff --git a/Source/Core/OutputDbNonQuery.cs b/Source/Core/OutputDbNonQuery.cs new file mode 100644 index 00000000..0b510539 --- /dev/null +++ b/Source/Core/OutputDbNonQuery.cs @@ -0,0 +1,269 @@ +using System.Diagnostics; + +namespace Open.Database.Extensions; + +/// +/// Declares the outputs of a definition, and checks them when it is declared. +/// +/// +/// Only what the model and the definition decide is checked here: no +/// provider and no server is needed. A bad declaration in a +/// field arrives as a +/// whose inner exception has the +/// message. +/// +static class OutputDefinitions +{ + /// + /// Names a definition for a message: the procedure, or the start of the + /// text. + /// + /// The definition. + /// The name. + public static string Describe(DbQuery definition) + { + if (definition.Kind == CommandType.StoredProcedure) + return $"the procedure {definition.CommandText}"; + + string text = definition.CommandText.Trim(); + return text.Length <= 40 + ? $"the text \"{text}\"" + : $"the text \"{text[..40]}…\""; + } + + public static DbQuery Model(DbQuery definition) + { + string model = Shape.TypeName(typeof(TOut)); + OutputLayout layout; + try + { + layout = OutputLayout.Get(OutputForm.Definition); + } + catch (InvalidOperationException ex) + { + throw new InvalidOperationException( + $"Output<{model}>() on {Describe(definition)} cannot be declared: {ex.Message}", + ex); + } + + 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); + } + + public static DbQuery Named(DbQuery definition, string name) + { + OutputArguments.ThrowIfNoName(name, OutputForm.Definition); + return definition.WithOutput(Wrap( + definition, + name, + static (n) => OutputValue.Get(n, OutputForm.Definition))); + } + + public static DbQuery Shaped( + DbQuery definition, + string name, + byte precision, + byte scale) + { + OutputArguments.ThrowIfNoName(name, OutputForm.Definition); + Check( + definition, + name, + static n => OutputValue.ThrowUnlessDecimal( + n, + OutputForm.Definition)); + OutputArguments.ThrowIfBadShape(name, precision, scale, OutputForm.Definition); + return definition.WithOutput(OutputValue.Shaped( + name, + precision, + scale, + $"Output<{Shape.TypeName(typeof(T))}>(\"{name}\", {precision}, {scale})", + OutputForm.Definition)); + } + + public static DbQuery Decimal( + DbQuery definition, + string name, + byte precision, + byte scale) + { + OutputArguments.ThrowIfNoName(name, OutputForm.Definition); + OutputArguments.ThrowIfBadShape(name, precision, scale, OutputForm.Definition); + return definition.WithOutput(OutputValue.Shaped( + name, + precision, + scale, + $"OutputDecimal(\"{name}\", {precision}, {scale})", + OutputForm.Definition)); + } + + // The same, for a check that returns nothing. + static void Check(DbQuery definition, string name, Action check) + => Wrap( + definition, + name, + n => + { + check(n); + return null!; + }); + + // Names the definition in the message of a refusal. + static OutputLayout Wrap( + DbQuery definition, + string name, + Func check) + { + try + { + return check(name); + } + catch (InvalidOperationException ex) + { + throw new InvalidOperationException( + $"Output<{Shape.TypeName(typeof(T))}>(\"{name}\") on {Describe(definition)} cannot be declared: {ex.Message}", + ex); + } + } +} + +/// +/// A write defined once that reads output parameters: the command text (or +/// stored procedure name) and what it reads back. It has no connection yet. +/// +/// +/// +/// Made by . It is immutable, so a +/// field holds it: +/// +/// +/// static readonly OutputDbNonQuery<AddPostResult> AddPost +/// = DbNonQuery.Procedure("[dbo].[AddPost]") +/// .Output<AddPostResult>(); +/// +/// AddPostResult created = await AddPost.Using(db) +/// .AddParam(title) +/// .ExecuteOutputAsync(cancellationToken); +/// +/// +/// The values can be added before or after Using. +/// Set the timeout on the first. +/// +/// +/// What the outputs are read as. +public sealed class OutputDbNonQuery +{ + // Carries the outputs it reads. + readonly DbQuery _definition; + + internal OutputDbNonQuery(DbQuery definition) => _definition = definition; + + PendingCall> Pending => new(_definition); + + /// + public OutputDbNonQuery Params() + where TParams : struct, IEquatable + => new(_definition.Params()); + + /// + public BoundCall> Using(DbConnection connection) + // DbQuery.Using throws ArgumentNullException for a null source. + => new(_definition.Using(connection).ToCall()); + + /// + public BoundCall> Using(DbTransaction transaction) + // DbQuery.Using throws ArgumentNullException for a null source. + => new(_definition.Using(transaction).ToCall()); + + /// + public BoundCall> Using( + IDbConnectionPool pool) + where TConnection : DbConnection + // DbQuery.Using throws ArgumentNullException for a null source. + => new(_definition.Using(pool).ToCall()); + + /// + public BoundCall> Using( + IDbConnectionFactory factory) + where TConnection : DbConnection + // DbQuery.Using throws ArgumentNullException for a null source. + => new(_definition.Using(factory).ToCall()); + + /// + public PendingCall> AddParam( + string name, + TValue value) + => Pending.AddParam(name, value); + + /// + public PendingCall> AddParam(string name, string? value) + => Pending.AddParam(name, value); + + /// + [OverloadResolutionPriority(-1)] + public PendingCall> AddParam( + TValue value, + [CallerArgumentExpression(nameof(value))] string? expression = null) + => Pending.AddParam(value, expression); + + /// + public PendingCall> AddParams(TValues values) + where TValues : notnull + => Pending.AddParams(values); +} + +/// +/// An whose values are one typed struct, +/// so the compiler checks them. +/// +/// The type of the values. +/// What the outputs are read as. +public sealed class OutputDbNonQuery + where TParams : struct, IEquatable +{ + readonly DbQuery _definition; + + internal OutputDbNonQuery(DbQuery definition) + { + Debug.Assert(definition is not null); + _definition = definition; + } + + /// Adds the values before the source is known. + /// The values. + /// The values, to be given a source with Using. + public PendingParams, TParams> AddParams(TParams values) + => new(_definition, values); + + /// + public BoundParams, TParams> Using(DbConnection connection) + // DbQuery.Using throws ArgumentNullException for a null source. + => new(_definition.Using(connection)); + + /// + public BoundParams, TParams> Using( + DbTransaction transaction) + // DbQuery.Using throws ArgumentNullException for a null source. + => new(_definition.Using(transaction)); + + /// + public BoundParams, TParams> Using( + IDbConnectionPool pool) + where TConnection : DbConnection + // DbQuery.Using throws ArgumentNullException for a null source. + => new(_definition.Using(pool)); + + /// + public BoundParams, TParams> Using( + IDbConnectionFactory factory) + where TConnection : DbConnection + // DbQuery.Using throws ArgumentNullException for a null source. + => new(_definition.Using(factory)); +} diff --git a/Source/Core/OutputLayout.cs b/Source/Core/OutputLayout.cs index f657ffd6..27e39091 100644 --- a/Source/Core/OutputLayout.cs +++ b/Source/Core/OutputLayout.cs @@ -18,6 +18,8 @@ sealed class OutputMember /// The member for the messages: Model.Member, or The output parameter 'name'. /// for the one value of a named /// form, which the caller named. + /// The names a non-exact named output is matched by, + /// most specific first; the default value means . /// The members the call comes from, for the fixes the /// messages give. public OutputMember( @@ -27,9 +29,11 @@ public OutputMember( OutputWire wire, string display, bool named = false, - OutputForm form = OutputForm.Execute) + OutputForm form = OutputForm.Execute, + ImmutableArray candidates = default) { Name = name; + Candidates = candidates; Exact = exact; Label = label; Wire = wire; @@ -66,6 +70,7 @@ public OutputMember(OutputMember member, string display, OutputForm form) IsReturnValue = member.IsReturnValue; Wire = member.Wire; Named = member.Named; + Candidates = member.Candidates; Display = display; Form = form; } @@ -84,6 +89,10 @@ public OutputMember(OutputMember member, string display, OutputForm form) /// The member for the messages: Model.Member, or The output parameter 'name' in the named form. public readonly string Display; + /// The names a non-exact named output is matched by through the + /// tiers, most specific first; the default value means . + public readonly ImmutableArray Candidates; + /// Whether names the parameter exactly ([Column]), with or without its @ and in any case; otherwise the name is matched in the four tiers like the name of AddParam. public readonly bool Exact; @@ -110,6 +119,10 @@ enum OutputForm : byte /// CaptureOutput, CaptureOutputDecimal and /// CaptureReturn. Capture, + + /// Output<T> and OutputDecimal, which declare + /// the outputs of a definition. + Definition, } /// @@ -341,15 +354,10 @@ public static OutputLayout Get(OutputForm form = OutputForm.Execute) static string Refusal(OutputForm form) { string model = Shape.TypeName(typeof(TOut)); - bool capture = form == OutputForm.Capture; - string call = capture - ? $"CaptureOutput(out DbCapture<{model}>)" - : $"ExecuteOutputAsync<{model}>()"; + string call = OutputArguments.ModelCall(form, model); if (IsScalar) { - string named = capture - ? $"CaptureOutput<{model}>(name, out …)" - : $"ExecuteOutputAsync<{model}>(name)"; + string named = OutputArguments.NamedCall(form, model, "name"); return $"{call} reads a model of output parameters, " + $"but {model} is a single value with no members to match to " + "parameters. " @@ -531,9 +539,17 @@ public static OutputLayout Get( string name, OutputForm form = OutputForm.Execute) { - string display = form == OutputForm.Capture - ? $"CaptureOutput<{Shape.TypeName(typeof(T))}>(\"{name}\")" - : $"The output parameter '{name}'"; + string display = form switch + { + OutputForm.Capture + => $"CaptureOutput<{Shape.TypeName(typeof(T))}>(\"{name}\")", + OutputForm.Definition + => OutputArguments.NamedCall( + form, + Shape.TypeName(typeof(T)), + $"\"{name}\""), + _ => $"The output parameter '{name}'", + }; OutputWire wire = Wire ?? throw new InvalidOperationException( Message(name, display, form)); return new( @@ -560,27 +576,18 @@ public static void ThrowUnlessDecimal( if (Reason == OutputValueRefusal.DecimalNeedsShape) return; string shown = Shape.TypeName(typeof(T)); - bool capture = form == OutputForm.Capture; string fix = Reason switch { // A model has no single value to read: the named form refuses it too. OutputValueRefusal.NotScalar - => capture - ? $"{shown} is a model; " - + $"call CaptureOutput(out DbCapture<{shown}>) " - + "without a name to read its members, " - + "giving each decimal member [Column(TypeName = " - + "\"decimal(p,s)\")]." - : $"{shown} is a model; " - + $"call ExecuteOutputAsync<{shown}>() " - + "without a name to read its members, " - + "giving each decimal member [Column(TypeName = " - + "\"decimal(p,s)\")].", + => $"{shown} is a model; " + + $"call {OutputArguments.ModelCall(form, shown)} " + + "without a name to read its members, " + + "giving each decimal member [Column(TypeName = " + + "\"decimal(p,s)\")].", OutputValueRefusal.NoDbType => $"{shown} has no database type for an output; read it as a type that has one, {OutputWire.SupportedTypes}.", - _ => capture - ? $"Use CaptureOutput<{shown}>(\"{name}\", out …)." - : $"Use ExecuteOutputAsync<{shown}>(\"{name}\").", + _ => $"Use {OutputArguments.NamedCall(form, shown, $"\"{name}\"")}.", }; throw new InvalidOperationException( @@ -595,17 +602,17 @@ public static void ThrowUnlessDecimal( /// The scale, checked by the caller. /// The value for the messages, or /// for the one of ExecuteOutputAsync. + /// The members the call comes from, for the fixes the + /// messages give. /// The layout; is checked by the caller, which has called . public static OutputLayout Shaped( string name, byte precision, byte scale, - string? display = null) + string? display = null, + OutputForm form = OutputForm.Execute) { Debug.Assert(Reason == OutputValueRefusal.DecimalNeedsShape); - OutputForm form = display is null - ? OutputForm.Execute - : OutputForm.Capture; display ??= $"The output parameter '{name}'"; return new( new OutputMember( @@ -621,39 +628,24 @@ public static OutputLayout Shaped( static string Message(string name, string display, OutputForm form) { string shown = Shape.TypeName(typeof(T)); - bool capture = form == OutputForm.Capture; + string quoted = $"\"{name}\""; return Reason switch { OutputValueRefusal.NotScalar - => capture - ? $"CaptureOutput<{shown}>(\"{name}\", out …) " - + $"reads one value, but {shown} is a model, " - + "not a single value. " - + $"Call CaptureOutput(out DbCapture<{shown}>) " - + "without a name to read its members, " - + $"or read '{name}' as a single-value type " - + $"{OutputWire.SupportedTypes}." - : $"ExecuteOutputAsync<{shown}>(\"{name}\") " - + $"reads one value, but {shown} is a model, " - + "not a single value. " - + $"Call ExecuteOutputAsync<{shown}>() " - + "without a name to read its members, " - + $"or read '{name}' as a single-value type " - + $"{OutputWire.SupportedTypes}.", + => $"{OutputArguments.NamedCall(form, shown, quoted)} " + + $"reads one value, but {shown} is a model, " + + "not a single value. " + + $"Call {OutputArguments.ModelCall(form, shown)} " + + "without a name to read its members, " + + $"or read '{name}' as a single-value type " + + $"{OutputWire.SupportedTypes}.", OutputValueRefusal.DecimalNeedsShape - => capture - ? $"{display} is read as {shown}. " - + "A decimal output needs its precision and scale, " - + "or the server rounds it to a whole number. " - + $"Use CaptureOutput(\"{name}\", 19, 4, out …) " - + $"or CaptureOutputDecimal(\"{name}\", 19, 4, out …) " - + "with the column's precision and scale." - : $"{display} is read as {shown}. " - + "A decimal output needs its precision and scale, " - + "or the server rounds it to a whole number. " - + $"Use ExecuteOutputAsync(\"{name}\", 19, 4) " - + $"or ExecuteOutputDecimalAsync(\"{name}\", 19, 4) " - + "with the column's precision and scale.", + => $"{display} is read as {shown}. " + + "A decimal output needs its precision and scale, " + + "or the server rounds it to a whole number. " + + $"Use {OutputArguments.ShapedCall(form, quoted)} " + + $"or {OutputArguments.DecimalCall(form, quoted)} " + + "with the column's precision and scale.", _ => $"{display} is read as {shown}, which has no database type, so it cannot be sent as an output parameter. " + $"Read it as a type that has one, {OutputWire.SupportedTypes}.", @@ -712,6 +704,26 @@ class OutputRun(OutputLayout layout) /// Whether each member's parameter is pure output (no value sent), so a means it never arrived. public bool[]? Pure; + // The values copied off the provider's command by Snapshot, so they can + // be read after the command is disposed. + object?[]? _values; + + /// + /// Copies the values off the provider's parameters, while the command is + /// still alive; and then read the + /// copy. + /// + public void Snapshot() + { + IDbDataParameter?[] parameters = Parameters!; + var values = new object?[parameters.Length]; + for (int i = 0; i < values.Length; i++) values[i] = parameters[i]!.Value; + _values = values; + } + + object? Raw(int index) + => _values is { } values ? values[index] : Parameters![index]!.Value; + /// /// Gets the value of a member once the response is complete. /// @@ -720,7 +732,7 @@ class OutputRun(OutputLayout layout) /// The value never arrived. public object? Value(int index) { - object? value = Parameters![index]!.Value; + object? value = Raw(index); if (!Delivered(index)) { OutputMember member = Layout.Members[index]; @@ -741,7 +753,7 @@ class OutputRun(OutputLayout layout) /// when the value never arrived; /// otherwise, . public bool Delivered(int index) - => Parameters![index]!.Value is not null || !Pure![index]; + => Raw(index) is not null || !Pure![index]; /// /// Builds the model from the values, once the response is complete. @@ -812,6 +824,73 @@ public static string Message(string shown) /// static class OutputArguments { + /// + /// Gets the call that reads a model, as a message tells the caller to + /// write it. + /// + /// The members the call comes from. + /// The model's type name. + /// The call. + public static string ModelCall(OutputForm form, string model) + => form switch + { + OutputForm.Capture => $"CaptureOutput(out DbCapture<{model}>)", + OutputForm.Definition => $"Output<{model}>()", + _ => $"ExecuteOutputAsync<{model}>()", + }; + + /// + /// Gets the call that reads one value by name, as a message tells the caller + /// to write it. + /// + /// The members the call comes from. + /// The value's type name. + /// The name as the call writes it: a placeholder, or + /// a quoted name. + /// The call. + public static string NamedCall( + OutputForm form, + string type, + string argument) + => form switch + { + OutputForm.Capture => $"CaptureOutput<{type}>({argument}, out …)", + OutputForm.Definition => $"Output<{type}>({argument})", + _ => $"ExecuteOutputAsync<{type}>({argument})", + }; + + /// + /// Gets the call that reads a by name with a + /// precision and scale, read as . + /// + /// The members the call comes from. + /// The name as the call writes it. + /// The call, written for decimal(19,4). + public static string ShapedCall(OutputForm form, string argument) + => form switch + { + OutputForm.Capture + => $"CaptureOutput({argument}, 19, 4, out …)", + OutputForm.Definition => $"Output({argument}, 19, 4)", + _ => $"ExecuteOutputAsync({argument}, 19, 4)", + }; + + /// + /// Gets the call that reads a by name as a + /// of it. + /// + /// The members the call comes from. + /// The name as the call writes it. + /// The call, written for decimal(19,4). + public static string DecimalCall(OutputForm form, string argument) + => form switch + { + OutputForm.Capture + => $"CaptureOutputDecimal({argument}, 19, 4, out …)", + OutputForm.Definition => $"OutputDecimal({argument}, 19, 4)", + _ => $"ExecuteOutputDecimalAsync({argument}, 19, 4)", + }; + /// /// Throws unless a name is given: , empty, white /// space and a bare @ are not names. @@ -836,11 +915,8 @@ public static void ThrowIfNoName(string name, OutputForm form) } static string NameRequired(OutputForm form) - => form == OutputForm.Capture - ? "A parameter name is required, " - + "for example CaptureOutput(\"total\", out …)." - : "A parameter name is required, " - + "for example ExecuteOutputAsync(\"total\")."; + => "A parameter name is required, for example " + + $"{NamedCall(form, "int", "\"total\"")}."; // One rule with [Column(TypeName = "decimal(p,s)")]: // OutputWire.IsDecimalShape. @@ -862,11 +938,8 @@ public static void ThrowIfBadShape( { if (OutputWire.IsDecimalShape(precision, scale)) return; - string example = form == OutputForm.Capture - ? $"For decimal(19,4), pass CaptureOutput(\"{name}\", 19, " - + "4, out …)." - : "For decimal(19,4), " - + $"pass ExecuteOutputAsync(\"{name}\", 19, 4)."; + string example = "For decimal(19,4), pass " + + $"{ShapedCall(form, $"\"{name}\"")}."; if (precision is 0 or > 38) { @@ -902,15 +975,23 @@ public static ValueMappingException DecimalNull( => new( $"The decimal output parameter '{name}' is NULL, " + "which a decimal cannot hold. " - + (form == OutputForm.Capture - ? $"Read it as decimal? (CaptureOutput(\"{name}\", " - + "precision, scale, out …)) " - + $"or with CaptureOutputDecimal(\"{name}\", precision, scale, " - + "out …), which give null for NULL." - : "Read it as decimal? " - + $"(ExecuteOutputAsync(\"{name}\", precision, " - + $"scale)) or with ExecuteOutputDecimalAsync(\"{name}\", " - + "precision, scale), which return null for NULL."), + + form switch + { + OutputForm.Capture + => $"Read it as decimal? (CaptureOutput(\"{name}\", " + + "precision, scale, out …)) " + + $"or with CaptureOutputDecimal(\"{name}\", precision, scale, " + + "out …), which give null for NULL.", + OutputForm.Definition + => $"Read it as decimal? (Output(\"{name}\", " + + "precision, scale)) " + + $"or with OutputDecimal(\"{name}\", precision, scale), " + + "which give null for NULL.", + _ => "Read it as decimal? " + + $"(ExecuteOutputAsync(\"{name}\", precision, " + + $"scale)) or with ExecuteOutputDecimalAsync(\"{name}\", " + + "precision, scale), which return null for NULL.", + }, name, name, typeof(decimal)); diff --git a/Source/Core/PublicAPI.Unshipped.txt b/Source/Core/PublicAPI.Unshipped.txt index e4f699a4..d8d929e1 100644 --- a/Source/Core/PublicAPI.Unshipped.txt +++ b/Source/Core/PublicAPI.Unshipped.txt @@ -128,3 +128,31 @@ Open.Database.Extensions.MappedQueryWithTake.WithOptions(Open.Database.Extens Open.Database.Extensions.MappedCommand.WithOptions(Open.Database.Extensions.QueryOptions options) -> Open.Database.Extensions.MappedCommand Open.Database.Extensions.MappedDbQuery.WithOptions(Open.Database.Extensions.QueryOptions options) -> Open.Database.Extensions.MappedDbQuery! Open.Database.Extensions.MappedDbQuery.WithOptions(Open.Database.Extensions.QueryOptions options) -> Open.Database.Extensions.MappedDbQuery! +Open.Database.Extensions.OutputDbNonQuery +Open.Database.Extensions.OutputDbNonQuery.AddParam(string! name, string? value) -> Open.Database.Extensions.PendingCall> +Open.Database.Extensions.OutputDbNonQuery.AddParam(string! name, TValue value) -> Open.Database.Extensions.PendingCall> +Open.Database.Extensions.OutputDbNonQuery.AddParam(TValue value, string? expression = null) -> Open.Database.Extensions.PendingCall> +Open.Database.Extensions.OutputDbNonQuery.AddParams(TValues values) -> Open.Database.Extensions.PendingCall> +Open.Database.Extensions.OutputDbNonQuery.Params() -> Open.Database.Extensions.OutputDbNonQuery! +Open.Database.Extensions.OutputDbNonQuery.Using(System.Data.Common.DbConnection! connection) -> Open.Database.Extensions.BoundCall> +Open.Database.Extensions.OutputDbNonQuery.Using(System.Data.Common.DbTransaction! transaction) -> Open.Database.Extensions.BoundCall> +Open.Database.Extensions.OutputDbNonQuery.Using(Open.Database.Extensions.IDbConnectionFactory! factory) -> Open.Database.Extensions.BoundCall> +Open.Database.Extensions.OutputDbNonQuery.Using(Open.Database.Extensions.IDbConnectionPool! pool) -> Open.Database.Extensions.BoundCall> +Open.Database.Extensions.OutputDbNonQuery +Open.Database.Extensions.OutputDbNonQuery.AddParams(TParams values) -> Open.Database.Extensions.PendingParams, TParams> +Open.Database.Extensions.OutputDbNonQuery.Using(System.Data.Common.DbConnection! connection) -> Open.Database.Extensions.BoundParams, TParams> +Open.Database.Extensions.OutputDbNonQuery.Using(System.Data.Common.DbTransaction! transaction) -> Open.Database.Extensions.BoundParams, TParams> +Open.Database.Extensions.OutputDbNonQuery.Using(Open.Database.Extensions.IDbConnectionFactory! factory) -> Open.Database.Extensions.BoundParams, TParams> +Open.Database.Extensions.OutputDbNonQuery.Using(Open.Database.Extensions.IDbConnectionPool! pool) -> Open.Database.Extensions.BoundParams, TParams> +Open.Database.Extensions.OutputKind +Open.Database.Extensions.OutputKind.OutputKind() -> void +Open.Database.Extensions.DbNonQuery.Output() -> Open.Database.Extensions.OutputDbNonQuery! +Open.Database.Extensions.DbNonQuery.Output(string! name) -> Open.Database.Extensions.OutputDbNonQuery! +Open.Database.Extensions.DbNonQuery.Output(string! name, byte precision, byte scale) -> Open.Database.Extensions.OutputDbNonQuery! +Open.Database.Extensions.DbNonQuery.OutputDecimal(string! name, byte precision, byte scale) -> Open.Database.Extensions.OutputDbNonQuery! +Open.Database.Extensions.DbNonQuery.Output() -> Open.Database.Extensions.OutputDbNonQuery! +Open.Database.Extensions.DbNonQuery.Output(string! name) -> Open.Database.Extensions.OutputDbNonQuery! +Open.Database.Extensions.DbNonQuery.Output(string! name, byte precision, byte scale) -> Open.Database.Extensions.OutputDbNonQuery! +Open.Database.Extensions.DbNonQuery.OutputDecimal(string! name, byte precision, byte scale) -> Open.Database.Extensions.OutputDbNonQuery! +static Open.Database.Extensions.BoundCallExtensions.ExecuteOutputAsync(this Open.Database.Extensions.BoundCall> call, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +static Open.Database.Extensions.BoundCallExtensions.ExecuteReturnAsync(this Open.Database.Extensions.BoundCall call, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask diff --git a/Tests/Open.Database.Extensions.Core.Tests/OutputDefinitionTests.cs b/Tests/Open.Database.Extensions.Core.Tests/OutputDefinitionTests.cs new file mode 100644 index 00000000..e8e49d03 --- /dev/null +++ b/Tests/Open.Database.Extensions.Core.Tests/OutputDefinitionTests.cs @@ -0,0 +1,476 @@ +using Microsoft.Data.SqlClient; +using System.ComponentModel.DataAnnotations.Schema; + +#nullable enable + +namespace Open.Database.Extensions.Tests; + +// Output() on a DbNonQuery definition: what is checked when it is declared +// (no server), and what a call reads against SQL Server (skipped without +// LocalDB), the same as the command's ExecuteOutputAsync reads. +[ExcludeFromCodeCoverage] +[Collection("LocalDB DDL")] +public static class OutputDefinitionTests +{ + static CancellationToken Token => TestContext.Current.CancellationToken; + + public sealed record Created(int PostId, int TotalCount); + + public sealed record Totals( + [property: Column(TypeName = "decimal(10,2)")] decimal Total); + + public sealed record WithReturn(int ReturnValue, int PostId); + + public sealed record NoMembers; + + + public readonly record struct IdOnly(int Id); + + static LocalDbFixture.Scratch Procedure(string parameters, string body) + => LocalDbFixture.CreateProcedureWithBody( + parameters, + "set nocount on; " + body, + "ode_def"); + + static async Task OpenAsync() + { + SqlConnection connection = LocalDbFixture.Create(); + await connection.OpenAsync(Token); + return connection; + } + + static DbNonQuery Proc(LocalDbFixture.Scratch procedure) + => DbNonQuery.Procedure("dbo." + procedure.Name); + + // ---- declaration: no server ---- + + [Fact] + public static void AModel_IsCheckedWhenDeclared_NamingTheDefinitionAndTheModel() + { + var ex = Assert.Throws( + () => DbNonQuery.Procedure("dbo.AddPost").Output()); + + Assert.Contains("Output()", ex.Message); + Assert.Contains("the procedure dbo.AddPost", ex.Message); + Assert.Contains("no member to read an output parameter", ex.Message); + Assert.NotNull(ex.InnerException); + } + + [Fact] + public static void ASingleValue_ForTheModelForm_SaysToUseTheNamedForm() + { + var ex = Assert.Throws( + () => DbNonQuery.Procedure("dbo.AddPost").Output()); + + Assert.Contains("Output(name)", ex.Message); + Assert.DoesNotContain("ExecuteOutputAsync", ex.Message); + } + + [Fact] + public static void AModel_ForTheNamedForm_PointsToTheModelForm() + { + var ex = Assert.Throws( + () => DbNonQuery.Procedure("dbo.AddPost").Output("id")); + + Assert.Contains("Output(\"id\")", ex.Message); + Assert.Contains("dbo.AddPost", ex.Message); + Assert.Contains("Output()", ex.Message); + } + + [Fact] + public static void ADecimal_WithoutAShape_NamesBothForms() + { + var ex = Assert.Throws( + () => DbNonQuery.Procedure("dbo.Total").Output("total")); + + Assert.Contains("Output(\"total\", 19, 4)", ex.Message); + Assert.Contains("OutputDecimal(\"total\", 19, 4)", ex.Message); + } + + [Fact] + public static void AShape_OnANonDecimal_SaysOnlyDecimalTakesOne() + { + var ex = Assert.Throws( + () => DbNonQuery.Procedure("dbo.Total").Output("total", 19, 4)); + + Assert.Contains("Only a decimal output takes a precision and scale", ex.Message); + Assert.Contains("Output(\"total\")", ex.Message); + } + + [Theory] + [InlineData(0, 0)] + [InlineData(39, 2)] + [InlineData(5, 6)] + public static void ABadShape_IsRefusedForBothDecimalForms( + byte precision, + byte scale) + { + DbNonQuery definition = DbNonQuery.Procedure("dbo.Total"); + + Assert.Throws( + () => definition.Output("total", precision, scale)); + Assert.Throws( + () => definition.OutputDecimal("total", precision, scale)); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(" ")] + [InlineData("@")] + public static void ANameThatIsNotOne_IsRefusedWithTheFix(string? name) + { + Exception ex = Assert.ThrowsAny( + () => DbNonQuery.Procedure("dbo.AddPost").Output(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() + { + var connection = new SqlConnection("Server=nowhere"); + BoundCall call = DbNonQuery.Procedure("dbo.P").Using(connection); + + var ex = Assert.Throws( + () => call.ExecuteReturnAsync(Token)); + + Assert.Contains("The return code is one integer", ex.Message); + } +#pragma warning restore CA2012 + + [Fact] + public static void ABadDefinitionInAStaticField_ArrivesAsTheInnerOfATypeInitializationException() + { + var wrapper = Assert.Throws( + () => _ = BadHolder.Definition); + + var inner = Assert.IsType(wrapper.InnerException); + Assert.Contains("Output()", inner.Message); + Assert.Contains("the procedure dbo.Broken", inner.Message); + } + + static class BadHolder + { + public static readonly OutputDbNonQuery Definition + = DbNonQuery.Procedure("dbo.Broken").Output(); + } + + [Fact] + public static void ADefinition_IsImmutable_AndTheNonOutputDefinitionIsUnchanged() + { + DbNonQuery plain = DbNonQuery.Procedure("dbo.AddPost"); + _ = plain.Output(); + + Assert.Equal(DbNonQuery.Procedure("dbo.AddPost"), plain); + } + + // ---- a call against SQL Server ---- + + [Fact] + public static async Task ADefinitionAndACommand_GiveTheSameModel() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = Procedure( + "@post_id int output, @total_count int output", + "set @post_id = 7; set @total_count = 42;"); + await using SqlConnection connection = await OpenAsync(); + + Created fromDefinition = await Proc(procedure) + .Output() + .Using(connection) + .ExecuteOutputAsync(Token); + Created fromCommand = await connection + .StoredProcedure("dbo." + procedure.Name) + .ExecuteOutputAsync(Token); + + Assert.Equal(new Created(7, 42), fromDefinition); + Assert.Equal(fromCommand, fromDefinition); + } + + [Fact] + public static async Task ANamedOutput_FindsTheParameterByTheTierRule_AndAnExactNameWins() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = Procedure( + "@total_count int = null output, @TotalCount int = null output", + "set @total_count = 1; set @TotalCount = 2;"); + await using SqlConnection connection = await OpenAsync(); + + // Exact first: TotalCount is a parameter, so it is not the tier match. + int exact = await Proc(procedure) + .Output("TotalCount") + .Using(connection) + .ExecuteOutputAsync(Token); + // A lower tier: ignoring case and underscores finds total_count only + // when no higher one matches. + int tier = await Proc(procedure) + .Output("totalcount") + .Using(connection) + .ExecuteOutputAsync(Token); + + Assert.Equal(2, exact); + // "totalcount" matches @TotalCount ignoring case (tier 2), ahead of + // @total_count (tier 3). + Assert.Equal(2, tier); + } + + [Fact] + public static async Task ANamedOutput_FindsAParameterAfterAPrefix() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = Procedure( + "@p_total_count int output", + "set @p_total_count = 9;"); + await using SqlConnection connection = await OpenAsync(); + + int value = await Proc(procedure) + .Output("totalCount") + .Using(connection) + .ExecuteOutputAsync(Token); + + Assert.Equal(9, value); + } + + [Fact] + public static async Task ANamedOutput_ThatMatchesTwoParametersAtOneTier_ThrowsWithTheFix() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = Procedure( + "@total_count int = null output, @totalCount_ int = null output", + "set @total_count = 1; set @totalCount_ = 2;"); + await using SqlConnection connection = await OpenAsync(); + + var ex = await Assert.ThrowsAsync( + async () => await Proc(procedure) + .Output("TOTAL__COUNT") + .Using(connection) + .ExecuteOutputAsync(Token)); + + Assert.Contains("matches both", ex.Message); + Assert.Contains("Pass the exact name of the parameter", ex.Message); + } + + [Fact] + public static async Task ANamedOutput_ThatMatchesNothing_NamesTheDefinitionForm() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = Procedure( + "@post_id int output", + "set @post_id = 1;"); + await using SqlConnection connection = await OpenAsync(); + + var ex = await Assert.ThrowsAsync( + async () => await Proc(procedure) + .Output("missing") + .Using(connection) + .ExecuteOutputAsync(Token)); + + Assert.Contains("is not a parameter of dbo." + procedure.Name, ex.Message); + Assert.Contains("Output(name)", ex.Message); + } + + [Fact] + public static async Task TheDecimalForms_GiveTheScale_AndNullByForm() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = Procedure( + "@total decimal(19,4) = null output, @none decimal(19,4) = null output", + "set @total = 12.3456; set @none = null;"); + await using SqlConnection connection = await OpenAsync(); + + decimal total = await Proc(procedure) + .Output("total", 19, 4) + .Using(connection) + .ExecuteOutputAsync(Token); + decimal? nullable = await Proc(procedure) + .OutputDecimal("none", 19, 4) + .Using(connection) + .ExecuteOutputAsync(Token); + decimal? asNullable = await Proc(procedure) + .Output("none", 19, 4) + .Using(connection) + .ExecuteOutputAsync(Token); + var refused = await Assert.ThrowsAsync( + async () => await Proc(procedure) + .Output("none", 19, 4) + .Using(connection) + .ExecuteOutputAsync(Token)); + + Assert.Equal(12.3456m, total); + Assert.Null(nullable); + Assert.Null(asNullable); + Assert.Contains("Output", refused.Message); + Assert.Contains("OutputDecimal(", refused.Message); + } + + [Fact] + public static async Task AModelWithADecimalColumnType_ReadsItsScale() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = Procedure( + "@total decimal(10,2) output", + "set @total = 3.25;"); + await using SqlConnection connection = await OpenAsync(); + + Totals totals = await Proc(procedure) + .Output() + .Using(connection) + .ExecuteOutputAsync(Token); + + Assert.Equal(3.25m, totals.Total); + } + + [Fact] + public static async Task TheReturnCode_OfABoundWrite_IsReadByExecuteReturnAsync() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = Procedure( + "@id int", + "return @id + 100;"); + await using SqlConnection connection = await OpenAsync(); + DbNonQuery definition = Proc(procedure); + + int status = await definition + .Using(connection) + .AddParam("id", 5) + .ExecuteReturnAsync(Token); + int rows = await definition + .Using(connection) + .AddParam("id", 5) + .ExecuteNonQueryAsync(Token); + + Assert.Equal(105, status); + Assert.Equal(-1, rows); + } + + [Fact] + public static async Task AModelWithTheReturnCode_ReadsOutputsAndTheCode() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = Procedure( + "@post_id int output", + "set @post_id = 4; return 11;"); + await using SqlConnection connection = await OpenAsync(); + + WithReturn result = await Proc(procedure) + .Output() + .Using(connection) + .ExecuteOutputAsync(Token); + + Assert.Equal(new WithReturn(11, 4), result); + } + + [Fact] + public static async Task AValueAddedUnderTheOutputsName_MakesItInputOutput() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = Procedure( + "@counter int output", + "set @counter = @counter + 1;"); + await using SqlConnection connection = await OpenAsync(); + + int next = await Proc(procedure) + .Output("counter") + .Using(connection) + .AddParam("counter", 41) + .ExecuteOutputAsync(Token); + + Assert.Equal(42, next); + } + + [Fact] + public static async Task ATextDefinition_ReadsAMarkerDeclaredOutput() + { + LocalDbFixture.SkipUnlessAvailable(); + await using SqlConnection connection = await OpenAsync(); + + int value = await DbNonQuery + .Text("set @result = @seed * 2") + .Output("result") + .Using(connection) + .AddParam("seed", 21) + .ExecuteOutputAsync(Token); + + Assert.Equal(42, value); + } + + [Fact] + public static async Task TypedParams_AndOutput_WorkInEitherOrder() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = Procedure( + "@id int, @doubled int output", + "set @doubled = @id * 2;"); + await using SqlConnection connection = await OpenAsync(); + + int first = await Proc(procedure) + .Params() + .Output("doubled") + .Using(connection) + .AddParams(new IdOnly(4)) + .ExecuteOutputAsync(Token); + int second = await Proc(procedure) + .Output("doubled") + .Params() + .Using(connection) + .AddParams(new IdOnly(5)) + .ExecuteOutputAsync(Token); + + Assert.Equal(8, first); + Assert.Equal(10, second); + } + + [Fact] + public static async Task AFailedOutputMatch_ForgetsTheNames_SoTheNextCallReadsThemAgain() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = Procedure( + "@a int = null output", + "set @a = 1;"); + await using SqlConnection connection = await OpenAsync(); + OutputDbNonQuery definition = Proc(procedure).Output("b"); + + await Assert.ThrowsAsync( + async () => await definition.Using(connection).ExecuteOutputAsync(Token)); + + // The procedure now declares @b; a remembered set would still say @a. + await using SqlCommand alter = connection.CreateCommand(); + alter.CommandText = "alter procedure dbo." + procedure.Name + + " @a int = null output, @b int output as set nocount on; set @a = 1; set @b = 2;"; + await alter.ExecuteNonQueryAsync(Token); + + Assert.Equal(2, await definition.Using(connection).ExecuteOutputAsync(Token)); + } +} From 2bdc77cc48738fb4b38061e06a3ac899b4099ef9 Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Wed, 2 Dec 2026 09:34:33 -0800 Subject: [PATCH 02/17] Captures work on the calls of a stored definition A capture can now be added per call on a query made from a stored DbQuery definition (X.Using(factory).AddParam(...).CaptureOutput(...)), and on a bound write or scalar call through extension methods of those two kinds. A call made from Output has no capture members, so a capture there is a compile error. A capture before or after AddParam gives the same call, and a kept or branched call that carries a capture runs once. A definition's call fills its captures through its own runner (DbQueryRunner.RunCapturedAsync and the write and scalar forms), which claims the captures when the terminal is called, copies the outputs off the command before it is disposed, and completes every capture on every exit. A query from a definition has no command, so its cancellation token and its captures are its own. ExecuteReturnAsync refuses a capture that reads the return code and runs beside an output-only capture. A bound call's equality includes its captures by reference; a call without one hashes as before. Co-Authored-By: Claude Sonnet 5.5 --- Source/Core/BoundCall.cs | 260 +++++++++- Source/Core/Capture.cs | 57 ++- Source/Core/DbQueryCall.cs | 17 + Source/Core/DbQueryRunner.Output.cs | 37 +- Source/Core/MappedQuery.Capture.cs | 19 +- Source/Core/MappedQuery.cs | 19 +- Source/Core/Output.docs.xml | 29 +- Source/Core/OutputBinding.cs | 15 +- Source/Core/PublicAPI.Unshipped.txt | 8 + .../CaptureDefinitionLocalDbTests.cs | 459 ++++++++++++++++++ 10 files changed, 833 insertions(+), 87 deletions(-) create mode 100644 Tests/Open.Database.Extensions.Core.Tests/CaptureDefinitionLocalDbTests.cs diff --git a/Source/Core/BoundCall.cs b/Source/Core/BoundCall.cs index 8d9ba582..d3e76fa9 100644 --- a/Source/Core/BoundCall.cs +++ b/Source/Core/BoundCall.cs @@ -34,7 +34,16 @@ namespace Open.Database.Extensions; /// public readonly struct BoundCall : IEquatable> { - internal BoundCall(DbQueryCall call) => Call = call; + internal BoundCall(DbQueryCall call, CaptureSet? captures = null) + { + Call = call; + Captures = captures; + } + + // The captures the call carries, or null. Added by the capture extensions + // of BoundCallExtensions after Using and the parameters, and carried by + // every AddParam; compared by reference. + internal CaptureSet? Captures { get; } // The same value a rows query holds: the definition, the source and the // values. @@ -46,26 +55,27 @@ namespace Open.Database.Extensions; /// public BoundCall AddParams(TValues values) where TValues : notnull - => new(Call.AddParams(values)); + => new(Call.AddParams(values), Captures); /// public BoundCall AddParam(string name, TValue value) - => new(Call.AddParam(name, value)); + => new(Call.AddParam(name, value), Captures); /// public BoundCall AddParam(string name, string? value) - => new(Call.AddParam(name, value)); + => new(Call.AddParam(name, value), Captures); /// [OverloadResolutionPriority(-1)] public BoundCall AddParam( TValue value, [CallerArgumentExpression(nameof(value))] string? expression = null) - => new(Call.AddParam(value, expression)); + => new(Call.AddParam(value, expression), Captures); /// public bool Equals(BoundCall other) - => Call.Equals(other.Call); + => Call.Equals(other.Call) + && ReferenceEquals(Captures, other.Captures); /// public override bool Equals(object? obj) @@ -90,7 +100,12 @@ public override int GetHashCode() { unchecked { - return Call.GetHashCode() * 31 + typeof(TKind).GetHashCode(); + int hash = Call.GetHashCode() * 31 + typeof(TKind).GetHashCode(); + + // Without a capture the hash is what it always was. + return Captures is null + ? hash + : hash * 31 + RuntimeHelpers.GetHashCode(Captures); } } } @@ -170,6 +185,8 @@ public BoundCall Using( // DbQuery.Using throws ArgumentNullException for a null source. => Bind(Definition.Using(factory)); + // A call made here has no captures: a capture is added after Using, on the + // bound call. BoundCall Bind(DbQueryUsing root) => new(root.WithParams(_list)); } @@ -269,11 +286,13 @@ public static class BoundCallExtensions public static ValueTask ExecuteScalarAsync( this BoundCall> call, CancellationToken cancellationToken = default) - => DbQueryRunner.ScalarAsync( - call.Call.Definition, - call.Call.SourceCore, - call.Call.Params, - cancellationToken); + => call.Captures is { } captures + ? DbQueryRunner.ScalarCapturedAsync( + call.Call.Definition, call.Call.SourceCore, call.Call.Params, + captures, cancellationToken) + : DbQueryRunner.ScalarAsync( + call.Call.Definition, call.Call.SourceCore, + call.Call.Params, cancellationToken); /// Runs the write and returns the number of rows affected. /// @@ -289,11 +308,13 @@ public static ValueTask ExecuteScalarAsync( public static ValueTask ExecuteNonQueryAsync( this BoundCall call, CancellationToken cancellationToken = default) - => DbQueryRunner.NonQueryAsync( - call.Call.Definition, - call.Call.SourceCore, - call.Call.Params, - cancellationToken); + => call.Captures is { } captures + ? DbQueryRunner.NonQueryCapturedAsync( + call.Call.Definition, call.Call.SourceCore, call.Call.Params, + captures, cancellationToken) + : DbQueryRunner.NonQueryAsync( + call.Call.Definition, call.Call.SourceCore, + call.Call.Params, cancellationToken); /// /// Runs the write and reads its output parameters (and return code) as the @@ -313,10 +334,8 @@ public static ValueTask ExecuteOutputAsync( this BoundCall> call, CancellationToken cancellationToken = default) => DbQueryRunner.OutputAsync( - call.Call.Definition, - call.Call.SourceCore, - call.Call.Params, - cancellationToken); + call.Call.Definition, call.Call.SourceCore, + call.Call.Params, cancellationToken); /// /// Runs the write and returns the stored procedure's return code, converted @@ -345,11 +364,208 @@ public static ValueTask ExecuteReturnAsync( + "Declare the definition with DbNonQuery.Procedure(name) to read the return code."); } + // A capture of the return code and this would read it twice. + if (call.Captures?.ReturnReader is { } returnReader) + { + throw call.Captures.Refuse( + new InvalidOperationException( + CaptureMessages.ReturnBeside(returnReader)), + cancellationToken); + } + return DbQueryRunner.ReturnAsync( definition, call.Call.SourceCore, call.Call.Params, - null, + call.Captures, cancellationToken); } + + // ---- 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. + static BoundCall WithCapture( + BoundCall call, + ICaptureSource source) + => new( + call.Call, + CaptureSet.WithOnDefinition( + call.Captures, source, call.Call.Definition.Kind)); + + /// + /// Reads the output parameters into a when the + /// write runs: a model by its members, or one value by the name of the + /// variable. + /// + /// + /// + /// The bound write. + /// The name of the output parameter of a single value; the compiler supplies the variable's name when it is left out. + public static BoundCall CaptureOutput( + this BoundCall call, + out DbCapture output, + [CallerArgumentExpression(nameof(output))] string? name = null) + { + CaptureSource source = Captures.Output(name); + BoundCall captured = WithCapture(call, source); + output = new(source); + return captured; + } + + /// + /// Reads one output parameter of the given precision + /// and scale when the write runs. A NULL faults the capture; + /// CaptureOutputDecimal reads it as . + /// + /// + /// + /// + /// The bound write. + public static BoundCall CaptureOutput( + this BoundCall call, + out DbCapture value, + byte precision, + byte scale, + [CallerArgumentExpression(nameof(value))] string? name = null) + { + CaptureSource source = Captures.Shaped( + name!, + precision, + scale); + BoundCall captured = WithCapture(call, source); + value = new(source); + return captured; + } + + /// + /// Reads one output parameter of the given precision + /// and scale when the write runs. + /// + /// + /// + /// + /// The bound write. + public static BoundCall CaptureOutputDecimal( + this BoundCall call, + out DbCapture value, + byte precision, + byte scale, + [CallerArgumentExpression(nameof(value))] string? name = null) + { + CaptureSource source = Captures.Decimal( + name!, + precision, + scale); + BoundCall captured = WithCapture(call, source); + value = new(source); + return captured; + } + + /// + /// Reads the stored procedure's return code, converted to + /// , when the write runs. + /// + /// + /// + /// The bound write. + public static BoundCall CaptureReturn( + this BoundCall call, + out DbCapture returnCode) + { + CaptureSource source = Captures.Return(); + BoundCall captured = WithCapture(call, source); + returnCode = new(source); + return captured; + } + + /// + /// Reads the output parameters into a when the + /// query runs: a model by its members, or one value by the name of the + /// variable. + /// + /// The type of the scalar, from the call. + /// + /// + /// The bound scalar query. + /// The name of the output parameter of a single value; the compiler supplies the variable's name when it is left out. + public static BoundCall> CaptureOutput( + this BoundCall> call, + out DbCapture output, + [CallerArgumentExpression(nameof(output))] string? name = null) + { + CaptureSource source = Captures.Output(name); + BoundCall> captured = WithCapture(call, source); + output = new(source); + return captured; + } + + /// + /// Reads one output parameter of the given precision + /// and scale when the query runs. A NULL faults the capture; + /// CaptureOutputDecimal reads it as . + /// + /// The type of the scalar, from the call. + /// + /// + /// + /// The bound scalar query. + public static BoundCall> CaptureOutput( + this BoundCall> call, + out DbCapture value, + byte precision, + byte scale, + [CallerArgumentExpression(nameof(value))] string? name = null) + { + CaptureSource source = Captures.Shaped( + name!, + precision, + scale); + BoundCall> captured = WithCapture(call, source); + value = new(source); + return captured; + } + + /// + /// Reads one output parameter of the given precision + /// and scale when the query runs. + /// + /// The type of the scalar, from the call. + /// + /// + /// + /// The bound scalar query. + public static BoundCall> CaptureOutputDecimal( + this BoundCall> call, + out DbCapture value, + byte precision, + byte scale, + [CallerArgumentExpression(nameof(value))] string? name = null) + { + CaptureSource source = Captures.Decimal( + name!, + precision, + scale); + BoundCall> captured = WithCapture(call, source); + value = new(source); + return captured; + } + + /// + /// Reads the stored procedure's return code, converted to + /// , when the query runs. + /// + /// The type of the scalar, from the call. + /// + /// + /// The bound scalar query. + public static BoundCall> CaptureReturn( + this BoundCall> call, + out DbCapture returnCode) + { + CaptureSource source = Captures.Return(); + BoundCall> captured = WithCapture(call, source); + returnCode = new(source); + return captured; + } } diff --git a/Source/Core/Capture.cs b/Source/Core/Capture.cs index 9bc663c6..6770a151 100644 --- a/Source/Core/Capture.cs +++ b/Source/Core/Capture.cs @@ -425,6 +425,37 @@ public static CaptureSet With( return new([.. set.Sources, source], onQuery || set.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 With(set, source, onQuery: true); + } + /// /// 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. @@ -804,6 +835,18 @@ static class Captures public static CaptureSource Model() => new ModelCapture(OutputLayout.Get(OutputForm.Capture)); + /// Makes the capture of an output model, or, when + /// is a single value, of the parameter the name + /// gives. + /// The model type, or the type of the value. + /// The name of the parameter of a single value; a model + /// ignores it. + /// The capture. + public static CaptureSource Output(string? name) + => Shape.IsScalar(typeof(TOut)) + ? Named(name!) + : Model(); + /// Makes the capture of one output parameter by name. /// The type of the value. /// The parameter's name. @@ -874,11 +917,8 @@ static NamedCapture Decimal( OutputForm.Capture); return new NamedCapture( OutputValue.Shaped( - name, - precision, - scale, - display, - OutputForm.Capture), + name, precision, scale, + display, OutputForm.Capture), name, display); } @@ -1022,13 +1062,6 @@ public static string ReturnModel(string type) + "Use CaptureReturn (or int?, long, an enum), " + "or a ReturnValue member on the output model."; - public static string NotFromDefinition(ICaptureSource source) - => $"{source.Display} needs a query built from an expressive command " - + "(connection.Command(…).Map()); " - + "a query from a DbQuery definition cannot take a capture. " - + "Build it from a command, " - + "or read the outputs with ExecuteOutputAsync."; - public static string NotFromCommand(ICaptureSource source, Type reader) => $"{source.Display} needs a query built from an expressive command " + "(connection.Command(…).Map()), " diff --git a/Source/Core/DbQueryCall.cs b/Source/Core/DbQueryCall.cs index a1a8112d..69ce516a 100644 --- a/Source/Core/DbQueryCall.cs +++ b/Source/Core/DbQueryCall.cs @@ -346,6 +346,23 @@ internal TResult Run( transform, behavior); + /// Runs the query with the given state and fills captures. + internal ValueTask RunCapturedAsync( + CaptureHolder captures, + TState state, + Func> transform, + CommandBehavior behavior, + CancellationToken cancellationToken) + => DbQueryRunner.RunCapturedAsync( + Definition, + SourceCore, + Params, + captures, + state, + transform, + behavior, + cancellationToken); + /// internal ValueTask RunAsync( TState state, diff --git a/Source/Core/DbQueryRunner.Output.cs b/Source/Core/DbQueryRunner.Output.cs index a1f24ab4..a5cf3098 100644 --- a/Source/Core/DbQueryRunner.Output.cs +++ b/Source/Core/DbQueryRunner.Output.cs @@ -93,9 +93,7 @@ public static ValueTask OutputAsync( ?? throw new InvalidOperationException( "This call's definition declares no outputs: make it with Output()."); return ExecuteWithOutputAsync( - definition, - source, - call, + definition, source, call, new OutputRun(layout), static (command, token) => command.ExecuteNonQueryAsync(token), static (_, run) => run.Layout.Members[0].Named @@ -134,19 +132,14 @@ public static ValueTask ReturnAsync( CancellationToken cancellationToken) => captures is null ? ExecuteWithOutputAsync( - definition, - source, - call, + definition, source, call, new OutputRun(ReturnOutput.Layout), static (command, token) => command.ExecuteNonQueryAsync(token), static (_, run) => run.Single(), cancellationToken) : CapturedAsync( - definition, - source, - call, - captures, - readReturn: true, + definition, source, call, + captures, readReturn: true, static (command, token) => command.ExecuteNonQueryAsync(token), static (_, run) => RowMap.ConvertScalar( run.Value(run.Layout.Members.Length - 1)), @@ -166,11 +159,8 @@ public static ValueTask NonQueryCapturedAsync( CaptureSet captures, CancellationToken cancellationToken) => CapturedAsync( - definition, - source, - call, - captures, - readReturn: false, + definition, source, call, + captures, readReturn: false, static (command, token) => command.ExecuteNonQueryAsync(token), static (count, _) => count, cancellationToken); @@ -190,11 +180,8 @@ public static ValueTask ScalarCapturedAsync( CaptureSet captures, CancellationToken cancellationToken) => CapturedAsync( - definition, - source, - call, - captures, - readReturn: false, + definition, source, call, + captures, readReturn: false, static (command, token) => command.ExecuteScalarAsync(token), static (value, _) => RowMap.ConvertScalar( value, @@ -221,9 +208,7 @@ static async ValueTask CapturedAsync( ? WithReturn(run.Set.Layout) : run.Set.Layout; return await ExecuteWithOutputAsync( - definition, - source, - call, + definition, source, call, new OutputRun(layout), execute, (value, output) => @@ -241,6 +226,8 @@ static async ValueTask CapturedAsync( run.Fail(ex); throw; } + // A finally, not a dispose: whatever the run left pending is completed on + // every exit, which a dispose cannot express. finally { run.Backstop(); @@ -432,6 +419,8 @@ public static async ValueTask RunCapturedAsync( run.Fail(ex); throw; } + // A finally, not a dispose: whatever the run left pending is completed on + // every exit, which a dispose cannot express. finally { run.Backstop(); diff --git a/Source/Core/MappedQuery.Capture.cs b/Source/Core/MappedQuery.Capture.cs index b4fd321c..51fad7af 100644 --- a/Source/Core/MappedQuery.Capture.cs +++ b/Source/Core/MappedQuery.Capture.cs @@ -35,6 +35,10 @@ readonly partial struct MappedQueryCore public CaptureRun? CapturedRun => _captures as CaptureRun; + // A query from a definition has no command, so no token of its own. + CancellationToken CommandToken + => _call.IsBound ? default : _command!.CancellationToken; + /// /// Returns the query with one more capture. /// @@ -54,8 +58,15 @@ public MappedQueryCore WithCapture(ICaptureSource source) EnsureCommand(); if (_call.IsBound) { - throw new NotSupportedException( - CaptureMessages.NotFromDefinition(source)); + // 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)); } if (_command is not ICaptureRunner runner) { @@ -111,7 +122,7 @@ CaptureRun StreamRun( CancellationToken cancellationToken) { var run = new CaptureRun(captures); - run.Owners(cancellationToken, default, _command!.CancellationToken); + run.Owners(cancellationToken, default, CommandToken); return run; } @@ -127,7 +138,7 @@ PooledBuffer CapturedBuffer( CancellationToken cancellationToken) { CaptureRun run = captures.Claim(cancellationToken); - run.Owners(cancellationToken, default, _command!.CancellationToken); + run.Owners(cancellationToken, default, CommandToken); try { return new(WithRun(run), Config, cancellationToken); diff --git a/Source/Core/MappedQuery.cs b/Source/Core/MappedQuery.cs index 67c034cc..9220cd04 100644 --- a/Source/Core/MappedQuery.cs +++ b/Source/Core/MappedQuery.cs @@ -344,13 +344,10 @@ public MappedQueryCore WithConfig(ChunkConfig config) _skip, _take, Options, config, _captures)); /// Returns the same query over another call. - /// The query carries a capture, - /// which only a command can fill. + // The captures go with it, so a capture before or after AddParam is the + // same call. public MappedQueryCore WithCall(DbQueryCall call) - => _captures is null - ? new(null, call, _source, _skip, _take, Options, Config) - : throw new InvalidOperationException( - CaptureMessages.NotFromDefinition(_captures.Set.Sources[0])); + => new(null, call, _source, _skip, _take, Options, Config, _captures); public MappedQueryCore WithSkip(int count) => count >= 0 @@ -494,13 +491,13 @@ TResult ExecuteReader(TState state, FuncRuns the asynchronous reader function on the call, held as it is, or on the command. // With captures (the query's or its command's), the command's own reader - // path fills them (only a command can be given them: see WithCapture). + // path fills them, or the definition's runner when the query has no command. // A command that re-implements IExecuteReader is refused here, when a // mapped query over it runs with captures: a capture made on the command, // not the query, is not checked at a capture call, and the command's own // terminals do not use the re-implemented reader. Its own reader would // skip the output parameters. The refusal is the task's exception, and - // completes every capture. + // completes every capture. A definition's call has no command to refuse. ValueTask ExecuteReaderAsync(TState state, Func> transform, CommandBehavior behavior, CancellationToken token) { if (Captured() is not { } captures) @@ -510,6 +507,12 @@ ValueTask ExecuteReaderAsync(TState state, Func At the call: cannot be read from output parameters (a single value, or a type with 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). @@ -205,7 +206,7 @@ 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; + At the call: is a model; or the definition is text, which has no return code; or another capture reads the return code. @@ -236,8 +237,9 @@ 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. + 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. The capture is complete when the terminal's task is. A stream's capture completes when its enumerator is disposed: await it after the loop. @@ -250,11 +252,28 @@ A query that carries a capture runs once, with an async terminal only: a synchronous terminal and CancelOnEarlyStop() throw, and so does a second run. - It is available on a query built from an expressive command (Map, and the views that skip or take rows); - one from a DbQuery definition throws. + It is available on a query built from an expressive command (Map, and the views that skip or take rows) + and on a query made from a stored DbQuery definition (X.Using(factory).AddParam(…)): add it per call, + after Using and the parameters, never on the stored definition, because a capture is used once. + A capture before or after AddParam gives the same call. + + + The query is not built from an expressive command or a definition, or its command re-implements IExecuteReader (thrown at the call). + + + + A copy of the call that carries the capture; its async terminal fills it. + + + Add it per call, after Using and the parameters, never on the stored definition: a capture is used once. + Kept or branched copies of the call share it, so the second run of any of them throws, and a new capture on a new call runs again. + It is complete when the terminal's task is, and fills beside ExecuteScalarAsync or ExecuteNonQueryAsync; + a call made from Output reads every output already, so it takes no capture. + + + The type comes from the declared type of the variable, as in CaptureOutput(out DbCapture<int> total). - The query is not built from an expressive command, or its command re-implements IExecuteReader (thrown at the call). diff --git a/Source/Core/OutputBinding.cs b/Source/Core/OutputBinding.cs index 1424ee1f..506eeba7 100644 --- a/Source/Core/OutputBinding.cs +++ b/Source/Core/OutputBinding.cs @@ -153,24 +153,15 @@ public static void Resolve( // One candidate, the name as given: remembered by that name. if (member.Candidates.IsDefault) { - return real.MatchName( - member.Name, - commandText, - member.Display, - fix); + return real.MatchName(member.Name, commandText, member.Display, fix); } // Not NameSet.Match: its memo is keyed by the text of an argument // expression, which AddParam shares, and its candidates include chain // names. Not MatchName either: its memo answers for one candidate. return ParameterNames.MatchBareAs( - member.Candidates, - real.Names, - real.BareNames, - member.Name, - commandText, - member.Display, - fix); + member.Candidates, real.Names, real.BareNames, + member.Name, commandText, member.Display, fix); } /// diff --git a/Source/Core/PublicAPI.Unshipped.txt b/Source/Core/PublicAPI.Unshipped.txt index d8d929e1..ccd72e6d 100644 --- a/Source/Core/PublicAPI.Unshipped.txt +++ b/Source/Core/PublicAPI.Unshipped.txt @@ -156,3 +156,11 @@ Open.Database.Extensions.DbNonQuery.Output(string! name, byte precis Open.Database.Extensions.DbNonQuery.OutputDecimal(string! name, byte precision, byte scale) -> Open.Database.Extensions.OutputDbNonQuery! static Open.Database.Extensions.BoundCallExtensions.ExecuteOutputAsync(this Open.Database.Extensions.BoundCall> call, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask static Open.Database.Extensions.BoundCallExtensions.ExecuteReturnAsync(this Open.Database.Extensions.BoundCall call, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +static Open.Database.Extensions.BoundCallExtensions.CaptureOutput(this Open.Database.Extensions.BoundCall call, out Open.Database.Extensions.DbCapture output, string? name = null) -> Open.Database.Extensions.BoundCall +static Open.Database.Extensions.BoundCallExtensions.CaptureOutput(this Open.Database.Extensions.BoundCall call, out Open.Database.Extensions.DbCapture value, byte precision, byte scale, string? name = null) -> Open.Database.Extensions.BoundCall +static Open.Database.Extensions.BoundCallExtensions.CaptureOutputDecimal(this Open.Database.Extensions.BoundCall call, out Open.Database.Extensions.DbCapture value, byte precision, byte scale, string? name = null) -> Open.Database.Extensions.BoundCall +static Open.Database.Extensions.BoundCallExtensions.CaptureReturn(this Open.Database.Extensions.BoundCall call, out Open.Database.Extensions.DbCapture returnCode) -> Open.Database.Extensions.BoundCall +static Open.Database.Extensions.BoundCallExtensions.CaptureOutput(this Open.Database.Extensions.BoundCall> call, out Open.Database.Extensions.DbCapture output, string? name = null) -> Open.Database.Extensions.BoundCall> +static Open.Database.Extensions.BoundCallExtensions.CaptureOutput(this Open.Database.Extensions.BoundCall> call, out Open.Database.Extensions.DbCapture value, byte precision, byte scale, string? name = null) -> Open.Database.Extensions.BoundCall> +static Open.Database.Extensions.BoundCallExtensions.CaptureOutputDecimal(this Open.Database.Extensions.BoundCall> call, out Open.Database.Extensions.DbCapture value, byte precision, byte scale, string? name = null) -> Open.Database.Extensions.BoundCall> +static Open.Database.Extensions.BoundCallExtensions.CaptureReturn(this Open.Database.Extensions.BoundCall> call, out Open.Database.Extensions.DbCapture returnCode) -> Open.Database.Extensions.BoundCall> diff --git a/Tests/Open.Database.Extensions.Core.Tests/CaptureDefinitionLocalDbTests.cs b/Tests/Open.Database.Extensions.Core.Tests/CaptureDefinitionLocalDbTests.cs new file mode 100644 index 00000000..9bed76f7 --- /dev/null +++ b/Tests/Open.Database.Extensions.Core.Tests/CaptureDefinitionLocalDbTests.cs @@ -0,0 +1,459 @@ +using Microsoft.Data.SqlClient; +using System.ComponentModel.DataAnnotations.Schema; + +#nullable enable + +namespace Open.Database.Extensions.Tests; + +// Captures on the calls of a stored definition (X.Using(factory)...), against +// SQL Server: a query's rows, a write, a scalar, and the single use that a +// capture brings. Skipped without LocalDB (see LocalDbFixture). +[ExcludeFromCodeCoverage] +[Collection("LocalDB DDL")] +public static class CaptureDefinitionLocalDbTests +{ + static CancellationToken Token => TestContext.Current.CancellationToken; + + public sealed record Row(int Id); + + public sealed record Page(int Total, int Pages); + + public sealed record TotalOnly(int Total); + + public sealed record WithCode(int Total, int ReturnValue); + + const string ManyRows + = "select top (50000) row_number() over (order by (select null)) as Id" + + " from sys.all_objects a cross join sys.all_objects b;"; + + static LocalDbFixture.Scratch Procedure(string parameters, string body) + => LocalDbFixture.CreateProcedureWithBody( + parameters, + "set nocount on; " + body, + "ode_cd"); + + static async Task OpenAsync() + { + SqlConnection connection = LocalDbFixture.Create(); + await connection.OpenAsync(Token); + return connection; + } + + static MappedDbQuery Rows(LocalDbFixture.Scratch procedure) + => DbQuery.Procedure("dbo." + procedure.Name).Map(); + + static LocalDbFixture.Scratch PageProcedure() + => Procedure( + "@page int = 1, @total int = null output, @pages int = null output", + "select n as Id from (values (1), (2), (3)) v(n);" + + " set @total = 30 + @page; set @pages = 3; return 7;"); + + [Fact] + public static async Task ARowsQueryFromADefinition_FillsAModelCapture() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = PageProcedure(); + await using SqlConnection connection = await OpenAsync(); + + List rows = await Rows(procedure) + .Using(connection) + .AddParam("page", 2) + .CaptureOutput(out DbCapture page) + .ToListAsync(Token); + + Assert.Equal([1, 2, 3], rows.Select(static r => r.Id)); + Assert.Equal(new Page(32, 3), await page); + } + + [Fact] + public static async Task ACaptureBeforeOrAfterAddParam_IsTheSameCall() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = PageProcedure(); + await using SqlConnection connection = await OpenAsync(); + MappedDbQuery definition = Rows(procedure); + + MappedQuery before = definition + .Using(connection) + .CaptureOutput(out DbCapture first) + .AddParam("page", 2); + MappedQuery after = definition + .Using(connection) + .AddParam("page", 2) + .CaptureOutput(out DbCapture second); + + await before.ToListAsync(Token); + await after.ToListAsync(Token); + + Assert.Equal(new Page(32, 3), await first); + Assert.Equal(new Page(32, 3), await second); + } + + [Fact] + public static async Task AKeptQueryWithACapture_RunsOnce() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = PageProcedure(); + await using SqlConnection connection = await OpenAsync(); + MappedQuery kept = Rows(procedure) + .Using(connection) + .CaptureOutput(out DbCapture page); + + await kept.ToListAsync(Token); + var ex = await Assert.ThrowsAsync( + async () => await kept.ToListAsync(Token)); + + Assert.Contains("already used by an earlier run of this query", ex.Message); + Assert.Equal(new Page(31, 3), await page); + } + + [Fact] + public static async Task AStreamFromADefinition_FillsTheCaptureAfterTheLoop_EvenOnBreak() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = Procedure( + "@total int output", + ManyRows + " set @total = 50000;"); + await using SqlConnection connection = await OpenAsync(); + + var seen = 0; + IAsyncEnumerable stream = Rows(procedure) + .Using(connection) + .CaptureOutput(out DbCapture total) + .ToPooledStream(Token); + await foreach (Row row in stream) + { + seen++; + break; + } + + Assert.Equal(1, seen); + // Closing the reader read the rest of the response. + Assert.Equal(new TotalOnly(50000), await total); + } + + [Fact] + public static async Task AStreamFromADefinition_ReadToTheEnd_FillsTheCapture() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = PageProcedure(); + await using SqlConnection connection = await OpenAsync(); + + MappedQuery query = Rows(procedure) + .Using(connection) + .CaptureOutput(out DbCapture page); + var ids = new List(); + await foreach (Row row in query.ToPooledStream(Token)) + { + ids.Add(row.Id); + } + + Assert.Equal([1, 2, 3], ids); + Assert.Equal(new Page(31, 3), await page); + } + + [Fact] + public static async Task APooledBuffer_FromADefinition_FillsTheCapture() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = PageProcedure(); + await using SqlConnection connection = await OpenAsync(); + + using PooledBuffer buffer = Rows(procedure) + .Using(connection) + .CaptureOutput(out DbCapture page) + .ToPooledBuffer(Token); + + Assert.Equal(3, (await buffer.Items).Count); + Assert.Equal(new Page(31, 3), await page); + } + + [Fact] + public static async Task ASynchronousTerminal_WithACapture_IsRefusedAndClaimsNothing() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = PageProcedure(); + await using SqlConnection connection = await OpenAsync(); + MappedQuery query = Rows(procedure) + .Using(connection) + .CaptureOutput(out DbCapture page); + + var ex = Assert.Throws(() => query.ToList()); + + Assert.Contains("captures only work with async terminals", ex.Message); + // Nothing was claimed: the async terminal still runs it. + await query.ToListAsync(Token); + Assert.Equal(new Page(31, 3), await page); + } + + [Fact] + public static async Task CancelOnEarlyStop_WithACapture_IsRefusedAndTheCaptureCompletes() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = PageProcedure(); + await using SqlConnection connection = await OpenAsync(); + MappedQuery query = Rows(procedure) + .Using(connection) + .CancelOnEarlyStop() + .CaptureOutput(out DbCapture page); + + var ex = await Assert.ThrowsAsync( + async () => await query.ToListAsync(Token)); + + Assert.Contains("cannot be used with CancelOnEarlyStop()", ex.Message); + await Assert.ThrowsAsync(async () => await page); + } + + [Fact] + public static async Task AFailedRun_CompletesTheCaptureWithTheSameError() + { + LocalDbFixture.SkipUnlessAvailable(); + await using SqlConnection connection = await OpenAsync(); + MappedQuery query = DbQuery + .Procedure("dbo.ode_cd_no_such_procedure") + .Map() + .Using(connection) + .CaptureOutput(out DbCapture page); + + var terminal = await Assert.ThrowsAnyAsync( + async () => await query.ToListAsync(Token)); + var capture = await Assert.ThrowsAnyAsync( + async () => await page); + + Assert.Equal(terminal.GetType(), capture.GetType()); + Assert.Equal(terminal.Message, capture.Message); + } + + [Fact] + public static async Task ACanceledToken_CancelsTheCapture() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = PageProcedure(); + await using SqlConnection connection = await OpenAsync(); + using var source = new CancellationTokenSource(); + await source.CancelAsync(); + MappedQuery query = Rows(procedure) + .Using(connection) + .CaptureOutput(out DbCapture page); + + await Assert.ThrowsAnyAsync( + async () => await query.ToListAsync(source.Token)); + await Assert.ThrowsAnyAsync( + async () => await page); + } + + [Fact] + public static async Task AWrite_ReadsRowsAffectedAndOutputs() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = Procedure( + "@id int, @doubled int output", + "set @doubled = @id * 2; return 5;"); + await using SqlConnection connection = await OpenAsync(); + DbNonQuery write = DbNonQuery.Procedure("dbo." + procedure.Name); + + int rows = await write + .Using(connection) + .AddParam("id", 21) + .CaptureOutput(out DbCapture doubled, "doubled") + .CaptureReturn(out DbCapture code) + .ExecuteNonQueryAsync(Token); + + Assert.Equal(-1, rows); + Assert.Equal(42, await doubled); + Assert.Equal(5, await code); + } + + [Fact] + public static async Task AScalarQuery_ReadsTheValueAndAnOutput() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = Procedure( + "@total int output", + "select 99; set @total = 12;"); + await using SqlConnection connection = await OpenAsync(); + + int value = await DbQuery + .Procedure("dbo." + procedure.Name) + .Scalar() + .Using(connection) + .CaptureOutput(out DbCapture total, "total") + .ExecuteScalarAsync(Token); + + Assert.Equal(99, value); + Assert.Equal(12, await total); + } + + [Fact] + public static async Task AKeptWrite_AndAKeptScalar_WithACapture_RunOnce() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = Procedure( + "@total int output", + "select 1; set @total = 12;"); + await using SqlConnection connection = await OpenAsync(); + string name = "dbo." + procedure.Name; + BoundCall write = DbNonQuery.Procedure(name) + .Using(connection) + .CaptureOutput(out DbCapture first, "total"); + BoundCall> scalar = DbQuery.Procedure(name) + .Scalar() + .Using(connection) + .CaptureOutput(out DbCapture second, "total"); + + await write.ExecuteNonQueryAsync(Token); + await scalar.ExecuteScalarAsync(Token); + var again = await Assert.ThrowsAsync( + async () => await write.ExecuteNonQueryAsync(Token)); + var scalarAgain = await Assert.ThrowsAsync( + async () => await scalar.ExecuteScalarAsync(Token)); + + Assert.Contains("already used by an earlier run", again.Message); + Assert.Contains("already used by an earlier run", scalarAgain.Message); + Assert.Equal(12, await first); + Assert.Equal(12, await second); + } + + [Fact] + public static async Task ABranchedCall_SharesTheCaptureAndSoRunsOnce() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = Procedure( + "@id int = 0, @total int output", + "set @total = @id;"); + await using SqlConnection connection = await OpenAsync(); + BoundCall root = DbNonQuery + .Procedure("dbo." + procedure.Name) + .Using(connection) + .CaptureOutput(out DbCapture total, "total"); + BoundCall left = root.AddParam("id", 1); + BoundCall right = root.AddParam("id", 2); + + await left.ExecuteNonQueryAsync(Token); + await Assert.ThrowsAsync( + async () => await right.ExecuteNonQueryAsync(Token)); + + Assert.Equal(1, await total); + } + + [Fact] + public static async Task ExecuteReturnAsync_RefusesACaptureThatReadsTheReturnCode_AndRunsBesideAnOutputCapture() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = Procedure( + "@total int output", + "set @total = 8; return 3;"); + await using SqlConnection connection = await OpenAsync(); + DbNonQuery write = DbNonQuery.Procedure("dbo." + procedure.Name); + + BoundCall withCode = write + .Using(connection) + .CaptureReturn(out DbCapture code); + BoundCall withModel = write + .Using(connection) + .CaptureOutput(out DbCapture model); + var first = await Assert.ThrowsAsync( + async () => await withCode.ExecuteReturnAsync(Token)); + var second = await Assert.ThrowsAsync( + async () => await withModel.ExecuteReturnAsync(Token)); + int status = await write + .Using(connection) + .CaptureOutput(out DbCapture total, "total") + .ExecuteReturnAsync(Token); + + Assert.Contains("reads its return code twice", first.Message); + Assert.Contains("reads its return code twice", second.Message); + Assert.Equal(3, status); + Assert.Equal(8, await total); + // The refused captures were completed with the refusal. + await Assert.ThrowsAsync(async () => await code); + await Assert.ThrowsAsync(async () => await model); + } + + [Fact] + public static async Task AModelWithReturnValue_IsReadByACapture() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = Procedure( + "@total int output", + "set @total = 8; return 3;"); + await using SqlConnection connection = await OpenAsync(); + + await DbNonQuery.Procedure("dbo." + procedure.Name) + .Using(connection) + .CaptureOutput(out DbCapture model) + .ExecuteNonQueryAsync(Token); + + Assert.Equal(new WithCode(8, 3), 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() + { + var connection = new SqlConnection("Server=nowhere"); + DbNonQuery write = DbNonQuery.Procedure("dbo.P"); + + BoundCall a = write.Using(connection).AddParam("x", 1); + BoundCall b = write.Using(connection).AddParam("x", 1); + BoundCall c = a.CaptureOutput(out DbCapture _, "t"); + BoundCall d = b.CaptureOutput(out DbCapture _, "t"); + + Assert.Equal(a, b); + Assert.Equal(a.GetHashCode(), b.GetHashCode()); + Assert.NotEqual(a, c); + // Two captures are two owners, even for the same text. + Assert.NotEqual(c, d); + // The hash of a call without a capture is the one it always had. + Assert.Equal( + a.Call.GetHashCode() * 31 + typeof(NonQueryKind).GetHashCode(), + a.GetHashCode()); + } + + [Fact] + public static async Task AnAwaitedFault_IsNotReportedAsUnobserved() + { + LocalDbFixture.SkipUnlessAvailable(); + await using SqlConnection connection = await OpenAsync(); + var unobserved = new List(); + void Handler(object? sender, UnobservedTaskExceptionEventArgs e) + => unobserved.Add(e.Exception); + TaskScheduler.UnobservedTaskException += Handler; + try + { + MappedQuery query = DbQuery + .Procedure("dbo.ode_cd_missing") + .Map() + .Using(connection) + .CaptureOutput(out DbCapture page); + await Assert.ThrowsAnyAsync( + async () => await query.ToListAsync(Token)); + await Assert.ThrowsAnyAsync(async () => await page); + + GC.Collect(); + GC.WaitForPendingFinalizers(); + GC.Collect(); + } + finally + { + TaskScheduler.UnobservedTaskException -= Handler; + } + + Assert.Empty(unobserved); + } +} From 47f4a421c9e3fb6a06183ebd745a86713f1b7aee Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Wed, 2 Dec 2026 10:23:41 -0800 Subject: [PATCH 03/17] Captures take their name last, from the variable CaptureOutput now names its output parameter after the variable it fills: CaptureOutput(out DbCapture total) reads @total, and the name can be passed last instead: CaptureOutput(out DbCapture x, "total"). The compiler supplies the variable's text; a new scanner reads the last identifier from it (a declaration, a local, this.total, state.total, arr[0].Total) or from a typed string, with one rule for both ($ and # allowed, one leading @ or : dropped, a discard, an element access or a missing name refused with the fix). The name is matched the way AddParam's names are, over the name as written and without a field prefix. Texts that are not one plain name are worked out once each. The name-first forms are gone on the command, MappedQuery (and its skip and take views) and the bound calls. The generic shape overload is replaced by CaptureOutput(out DbCapture, precision, scale), so a wrong type with a shape is a compile error; CaptureOutputDecimal keeps the nullable form. A model ignores the name and never refuses one; when its member matches nothing, the message says the name was not used and gives both fixes. Two captures that resolve to one parameter fail the run with a capture fix. Every message that named a capture form names the new ones, and the source in a message is the command text or the procedure, as the command's messages say it. Co-Authored-By: Claude Sonnet 5.5 --- Source/Core/BoundCall.cs | 24 +- Source/Core/Capture.cs | 93 +++-- Source/Core/CaptureNames.cs | 136 +++++++ Source/Core/DbQueryCall.cs | 10 +- Source/Core/DbQueryRunner.Output.cs | 16 +- Source/Core/ExpressiveCommandBase.Capture.cs | 50 +-- Source/Core/MappedQuery.Capture.cs | 139 ++----- Source/Core/Output.docs.xml | 68 ++-- Source/Core/OutputBinding.cs | 32 +- Source/Core/OutputLayout.cs | 61 ++- Source/Core/ParameterNames.cs | 2 +- Source/Core/PublicAPI.Unshipped.txt | 28 +- .../BoundCallCaptureCompileTests.cs | 147 +++++++ .../CaptureLibraryCommandTests.cs | 4 +- .../CaptureLocalDbTests.cs | 28 +- .../CaptureNameLocalDbTests.cs | 260 ++++++++++++ .../CaptureNameTests.cs | 376 ++++++++++++++++++ .../CaptureStreamTests.cs | 26 +- .../CaptureTests.cs | 142 +++---- .../PumpStreamOpenTests.cs | 4 +- .../BoundCallCaptureBindingTests.cs | 98 +++++ docsite/articles/release-notes.md | 2 +- 22 files changed, 1362 insertions(+), 384 deletions(-) create mode 100644 Source/Core/CaptureNames.cs create mode 100644 Tests/Open.Database.Extensions.Core.Tests/BoundCallCaptureCompileTests.cs create mode 100644 Tests/Open.Database.Extensions.Core.Tests/CaptureNameLocalDbTests.cs create mode 100644 Tests/Open.Database.Extensions.Core.Tests/CaptureNameTests.cs create mode 100644 Tests/Open.Database.Extensions.LegacyCompiler.Tests/BoundCallCaptureBindingTests.cs diff --git a/Source/Core/BoundCall.cs b/Source/Core/BoundCall.cs index d3e76fa9..72e249ff 100644 --- a/Source/Core/BoundCall.cs +++ b/Source/Core/BoundCall.cs @@ -399,9 +399,9 @@ static BoundCall WithCapture( /// variable. /// /// + /// /// /// The bound write. - /// The name of the output parameter of a single value; the compiler supplies the variable's name when it is left out. public static BoundCall CaptureOutput( this BoundCall call, out DbCapture output, @@ -429,10 +429,7 @@ public static BoundCall CaptureOutput( byte scale, [CallerArgumentExpression(nameof(value))] string? name = null) { - CaptureSource source = Captures.Shaped( - name!, - precision, - scale); + CaptureSource source = Captures.Shaped(name, precision, scale); BoundCall captured = WithCapture(call, source); value = new(source); return captured; @@ -453,10 +450,7 @@ public static BoundCall CaptureOutputDecimal( byte scale, [CallerArgumentExpression(nameof(value))] string? name = null) { - CaptureSource source = Captures.Decimal( - name!, - precision, - scale); + CaptureSource source = Captures.Decimal(name, precision, scale); BoundCall captured = WithCapture(call, source); value = new(source); return captured; @@ -486,9 +480,9 @@ public static BoundCall CaptureReturn( /// /// The type of the scalar, from the call. /// + /// /// /// The bound scalar query. - /// The name of the output parameter of a single value; the compiler supplies the variable's name when it is left out. public static BoundCall> CaptureOutput( this BoundCall> call, out DbCapture output, @@ -517,10 +511,7 @@ public static BoundCall> CaptureOutput( byte scale, [CallerArgumentExpression(nameof(value))] string? name = null) { - CaptureSource source = Captures.Shaped( - name!, - precision, - scale); + CaptureSource source = Captures.Shaped(name, precision, scale); BoundCall> captured = WithCapture(call, source); value = new(source); return captured; @@ -542,10 +533,7 @@ public static BoundCall> CaptureOutputDecimal( byte scale, [CallerArgumentExpression(nameof(value))] string? name = null) { - CaptureSource source = Captures.Decimal( - name!, - precision, - scale); + CaptureSource source = Captures.Decimal(name, precision, scale); BoundCall> captured = WithCapture(call, source); value = new(source); return captured; diff --git a/Source/Core/Capture.cs b/Source/Core/Capture.cs index 6770a151..a301c80b 100644 --- a/Source/Core/Capture.cs +++ b/Source/Core/Capture.cs @@ -33,7 +33,7 @@ enum CaptureKind : byte Model, /// One output parameter by name: - /// CaptureOutput<TValue>(name, …) and + /// CaptureOutput(out DbCapture<int> total) and /// CaptureOutputDecimal. Named, @@ -215,20 +215,23 @@ public Task Started(bool awaiting) /// /// The model type. /// The model's layout. -sealed class ModelCapture(OutputLayout layout) +/// The name the capture was given, which a model does not use, or . +sealed class ModelCapture(OutputLayout layout, string? receivedName) : CaptureSource( - $"CaptureOutput<{Shape.TypeName(typeof(TOut))}>", + $"CaptureOutput(out DbCapture<{Shape.TypeName(typeof(TOut))}>)", CaptureKind.Model) { // The members named for the messages as members of this capture. public override ImmutableArray Members { get; } - = Named(layout); + = Named(layout, receivedName); public override bool ReadsReturn => layout.HasReturnValue; - static ImmutableArray Named(OutputLayout layout) + static ImmutableArray Named( + OutputLayout layout, + string? receivedName) { - string capture = $"CaptureOutput<{Shape.TypeName(typeof(TOut))}>"; + string capture = $"CaptureOutput(out DbCapture<{Shape.TypeName(typeof(TOut))}>)"; var members = ImmutableArray.CreateBuilder( layout.Members.Length); foreach (OutputMember member in layout.Members) @@ -236,7 +239,8 @@ static ImmutableArray Named(OutputLayout layout) members.Add(new OutputMember( member, $"{member.Display} of {capture}", - OutputForm.Capture)); + OutputForm.Capture, + receivedName)); } return members.MoveToImmutable(); @@ -829,97 +833,104 @@ static class Captures { /// Makes the capture of an output model. /// The model type. + /// The name the capture was given, which a model + /// does not use, or . /// The capture. /// /// cannot be read from output parameters. - public static CaptureSource Model() - => new ModelCapture(OutputLayout.Get(OutputForm.Capture)); + public static CaptureSource Model(string? receivedName = null) + => new ModelCapture( + OutputLayout.Get(OutputForm.Capture), + receivedName); /// Makes the capture of an output model, or, when - /// is a single value, of the parameter the name + /// is a single value, of the parameter its name /// gives. /// The model type, or the type of the value. - /// The name of the parameter of a single value; a model - /// ignores it. + /// The text of the capture's name argument: the + /// variable's declaration, or what the caller typed. A model never derives + /// or refuses a name. /// The capture. + /// A single value has no name in + /// . public static CaptureSource Output(string? name) => Shape.IsScalar(typeof(TOut)) - ? Named(name!) - : Model(); + ? Named(CaptureNames.From(name)) + : Model(CaptureNames.TryFrom(name)?.Name); /// Makes the capture of one output parameter by name. /// The type of the value. /// The parameter's name. /// The capture. - public static CaptureSource Named(string name) + public static CaptureSource Named(CaptureName name) { - OutputArguments.ThrowIfNoName(name, OutputForm.Capture); - OutputLayout layout = OutputValue.Get(name, OutputForm.Capture); + OutputLayout layout = OutputValue.Get( + name.Name, + OutputForm.Capture, + name.Candidates); return new NamedCapture( layout, - name, + name.Name, layout.Members[0].Display); } - /// Makes the capture of one decimal output parameter, read as - /// . - /// , or a - /// of it. - /// The parameter's name. + /// Makes the capture of one decimal output parameter, read as a + /// . + /// The text of the capture's name argument. /// The precision. /// The scale. /// The capture. - public static CaptureSource Shaped( - string name, + public static CaptureSource Shaped( + string? name, byte precision, byte scale) { - OutputArguments.ThrowIfNoName(name, OutputForm.Capture); - OutputValue.ThrowUnlessDecimal(name, OutputForm.Capture); - return Decimal( - name, + CaptureName derived = CaptureNames.From(name); + return Decimal( + derived, precision, scale, - $"CaptureOutput<{Shape.TypeName(typeof(TValue))}>" - + $"(\"{name}\", {precision}, {scale})"); + $"CaptureOutput(out DbCapture {derived.Name}, " + + $"{precision}, {scale})"); } /// Makes the capture of one decimal output parameter, read as a /// of . - /// The parameter's name. + /// The text of the capture's name argument. /// The precision. /// The scale. /// The capture. public static CaptureSource Decimal( - string name, + string? name, byte precision, byte scale) { - OutputArguments.ThrowIfNoName(name, OutputForm.Capture); + CaptureName derived = CaptureNames.From(name); return Decimal( - name, + derived, precision, scale, - $"CaptureOutputDecimal(\"{name}\", {precision}, {scale})"); + $"CaptureOutputDecimal(out DbCapture {derived.Name}, " + + $"{precision}, {scale})"); } // The one implementation of both decimal forms. static NamedCapture Decimal( - string name, + CaptureName name, byte precision, byte scale, string display) { OutputArguments.ThrowIfBadShape( - name, + name.Name, precision, scale, OutputForm.Capture); return new NamedCapture( OutputValue.Shaped( - name, precision, scale, - display, OutputForm.Capture), - name, + name.Name, precision, scale, + display, OutputForm.Capture, name.Candidates), + name.Name, display); } diff --git a/Source/Core/CaptureNames.cs b/Source/Core/CaptureNames.cs new file mode 100644 index 00000000..2daec6d2 --- /dev/null +++ b/Source/Core/CaptureNames.cs @@ -0,0 +1,136 @@ +using System.Runtime.CompilerServices; + +namespace Open.Database.Extensions; + +/// +/// The name a capture reads, and the names it is matched by. +/// +/// The name. +sealed class CaptureName(string name) +{ + /// Gets the derived name. + public string Name { get; } = name; + + /// + /// Gets the names the capture is matched by, most specific first: the name + /// as written, then without a field prefix (m_total gives + /// total). The default value means only . + /// + public ImmutableArray Candidates { get; } = Prefixed(name); + + static ImmutableArray Prefixed(string name) + { + int prefix = ParameterNames.FieldPrefixLength(name, 0, name.Length); + return prefix == 0 + ? default + : [name, name[prefix..]]; + } +} + +/// +/// Reads the name of an output parameter from the text of the capture's +/// name argument: what the compiler supplies from the variable +/// (DbCapture<int> total, this.total), or what the caller +/// typed ("total"). One rule for both. +/// +static class CaptureNames +{ + // Texts that are not one plain name are worked out once each: they are + // compile-time literals, so the table holds one entry per call site, and + // it does not keep them alive. A plain name has no entry. + static readonly ConditionalWeakTable Cache = new(); + + sealed class Parsed(CaptureName? name) + { + public CaptureName? Name { get; } = name; + } + + /// + /// Gets the name the text gives. + /// + /// The text of the argument, or what was passed. + /// The name. + /// No name can be taken from the + /// text. + public static CaptureName From(string? text) + => TryFrom(text) ?? throw NoName(text); + + /// + /// Gets the name the text gives, or when it gives + /// none. + /// + /// The text of the argument, or what was passed. + /// The name, or . + public static CaptureName? TryFrom(string? text) + { + if (string.IsNullOrWhiteSpace(text)) return null; + + if (IsPlain(text!)) + { + // A typed value: "$", "#" and the like are part of the name; one + // leading @ or : is dropped. + string plain = text![0] is '@' or ':' ? text[1..] : text; + return plain.Length == 0 || plain == "_" + ? null + : new CaptureName(plain); + } + + return Cache + .GetValue(text!, static t => new Parsed(Derive(t))) + .Name; + } + + // A plain name has none of the characters of a declaration or a chain. + static bool IsPlain(string text) + { + foreach (char c in text) + { + if (c is '.' or '[' or ']' or '(' or ')' or '<' or '>' or ',' + || char.IsWhiteSpace(c)) + { + return false; + } + } + + return true; + } + + // The last identifier: the declared variable (after its type), a local, + // or the last member of a chain. A discard, an element access that ends the + // text, and anything that does not end in an identifier have none. + static CaptureName? Derive(string text) + { + int end = text.Length; + while (end > 0 && char.IsWhiteSpace(text[end - 1])) end--; + + int start = end; + while (start > 0 + && (char.IsLetterOrDigit(text[start - 1]) || text[start - 1] == '_')) + { + start--; + } + + if (start == end || char.IsDigit(text[start])) return null; + + string name = text[start..end]; + return name == "_" ? null : new CaptureName(name); + } + + // The argument is the capture's name, which the caller sees as the optional + // last argument of every capture call. + [SuppressMessage( + "Usage", + "CA2208:Instantiate argument exceptions correctly")] + static ArgumentException NoName(string? text) + => new( + (string.IsNullOrWhiteSpace(text) + ? "The output parameter's name was not given: the compiler did " + + "not supply the variable's name (that needs a C# 10 compiler " + + "or newer, and a dynamic call gives none), or null was " + + "passed. " + : $"Cannot take the output parameter's name from '{text}': a " + + "discard (_) and an element access (arr[0]) have no name. ") + + "Declare a variable named after the parameter, or pass the name " + + "last: CaptureOutput(out DbCapture x, \"total\").", + "name"); +} diff --git a/Source/Core/DbQueryCall.cs b/Source/Core/DbQueryCall.cs index 69ce516a..d6b87780 100644 --- a/Source/Core/DbQueryCall.cs +++ b/Source/Core/DbQueryCall.cs @@ -354,14 +354,8 @@ internal ValueTask RunCapturedAsync( CommandBehavior behavior, CancellationToken cancellationToken) => DbQueryRunner.RunCapturedAsync( - Definition, - SourceCore, - Params, - captures, - state, - transform, - behavior, - cancellationToken); + Definition, SourceCore, Params, captures, + state, transform, behavior, cancellationToken); /// internal ValueTask RunAsync( diff --git a/Source/Core/DbQueryRunner.Output.cs b/Source/Core/DbQueryRunner.Output.cs index a5cf3098..afafd300 100644 --- a/Source/Core/DbQueryRunner.Output.cs +++ b/Source/Core/DbQueryRunner.Output.cs @@ -267,12 +267,8 @@ static async ValueTask ExecuteWithOutputAsync( cancellationToken) .ConfigureAwait(false); built = MakeWithOutput( - lease.Connection, - lease.Transaction, - definition, - call, - names, - output); + lease.Connection, lease.Transaction, + definition, call, names, output); } catch (Exception ex) when (ProcedureParameterNames.ForgetUnlessCanceled(names, ex)) { @@ -352,12 +348,8 @@ public static async ValueTask RunCapturedAsync( cancellationToken) .ConfigureAwait(false); built = MakeWithOutput( - lease.Connection, - lease.Transaction, - definition, - call, - names, - output); + lease.Connection, lease.Transaction, + definition, call, names, output); } catch (Exception ex) when (ProcedureParameterNames.ForgetUnlessCanceled(names, ex)) { diff --git a/Source/Core/ExpressiveCommandBase.Capture.cs b/Source/Core/ExpressiveCommandBase.Capture.cs index 4d9fb0f7..8e2b7e26 100644 --- a/Source/Core/ExpressiveCommandBase.Capture.cs +++ b/Source/Core/ExpressiveCommandBase.Capture.cs @@ -79,42 +79,28 @@ public abstract partial class ExpressiveCommandBase< /// /// Reads the command's output parameters into a - /// when the next terminal runs it. + /// when the next terminal runs it: a model by its members, or one value by + /// the name of the variable. /// /// /// - public TThis CaptureOutput(out DbCapture output) - { - CaptureSource source = Captures.Model(); - Attach(source); - output = new(source); - return (TThis)this; - } - - /// - /// Reads one output parameter, converted to , - /// when the next terminal runs the command. - /// - /// - /// /// - public TThis CaptureOutput(string name, out DbCapture value) + public TThis CaptureOutput( + out DbCapture output, + [CallerArgumentExpression(nameof(output))] string? name = null) { - CaptureSource source = Captures.Named(name); + CaptureSource source = Captures.Output(name); Attach(source); - value = new(source); + output = new(source); return (TThis)this; } /// /// Reads one output parameter of the given precision - /// and scale, converted to , when the next - /// terminal runs the command. + /// and scale when the next terminal runs the command. /// /// @@ -122,16 +108,13 @@ public TThis CaptureOutput(string name, out DbCapture value) /// path="docs/members[@name='out-name-param']/*" /> /// - public TThis CaptureOutput( - string name, + public TThis CaptureOutput( + out DbCapture value, byte precision, byte scale, - out DbCapture value) + [CallerArgumentExpression(nameof(value))] string? name = null) { - CaptureSource source = Captures.Shaped( - name, - precision, - scale); + CaptureSource source = Captures.Shaped(name, precision, scale); Attach(source); value = new(source); return (TThis)this; @@ -148,15 +131,12 @@ public TThis CaptureOutput( /// public TThis CaptureOutputDecimal( - string name, + out DbCapture value, byte precision, byte scale, - out DbCapture value) + [CallerArgumentExpression(nameof(value))] string? name = null) { - CaptureSource source = Captures.Decimal( - name, - precision, - scale); + CaptureSource source = Captures.Decimal(name, precision, scale); Attach(source); value = new(source); return (TThis)this; diff --git a/Source/Core/MappedQuery.Capture.cs b/Source/Core/MappedQuery.Capture.cs index 51fad7af..78eb63e5 100644 --- a/Source/Core/MappedQuery.Capture.cs +++ b/Source/Core/MappedQuery.Capture.cs @@ -157,44 +157,28 @@ public readonly partial record struct MappedQuery { /// /// Reads the command's output parameters into a - /// when the query's terminal runs. + /// when the query's terminal runs: a model by its members, or one value by + /// the name of the variable. /// /// /// - public MappedQuery CaptureOutput(out DbCapture output) - { - CaptureSource source = Captures.Model(); - MappedQuery captured = new(_core.WithCapture(source)); - output = new(source); - return captured; - } - - /// - /// Reads one output parameter, converted to , - /// when the query's terminal runs. - /// - /// - /// /// - public MappedQuery CaptureOutput( - string name, - out DbCapture value) + public MappedQuery CaptureOutput( + out DbCapture output, + [CallerArgumentExpression(nameof(output))] string? name = null) { - CaptureSource source = Captures.Named(name); + CaptureSource source = Captures.Output(name); MappedQuery captured = new(_core.WithCapture(source)); - value = new(source); + output = new(source); return captured; } /// /// Reads one output parameter of the given precision - /// and scale, converted to , when the query's - /// terminal runs. + /// and scale when the query's terminal runs. /// /// @@ -202,16 +186,13 @@ public MappedQuery CaptureOutput( /// path="docs/members[@name='out-name-param']/*" /> /// - public MappedQuery CaptureOutput( - string name, + public MappedQuery CaptureOutput( + out DbCapture value, byte precision, byte scale, - out DbCapture value) + [CallerArgumentExpression(nameof(value))] string? name = null) { - CaptureSource source = Captures.Shaped( - name, - precision, - scale); + CaptureSource source = Captures.Shaped(name, precision, scale); MappedQuery captured = new(_core.WithCapture(source)); value = new(source); return captured; @@ -228,15 +209,12 @@ public MappedQuery CaptureOutput( /// public MappedQuery CaptureOutputDecimal( - string name, + out DbCapture value, byte precision, byte scale, - out DbCapture value) + [CallerArgumentExpression(nameof(value))] string? name = null) { - CaptureSource source = Captures.Decimal( - name, - precision, - scale); + CaptureSource source = Captures.Decimal(name, precision, scale); MappedQuery captured = new(_core.WithCapture(source)); value = new(source); return captured; @@ -263,57 +241,40 @@ public MappedQuery CaptureReturn( public readonly partial record struct MappedQueryWithSkip { /// + /// cref="MappedQuery{T}.CaptureOutput{TOut}(out DbCapture{TOut}, string)"/> public MappedQueryWithSkip CaptureOutput( - out DbCapture output) + out DbCapture output, + [CallerArgumentExpression(nameof(output))] string? name = null) { - CaptureSource source = Captures.Model(); + CaptureSource source = Captures.Output(name); MappedQueryWithSkip captured = new(_core.WithCapture(source)); output = new(source); return captured; } /// - public MappedQueryWithSkip CaptureOutput( - string name, - out DbCapture value) - { - CaptureSource source = Captures.Named(name); - MappedQueryWithSkip captured = new(_core.WithCapture(source)); - value = new(source); - return captured; - } - - /// - public MappedQueryWithSkip CaptureOutput( - string name, + /// cref="MappedQuery{T}.CaptureOutput(out DbCapture{decimal}, byte, byte, string)"/> + public MappedQueryWithSkip CaptureOutput( + out DbCapture value, byte precision, byte scale, - out DbCapture value) + [CallerArgumentExpression(nameof(value))] string? name = null) { - CaptureSource source = Captures.Shaped( - name, - precision, - scale); + CaptureSource source = Captures.Shaped(name, precision, scale); MappedQueryWithSkip captured = new(_core.WithCapture(source)); value = new(source); return captured; } /// + /// cref="MappedQuery{T}.CaptureOutputDecimal(out DbCapture{decimal?}, byte, byte, string)"/> public MappedQueryWithSkip CaptureOutputDecimal( - string name, + out DbCapture value, byte precision, byte scale, - out DbCapture value) + [CallerArgumentExpression(nameof(value))] string? name = null) { - CaptureSource source = Captures.Decimal( - name, - precision, - scale); + CaptureSource source = Captures.Decimal(name, precision, scale); MappedQueryWithSkip captured = new(_core.WithCapture(source)); value = new(source); return captured; @@ -334,57 +295,40 @@ public MappedQueryWithSkip CaptureReturn( public readonly partial record struct MappedQueryWithTake { /// + /// cref="MappedQuery{T}.CaptureOutput{TOut}(out DbCapture{TOut}, string)"/> public MappedQueryWithTake CaptureOutput( - out DbCapture output) + out DbCapture output, + [CallerArgumentExpression(nameof(output))] string? name = null) { - CaptureSource source = Captures.Model(); + CaptureSource source = Captures.Output(name); MappedQueryWithTake captured = new(_core.WithCapture(source)); output = new(source); return captured; } /// - public MappedQueryWithTake CaptureOutput( - string name, - out DbCapture value) - { - CaptureSource source = Captures.Named(name); - MappedQueryWithTake captured = new(_core.WithCapture(source)); - value = new(source); - return captured; - } - - /// - public MappedQueryWithTake CaptureOutput( - string name, + /// cref="MappedQuery{T}.CaptureOutput(out DbCapture{decimal}, byte, byte, string)"/> + public MappedQueryWithTake CaptureOutput( + out DbCapture value, byte precision, byte scale, - out DbCapture value) + [CallerArgumentExpression(nameof(value))] string? name = null) { - CaptureSource source = Captures.Shaped( - name, - precision, - scale); + CaptureSource source = Captures.Shaped(name, precision, scale); MappedQueryWithTake captured = new(_core.WithCapture(source)); value = new(source); return captured; } /// + /// cref="MappedQuery{T}.CaptureOutputDecimal(out DbCapture{decimal?}, byte, byte, string)"/> public MappedQueryWithTake CaptureOutputDecimal( - string name, + out DbCapture value, byte precision, byte scale, - out DbCapture value) + [CallerArgumentExpression(nameof(value))] string? name = null) { - CaptureSource source = Captures.Decimal( - name, - precision, - scale); + CaptureSource source = Captures.Decimal(name, precision, scale); MappedQueryWithTake captured = new(_core.WithCapture(source)); value = new(source); return captured; @@ -401,3 +345,4 @@ public MappedQueryWithTake CaptureReturn( return captured; } } + diff --git a/Source/Core/Output.docs.xml b/Source/Core/Output.docs.xml index 3bdb2503..85bc050f 100644 --- a/Source/Core/Output.docs.xml +++ b/Source/Core/Output.docs.xml @@ -149,53 +149,67 @@ --> - The output model: a class or struct whose members name the output parameters, - as for ExecuteOutputAsync<TOut>(). + The output model (a class or struct whose members name the output parameters, as for ExecuteOutputAsync<TOut>()), + or the type of one output parameter's value, converted as Map<T>() converts a single column. The capture: await it after the terminal. + + + is optional. A single value reads the parameter named after the variable (out DbCapture<int> total + reads @total; the last identifier of out this.total or out state.total is total), or the name passed last + (CaptureOutput(out DbCapture<int> x, "total")). One rule reads both: the last identifier, with a leading @ or : dropped; + a field prefix (m_, s_, _) is also tried without it. + A model maps by its members and ignores the name: it never derives or refuses one, and a member that matches no parameter says so in its message. + Name the variable after the output parameter, or pass the name last; a variable named after an input parameter with a value is sent as + , and a variable named after an input parameter without a default is refused by SQL Server (error 8162 for a procedure, + error 137 for a text command, before any data): the output path is not gated by provider, and is tested on SQL Server only. + A compiler older than C# 10 does not supply the variable's name: pass it last. + + + + A single value has no name: a discard (_), an element access (arr[0]), or an empty name + (the compiler did not supply it, or it was passed). Declare a variable named after the parameter, or pass the name last. + - At the call: cannot be read from output parameters - (a single value, or a type with no member to set); + 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). - - The type the value converts to, as Map<T>() converts a single column. - The capture: await it after the terminal. - is . - is empty, white space or a bare @. - - At the call: is not a single value, or is a , - which needs its precision and scale (use the form that takes them); - or another capture reads the same parameter. - - - - , which throws on NULL, or a of it, which reads NULL as . + The capture: await it after the terminal; a NULL faults it (use CaptureOutputDecimal for a parameter that can be NULL). The number of digits its SQL type declares, from 1 to 38. The number of those digits after the decimal point, from 0 to . - The capture: await it after the terminal. - is . - is empty, white space or a bare @. + + + is optional, as for CaptureOutput(out DbCapture<int> total): the variable's name, or the name passed last. + This form takes only , so a wrong type with a shape is a compile error. + CaptureOutput<decimal>(out DbCapture<decimal> x, 19, 4) with an explicit type argument no longer compiles: + write CaptureOutput(out DbCapture<decimal> x, 19, 4), or CaptureOutputDecimal(out DbCapture<decimal?> x, 19, 4). + A NULL output faults the capture with a message that names the nullable form; when the parameter can be NULL, use the nullable form. + + + No name can be taken from the variable or the text passed last (a discard, an element access, ). is 0 or more than 38, or is more than . - - At the call: is not or a of it; - or another capture reads the same parameter. - + At the call: another capture reads the same parameter. + The capture: await it after the terminal; NULL is . The number of digits its SQL type declares, from 1 to 38. The number of those digits after the decimal point, from 0 to . - The capture: await it after the terminal; NULL is . - is . - is empty, white space or a bare @. + + + is optional, as for CaptureOutput(out DbCapture<int> total): the variable's name, or the name passed last. + Use this form when the parameter can be NULL. + + + No name can be taken from the variable or the text passed last (a discard, an element access, ). is 0 or more than 38, or is more than . diff --git a/Source/Core/OutputBinding.cs b/Source/Core/OutputBinding.cs index 506eeba7..41e438b5 100644 --- a/Source/Core/OutputBinding.cs +++ b/Source/Core/OutputBinding.cs @@ -127,6 +127,16 @@ public static void Resolve( continue; } + if (layout.Members[i].Form == OutputForm.Capture + && layout.Members[i].Named + && layout.Members[j].Named) + { + throw new InvalidOperationException( + $"{layout.Members[i].Display} and {layout.Members[j].Display} both resolve to the output parameter '{first}' of {where}, so two captures would read one value. " + + "Name one of them exactly as the parameter is declared, passing the name last (CaptureOutput(out DbCapture x, \"name\")): a name that matches exactly wins over one that matches only ignoring case or underscores. " + + "Or capture the parameter once."); + } + throw new InvalidOperationException( $"{layout.Members[i].Display} and {layout.Members[j].Display} both resolve to the output parameter '{first}' of {where}, so one value would be read under two meanings. " + (layout.Members[i].Named || layout.Members[j].Named @@ -146,9 +156,7 @@ public static void Resolve( if (member.Exact) return real.Find(member.Name)?.Real; if (!member.Named) return real.Match(member.Name, commandText, member.Display); - string fix = member.Form == OutputForm.Execute - ? "Pass the exact parameter name, naming one of those two." - : "Pass the exact name of the parameter."; + string fix = OutputArguments.ExactNameFix(member.Form); // One candidate, the name as given: remembered by that name. if (member.Candidates.IsDefault) @@ -185,9 +193,10 @@ static InvalidOperationException NoOutputMatch( ? member.Form switch { OutputForm.Capture - => "Pass one of those names to CaptureOutput(name, " - + "precision, scale, out …) or CaptureOutputDecimal(name, " - + "precision, scale, out …)", + => "Pass one of those names last to " + + "CaptureOutput(out DbCapture x, precision, scale, name) " + + "or CaptureOutputDecimal(out DbCapture x, precision, " + + "scale, name)", OutputForm.Definition => "Pass one of those names to Output(name, " + "precision, scale) or OutputDecimal(name, precision, " @@ -210,6 +219,17 @@ static InvalidOperationException NoOutputMatch( + "Change the [Column] name to one it declares, or add the parameter."); } + if (member.ReceivedName is { } received) + { + // A model capture maps by its members: the name it was given (typed, + // or its variable's) is not used. + return new( + $"{member.Display} has no matching parameter on {where} (tried {string.Join(", ", ParameterNames.Candidates(member.Name))}; it declares: {declared}). " + + $"The name '{received}' was not used: a model is read by its members, not by a name. " + + $"To read one value into that name, use a single-value type (CaptureOutput(out DbCapture x, \"{received}\")); " + + "otherwise give the model members named after the parameters, or [Column(\"name\")]."); + } + return new( $"{member.Display} has no matching parameter on {where} (tried {string.Join(", ", ParameterNames.Candidates(member.Name))}; it declares: {declared}). " + $"Add a parameter named {member.Name} to {where}, or name the member's parameter with [Column(\"name\")]."); diff --git a/Source/Core/OutputLayout.cs b/Source/Core/OutputLayout.cs index 27e39091..08958425 100644 --- a/Source/Core/OutputLayout.cs +++ b/Source/Core/OutputLayout.cs @@ -62,8 +62,15 @@ public OutputMember(string label, string display, bool named = false) /// The member. /// The name for the messages. /// The members the call comes from. - public OutputMember(OutputMember member, string display, OutputForm form) + /// The name a model capture was given, which it + /// does not use, for the message of a member that matches nothing. + public OutputMember( + OutputMember member, + string display, + OutputForm form, + string? receivedName = null) { + ReceivedName = receivedName; Name = member.Name; Exact = member.Exact; Label = member.Label; @@ -89,6 +96,11 @@ public OutputMember(OutputMember member, string display, OutputForm form) /// The member for the messages: Model.Member, or The output parameter 'name' in the named form. public readonly string Display; + /// The name a model capture received (typed or from its variable), + /// or : a model maps by its members and ignores + /// it. + public readonly string? ReceivedName; + /// The names a non-exact named output is matched by through the /// tiers, most specific first; the default value means . public readonly ImmutableArray Candidates; @@ -533,16 +545,19 @@ static class OutputValue /// The parameter's name. /// The members the call comes from: the display of the /// value and the fixes of the messages. + /// The names a capture is matched by, most specific + /// first, or the default value for alone. /// The layout. /// cannot be read as one output parameter. public static OutputLayout Get( string name, - OutputForm form = OutputForm.Execute) + OutputForm form = OutputForm.Execute, + ImmutableArray candidates = default) { string display = form switch { OutputForm.Capture - => $"CaptureOutput<{Shape.TypeName(typeof(T))}>(\"{name}\")", + => $"CaptureOutput(out DbCapture<{Shape.TypeName(typeof(T))}> {name})", OutputForm.Definition => OutputArguments.NamedCall( form, @@ -560,7 +575,8 @@ public static OutputLayout Get( wire, display, named: true, - form)); + form, + candidates)); } /// @@ -604,13 +620,16 @@ public static void ThrowUnlessDecimal( /// for the one of ExecuteOutputAsync. /// The members the call comes from, for the fixes the /// messages give. + /// The names a capture is matched by, most specific + /// first, or the default value for alone. /// The layout; is checked by the caller, which has called . public static OutputLayout Shaped( string name, byte precision, byte scale, string? display = null, - OutputForm form = OutputForm.Execute) + OutputForm form = OutputForm.Execute, + ImmutableArray candidates = default) { Debug.Assert(Reason == OutputValueRefusal.DecimalNeedsShape); display ??= $"The output parameter '{name}'"; @@ -622,7 +641,8 @@ public static OutputLayout Shaped( new OutputWire(DbType.Decimal, 0, precision, scale), display, named: true, - form)); + form, + candidates)); } static string Message(string name, string display, OutputForm form) @@ -824,6 +844,22 @@ public static string Message(string shown) /// static class OutputArguments { + /// + /// Gets what to do about a name that fits two parameters equally well. + /// + /// The members the call comes from. + /// The fix, ending the message. + public static string ExactNameFix(OutputForm form) + => form switch + { + OutputForm.Capture + => "Pass the exact name of the parameter last: " + + "CaptureOutput(out DbCapture x, \"exact_name\").", + OutputForm.Definition + => "Pass the exact name of the parameter to Output(name).", + _ => "Pass the exact parameter name, naming one of those two.", + }; + /// /// Gets the call that reads a model, as a message tells the caller to /// write it. @@ -854,7 +890,8 @@ public static string NamedCall( string argument) => form switch { - OutputForm.Capture => $"CaptureOutput<{type}>({argument}, out …)", + OutputForm.Capture + => $"CaptureOutput(out DbCapture<{type}> x, {argument})", OutputForm.Definition => $"Output<{type}>({argument})", _ => $"ExecuteOutputAsync<{type}>({argument})", }; @@ -870,7 +907,7 @@ public static string ShapedCall(OutputForm form, string argument) => form switch { OutputForm.Capture - => $"CaptureOutput({argument}, 19, 4, out …)", + => $"CaptureOutput(out DbCapture x, 19, 4, {argument})", OutputForm.Definition => $"Output({argument}, 19, 4)", _ => $"ExecuteOutputAsync({argument}, 19, 4)", }; @@ -886,7 +923,7 @@ public static string DecimalCall(OutputForm form, string argument) => form switch { OutputForm.Capture - => $"CaptureOutputDecimal({argument}, 19, 4, out …)", + => $"CaptureOutputDecimal(out DbCapture x, 19, 4, {argument})", OutputForm.Definition => $"OutputDecimal({argument}, 19, 4)", _ => $"ExecuteOutputDecimalAsync({argument}, 19, 4)", }; @@ -978,10 +1015,8 @@ public static ValueMappingException DecimalNull( + form switch { OutputForm.Capture - => $"Read it as decimal? (CaptureOutput(\"{name}\", " - + "precision, scale, out …)) " - + $"or with CaptureOutputDecimal(\"{name}\", precision, scale, " - + "out …), which give null for NULL.", + => "Read it with CaptureOutputDecimal(out DbCapture " + + $"{name}, precision, scale), which gives null for NULL.", OutputForm.Definition => $"Read it as decimal? (Output(\"{name}\", " + "precision, scale)) " diff --git a/Source/Core/ParameterNames.cs b/Source/Core/ParameterNames.cs index f4299332..0d6ba248 100644 --- a/Source/Core/ParameterNames.cs +++ b/Source/Core/ParameterNames.cs @@ -160,7 +160,7 @@ internal static ImmutableArray Candidates(string expression) /// The index where the member name starts. /// The length of the member name. /// The length of the prefix, or 0 when there is none. - static int FieldPrefixLength(string s, int start, int length) + public static int FieldPrefixLength(string s, int start, int length) { int prefix = s[start] == '_' ? 1 : length > 1 && (s[start] == 'm' || s[start] == 's') && s[start + 1] == '_' ? 2 : 0; return prefix > 0 && prefix < length && char.IsLetterOrDigit(s[start + prefix]) ? prefix : 0; diff --git a/Source/Core/PublicAPI.Unshipped.txt b/Source/Core/PublicAPI.Unshipped.txt index ccd72e6d..11d05c30 100644 --- a/Source/Core/PublicAPI.Unshipped.txt +++ b/Source/Core/PublicAPI.Unshipped.txt @@ -96,25 +96,9 @@ Open.Database.Extensions.DbCapture.ConfiguredAwaiter.GetResult() -> T Open.Database.Extensions.DbCapture.ConfiguredAwaiter.IsCompleted.get -> bool Open.Database.Extensions.DbCapture.ConfiguredAwaiter.OnCompleted(System.Action! continuation) -> void Open.Database.Extensions.DbCapture.ConfiguredAwaiter.UnsafeOnCompleted(System.Action! continuation) -> void -Open.Database.Extensions.ExpressiveCommandBase.CaptureOutput(out Open.Database.Extensions.DbCapture output) -> TThis! -Open.Database.Extensions.ExpressiveCommandBase.CaptureOutput(string! name, out Open.Database.Extensions.DbCapture value) -> TThis! -Open.Database.Extensions.ExpressiveCommandBase.CaptureOutput(string! name, byte precision, byte scale, out Open.Database.Extensions.DbCapture value) -> TThis! -Open.Database.Extensions.ExpressiveCommandBase.CaptureOutputDecimal(string! name, byte precision, byte scale, out Open.Database.Extensions.DbCapture value) -> TThis! Open.Database.Extensions.ExpressiveCommandBase.CaptureReturn(out Open.Database.Extensions.DbCapture returnCode) -> TThis! -Open.Database.Extensions.MappedQuery.CaptureOutput(out Open.Database.Extensions.DbCapture output) -> Open.Database.Extensions.MappedQuery -Open.Database.Extensions.MappedQuery.CaptureOutput(string! name, out Open.Database.Extensions.DbCapture value) -> Open.Database.Extensions.MappedQuery -Open.Database.Extensions.MappedQuery.CaptureOutput(string! name, byte precision, byte scale, out Open.Database.Extensions.DbCapture value) -> Open.Database.Extensions.MappedQuery -Open.Database.Extensions.MappedQuery.CaptureOutputDecimal(string! name, byte precision, byte scale, out Open.Database.Extensions.DbCapture value) -> Open.Database.Extensions.MappedQuery Open.Database.Extensions.MappedQuery.CaptureReturn(out Open.Database.Extensions.DbCapture returnCode) -> Open.Database.Extensions.MappedQuery -Open.Database.Extensions.MappedQueryWithSkip.CaptureOutput(out Open.Database.Extensions.DbCapture output) -> Open.Database.Extensions.MappedQueryWithSkip -Open.Database.Extensions.MappedQueryWithSkip.CaptureOutput(string! name, out Open.Database.Extensions.DbCapture value) -> Open.Database.Extensions.MappedQueryWithSkip -Open.Database.Extensions.MappedQueryWithSkip.CaptureOutput(string! name, byte precision, byte scale, out Open.Database.Extensions.DbCapture value) -> Open.Database.Extensions.MappedQueryWithSkip -Open.Database.Extensions.MappedQueryWithSkip.CaptureOutputDecimal(string! name, byte precision, byte scale, out Open.Database.Extensions.DbCapture value) -> Open.Database.Extensions.MappedQueryWithSkip Open.Database.Extensions.MappedQueryWithSkip.CaptureReturn(out Open.Database.Extensions.DbCapture returnCode) -> Open.Database.Extensions.MappedQueryWithSkip -Open.Database.Extensions.MappedQueryWithTake.CaptureOutput(out Open.Database.Extensions.DbCapture output) -> Open.Database.Extensions.MappedQueryWithTake -Open.Database.Extensions.MappedQueryWithTake.CaptureOutput(string! name, out Open.Database.Extensions.DbCapture value) -> Open.Database.Extensions.MappedQueryWithTake -Open.Database.Extensions.MappedQueryWithTake.CaptureOutput(string! name, byte precision, byte scale, out Open.Database.Extensions.DbCapture value) -> Open.Database.Extensions.MappedQueryWithTake -Open.Database.Extensions.MappedQueryWithTake.CaptureOutputDecimal(string! name, byte precision, byte scale, out Open.Database.Extensions.DbCapture value) -> Open.Database.Extensions.MappedQueryWithTake Open.Database.Extensions.MappedQueryWithTake.CaptureReturn(out Open.Database.Extensions.DbCapture returnCode) -> Open.Database.Extensions.MappedQueryWithTake Open.Database.Extensions.QueryOptions Open.Database.Extensions.QueryOptions.AsyncReads = 1 -> Open.Database.Extensions.QueryOptions @@ -164,3 +148,15 @@ static Open.Database.Extensions.BoundCallExtensions.CaptureOutput(this static Open.Database.Extensions.BoundCallExtensions.CaptureOutput(this Open.Database.Extensions.BoundCall> call, out Open.Database.Extensions.DbCapture value, byte precision, byte scale, string? name = null) -> Open.Database.Extensions.BoundCall> static Open.Database.Extensions.BoundCallExtensions.CaptureOutputDecimal(this Open.Database.Extensions.BoundCall> call, out Open.Database.Extensions.DbCapture value, byte precision, byte scale, string? name = null) -> Open.Database.Extensions.BoundCall> static Open.Database.Extensions.BoundCallExtensions.CaptureReturn(this Open.Database.Extensions.BoundCall> call, out Open.Database.Extensions.DbCapture returnCode) -> Open.Database.Extensions.BoundCall> +Open.Database.Extensions.ExpressiveCommandBase.CaptureOutput(out Open.Database.Extensions.DbCapture output, string? name = null) -> TThis! +Open.Database.Extensions.ExpressiveCommandBase.CaptureOutput(out Open.Database.Extensions.DbCapture value, byte precision, byte scale, string? name = null) -> TThis! +Open.Database.Extensions.ExpressiveCommandBase.CaptureOutputDecimal(out Open.Database.Extensions.DbCapture value, byte precision, byte scale, string? name = null) -> TThis! +Open.Database.Extensions.MappedQuery.CaptureOutput(out Open.Database.Extensions.DbCapture output, string? name = null) -> Open.Database.Extensions.MappedQuery +Open.Database.Extensions.MappedQuery.CaptureOutput(out Open.Database.Extensions.DbCapture value, byte precision, byte scale, string? name = null) -> Open.Database.Extensions.MappedQuery +Open.Database.Extensions.MappedQuery.CaptureOutputDecimal(out Open.Database.Extensions.DbCapture value, byte precision, byte scale, string? name = null) -> Open.Database.Extensions.MappedQuery +Open.Database.Extensions.MappedQueryWithSkip.CaptureOutput(out Open.Database.Extensions.DbCapture output, string? name = null) -> Open.Database.Extensions.MappedQueryWithSkip +Open.Database.Extensions.MappedQueryWithSkip.CaptureOutput(out Open.Database.Extensions.DbCapture value, byte precision, byte scale, string? name = null) -> Open.Database.Extensions.MappedQueryWithSkip +Open.Database.Extensions.MappedQueryWithSkip.CaptureOutputDecimal(out Open.Database.Extensions.DbCapture value, byte precision, byte scale, string? name = null) -> Open.Database.Extensions.MappedQueryWithSkip +Open.Database.Extensions.MappedQueryWithTake.CaptureOutput(out Open.Database.Extensions.DbCapture output, string? name = null) -> Open.Database.Extensions.MappedQueryWithTake +Open.Database.Extensions.MappedQueryWithTake.CaptureOutput(out Open.Database.Extensions.DbCapture value, byte precision, byte scale, string? name = null) -> Open.Database.Extensions.MappedQueryWithTake +Open.Database.Extensions.MappedQueryWithTake.CaptureOutputDecimal(out Open.Database.Extensions.DbCapture value, byte precision, byte scale, string? name = null) -> Open.Database.Extensions.MappedQueryWithTake diff --git a/Tests/Open.Database.Extensions.Core.Tests/BoundCallCaptureCompileTests.cs b/Tests/Open.Database.Extensions.Core.Tests/BoundCallCaptureCompileTests.cs new file mode 100644 index 00000000..2d13550a --- /dev/null +++ b/Tests/Open.Database.Extensions.Core.Tests/BoundCallCaptureCompileTests.cs @@ -0,0 +1,147 @@ +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; + +#nullable enable + +namespace Open.Database.Extensions.Tests; + +// The captures on a bound call are extension methods of the kinds that run +// them (a write and a scalar), so a capture on a call made from Output does +// not compile, and on a scalar the type of the value comes only from a typed +// out declaration. Compiled in memory, as DbQueryBindingTests does. +[ExcludeFromCodeCoverage] +public static class BoundCallCaptureCompileTests +{ + static readonly Dictionary Suppressed = new() + { + ["CS1701"] = ReportDiagnostic.Suppress, + ["CS1702"] = ReportDiagnostic.Suppress, + }; + + static readonly Lazy References = new(static () => + { + var paths = new HashSet(StringComparer.OrdinalIgnoreCase); + if (AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES") is string tpa) + { + foreach (string path in tpa.Split(Path.PathSeparator)) + { + string file = Path.GetFileName(path); + if (file.StartsWith("Open.Database.Extensions.", StringComparison.OrdinalIgnoreCase) + && !file.Equals("Open.Database.Extensions.Core.dll", StringComparison.OrdinalIgnoreCase)) + { + continue; + } + + paths.Add(path); + } + } + + paths.Add(typeof(DbQuery).Assembly.Location); + return [.. paths.Select(static p => (MetadataReference)MetadataReference.CreateFromFile(p))]; + }); + + const string Header = """ + #nullable enable + using System; + using System.Data.Common; + using System.Threading.Tasks; + using Open.Database.Extensions; + readonly record struct Ids(int Id); + sealed record Totals(int Total); + static class Probe + { + static readonly DbNonQuery W = DbNonQuery.Procedure("dbo.P"); + static readonly ScalarDbQuery S = DbQuery.Procedure("dbo.P").Scalar(); + static readonly OutputDbNonQuery O = W.Output("total"); + static readonly OutputDbNonQuery Mo = W.Output(); + static readonly OutputDbNonQuery T = W.Params().Output("total"); + """; + + static Diagnostic[] Errors(string body) + { + SyntaxTree tree = CSharpSyntaxTree.ParseText( + Header + "\n" + body + "\n}\n", + new CSharpParseOptions(LanguageVersion.Preview)); + var compilation = CSharpCompilation.Create( + "CaptureProbe", + [tree], + References.Value, + new CSharpCompilationOptions( + OutputKind.DynamicallyLinkedLibrary, + specificDiagnosticOptions: Suppressed, + nullableContextOptions: NullableContextOptions.Enable)); + return [.. compilation + .GetDiagnostics(TestContext.Current.CancellationToken) + .Where(static d => d.Severity >= DiagnosticSeverity.Warning)]; + } + + static string Show(IEnumerable diagnostics) + => string.Join(" ; ", diagnostics.Select(static d => d.ToString())); + + [Theory] + [InlineData("W.Using(c).CaptureOutput(out DbCapture total, \"total\").ExecuteNonQueryAsync()")] + [InlineData("W.Using(c).CaptureOutput(out DbCapture totals).ExecuteNonQueryAsync()")] + [InlineData("W.Using(c).CaptureOutput(out var total, 18, 2, \"total\").ExecuteNonQueryAsync()")] + [InlineData("W.Using(c).CaptureOutput(out var total, \"total\").ExecuteNonQueryAsync()")] + [InlineData("W.Using(c).CaptureOutputDecimal(out var total, 18, 2, \"total\").ExecuteNonQueryAsync()")] + [InlineData("W.Using(c).CaptureReturn(out DbCapture code).ExecuteNonQueryAsync()")] + [InlineData("W.Using(c).CaptureReturn(out var code).ExecuteNonQueryAsync()")] + [InlineData("S.Using(c).CaptureOutput(out DbCapture total, \"total\").ExecuteScalarAsync()")] + [InlineData("S.Using(c).CaptureOutput(out DbCapture totals).ExecuteScalarAsync()")] + [InlineData("S.Using(c).CaptureOutput(out var total, 18, 2, \"total\").ExecuteScalarAsync()")] + [InlineData("S.Using(c).CaptureOutputDecimal(out var total, 18, 2, \"total\").ExecuteScalarAsync()")] + [InlineData("S.Using(c).CaptureReturn(out DbCapture code).ExecuteScalarAsync()")] + [InlineData("S.AddParam(\"a\", 1).Using(c).CaptureOutput(out DbCapture total, \"total\").AddParam(\"b\", 2).ExecuteScalarAsync()")] + public static void TheTypedSpellings_CompileOnAWriteAndOnAScalar(string expression) + { + Diagnostic[] errors = Errors( + "static void M(DbConnection c) { var call = " + expression + "; }"); + + Assert.True(errors.Length == 0, Show(errors)); + } + + [Fact] + public static void OnAScalar_ADecimalShapeWithTheScalarsTypeArgument_BindsTheDecimalForm() + { + // is the scalar's T, so the capture is a DbCapture. + Diagnostic[] errors = Errors(""" + static void M(DbConnection c) + { + var call = S.Using(c).CaptureOutput(out var t, 18, 2, "t"); + DbCapture check = t; + } + """); + + Assert.True(errors.Length == 0, Show(errors)); + } + + [Theory] + [InlineData("S.Using(c).CaptureOutput(out var t, \"t\")")] + [InlineData("S.Using(c).CaptureReturn(out var r)")] + [InlineData("O.Using(c).CaptureOutput(out DbCapture t, \"t\")")] + [InlineData("O.Using(c).CaptureReturn(out DbCapture r)")] + [InlineData("Mo.Using(c).CaptureOutput(out DbCapture t)")] + [InlineData("O.Using(c).CaptureOutput(out var t, 18, 2, \"t\")")] + [InlineData("O.Using(c).CaptureOutputDecimal(out var t, 18, 2, \"t\")")] + [InlineData("O.AddParam(\"a\", 1).Using(c).CaptureOutput(out DbCapture t, \"t\")")] + [InlineData("O.Using(c).AddParam(\"a\", 1).CaptureOutput(out DbCapture t, \"t\")")] + [InlineData("T.Using(c).AddParams(new Ids(1)).CaptureOutput(out DbCapture t, \"t\")")] + [InlineData("T.AddParams(new Ids(1)).Using(c).CaptureReturn(out DbCapture r)")] + public static void ACaptureOnACallMadeFromOutput_OrOnAScalarWithTheTypeArgument_DoesNotCompile( + string expression) + { + Diagnostic[] errors = Errors( + "static void M(DbConnection c) { var call = " + expression + "; }"); + + Assert.NotEmpty(errors); + Assert.All( + errors, + static d => Assert.True( + d.Severity == DiagnosticSeverity.Error, + d.ToString())); + // Seen: the receiver is not one the extension takes (CS1929). + Assert.True( + errors.All(static d => d.Id == "CS1929"), + Show(errors)); + } +} diff --git a/Tests/Open.Database.Extensions.Core.Tests/CaptureLibraryCommandTests.cs b/Tests/Open.Database.Extensions.Core.Tests/CaptureLibraryCommandTests.cs index df73a8e3..55dfd84e 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/CaptureLibraryCommandTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/CaptureLibraryCommandTests.cs @@ -20,14 +20,14 @@ public static void TheSqlCommands_NeedNoLookup_ForACapture() using var legacy = new System.Data.SqlClient.SqlConnection(); _ = new ExpressiveSqlCommand(legacy, CommandType.StoredProcedure, "p") .Map() - .CaptureOutput("total", out _); + .CaptureOutput(out DbCapture _, "total"); using var connection = new Microsoft.Data.SqlClient.SqlConnection(); _ = new mssql::Open.Database.Extensions.ExpressiveSqlCommand( connection, CommandType.StoredProcedure, "p") .Map() - .CaptureOutput("total", out _); + .CaptureOutput(out DbCapture _, "total"); Assert.Equal( 0, diff --git a/Tests/Open.Database.Extensions.Core.Tests/CaptureLocalDbTests.cs b/Tests/Open.Database.Extensions.Core.Tests/CaptureLocalDbTests.cs index da5fb494..bc524dc3 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/CaptureLocalDbTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/CaptureLocalDbTests.cs @@ -52,7 +52,7 @@ public static async Task TheRows_AnOutput_AndTheReturnCode() string name = "dbo." + procedure.Name; List rows = await connection.StoredProcedure(name) - .CaptureOutput("total", out DbCapture total) + .CaptureOutput(out DbCapture total, "total") .CaptureReturn(out DbCapture code) .Map() .ToListAsync(Token); @@ -78,7 +78,7 @@ public static async Task ASingleRowRead_StillDelivers() Row? row = await connection.StoredProcedure(name) .Map() .SingleResult() - .CaptureOutput("total", out DbCapture total) + .CaptureOutput(out DbCapture total, "total") .FirstOrDefaultAsync(Token); Assert.Equal(new Row(1), row); @@ -103,7 +103,7 @@ public static async Task AnEarlyStop_StillDelivers(string kind) string name = "dbo." + procedure.Name; MappedQuery query = connection.StoredProcedure(name) .Map() - .CaptureOutput("total", out DbCapture total); + .CaptureOutput(out DbCapture total, "total"); var forever = Timeout.InfiniteTimeSpan; switch (kind) @@ -149,7 +149,7 @@ public static async Task ABreak_AfterOneRow_StillFillsIt_BecauseTheRestIsRead() MappedQuery query = connection .StoredProcedure("dbo." + procedure.Name) .Map() - .CaptureOutput("total", out DbCapture total); + .CaptureOutput(out DbCapture total, "total"); await foreach (Row row in query.ToPooledStream(Token)) { @@ -173,7 +173,7 @@ public static async Task ALaterError_FaultsIt_WithTheProvidersError() MappedQuery query = connection.StoredProcedure(name) .Map() - .CaptureOutput("total", out DbCapture total); + .CaptureOutput(out DbCapture total, "total"); SqlException ex = await Assert.ThrowsAsync( async () => await query.ToListAsync(Token)); @@ -198,7 +198,7 @@ public static async Task ACancelMidRead_CancelsIt(int bufferSize) string name = "dbo." + procedure.Name; IAsyncEnumerable rows = connection.StoredProcedure(name) .Map() - .CaptureOutput("total", out DbCapture total) + .CaptureOutput(out DbCapture total, "total") .StreamBuffered(Timeout.InfiniteTimeSpan, bufferSize, Token); using var stop = CancellationTokenSource.CreateLinkedTokenSource(Token); @@ -226,14 +226,14 @@ public static async Task AModel_WithADecimal_AndTheNamedDecimal() Assert.Single(await connection.StoredProcedure(name) .Map() - .CaptureOutput(out DbCapture totals) + .CaptureOutput(out DbCapture totals) .ToListAsync(Token)); Assert.Equal(new Totals(12.34m, 2), await totals); Assert.Single(await connection.StoredProcedure(name) .Map() - .CaptureOutputDecimal("total", 10, 2, out DbCapture total) - .CaptureOutput("count", out DbCapture count) + .CaptureOutputDecimal(out DbCapture total, 10, 2, "total") + .CaptureOutput(out DbCapture count, "count") .ToListAsync(Token)); Assert.Equal(12.34m, await total); Assert.Equal(2, await count); @@ -249,7 +249,7 @@ public static async Task ANamedCapture_FindsItsParameter_ThroughTheTiers() await using SqlConnection connection = await OpenAsync(); List rows = await connection.StoredProcedure("dbo." + procedure.Name) - .CaptureOutput("totalCount", out DbCapture total) + .CaptureOutput(out DbCapture total, "totalCount") .Map() .ToListAsync(Token); @@ -268,8 +268,8 @@ public static async Task TwoNamedCaptures_OnOneParameter_FailTheRun() // The call compares the names as written, so only the run finds the collision. var query = connection.StoredProcedure("dbo." + procedure.Name) - .CaptureOutput("total_count", out DbCapture first) - .CaptureOutput("totalCount", out DbCapture second) + .CaptureOutput(out DbCapture first, "total_count") + .CaptureOutput(out DbCapture second, "totalCount") .Map(); var ex = await Assert.ThrowsAsync(async () => await query.ToListAsync(Token)); @@ -292,7 +292,7 @@ public static async Task ANamedCapture_FindsAPrefixedParameter() string name = "dbo." + procedure.Name; List rows = await connection.StoredProcedure(name) - .CaptureOutput("total", out DbCapture total) + .CaptureOutput(out DbCapture total, "total") .Map() .ToListAsync(Token); @@ -316,7 +316,7 @@ public static async Task ATextCommand_FillsItThroughItsMarker() string sql = $"exec dbo.[{procedure.Name}] @total output"; List rows = await connection.Command(sql) - .CaptureOutput("total", out DbCapture total) + .CaptureOutput(out DbCapture total, "total") .Map() .ToListAsync(Token); diff --git a/Tests/Open.Database.Extensions.Core.Tests/CaptureNameLocalDbTests.cs b/Tests/Open.Database.Extensions.Core.Tests/CaptureNameLocalDbTests.cs new file mode 100644 index 00000000..80fe0672 --- /dev/null +++ b/Tests/Open.Database.Extensions.Core.Tests/CaptureNameLocalDbTests.cs @@ -0,0 +1,260 @@ +using Microsoft.Data.SqlClient; + +#nullable enable + +namespace Open.Database.Extensions.Tests; + +// The name of a capture against SQL Server: the tiers of AddParam's names, +// what happens when the variable is named after an input parameter (SQL +// Server's own refusal, by number: it is localised), and the source named in +// the messages. Skipped without LocalDB (see LocalDbFixture). +[ExcludeFromCodeCoverage] +[Collection("LocalDB DDL")] +public static class CaptureNameLocalDbTests +{ + static CancellationToken Token => TestContext.Current.CancellationToken; + + public sealed record IdOnly(int Id); + + public sealed record PostId(int Value); + + public sealed record Row(int Id); + + static LocalDbFixture.Scratch Procedure(string parameters, string body) + => LocalDbFixture.CreateProcedureWithBody( + parameters, + "set nocount on; " + body, + "ode_nm"); + + static async Task OpenAsync() + { + SqlConnection connection = LocalDbFixture.Create(); + await connection.OpenAsync(Token); + return connection; + } + + // ---- the tiers ---- + + [Fact] + public static async Task AVariableNamedInCamelCase_FindsTheSnakeCaseParameter() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = Procedure( + "@total_count int output", + "set @total_count = 12;"); + await using SqlConnection connection = await OpenAsync(); + + await connection.StoredProcedure("dbo." + procedure.Name) + .CaptureOutput(out DbCapture totalCount) + .ExecuteNonQueryAsync(Token); + + Assert.Equal(12, await totalCount); + } + + [Fact] + public static async Task AnExactName_WinsOverATierMatch() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = Procedure( + "@total_count int = null output, @totalcount int = null output", + "set @total_count = 1; set @totalcount = 2;"); + await using SqlConnection connection = await OpenAsync(); + + await connection.StoredProcedure("dbo." + procedure.Name) + .CaptureOutput(out DbCapture total_count) + .ExecuteNonQueryAsync(Token); + + Assert.Equal(1, await total_count); + } + + [Fact] + public static async Task AFieldPrefix_IsTriedAfterTheNameAsWritten() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = Procedure( + "@total int output", + "set @total = 31;"); + await using SqlConnection connection = await OpenAsync(); +#pragma warning disable IDE0018, IDE0059 // An existing local is the case under test. + DbCapture m_total; +#pragma warning restore IDE0018, IDE0059 + + await connection.StoredProcedure("dbo." + procedure.Name) + .CaptureOutput(out m_total) + .ExecuteNonQueryAsync(Token); + + Assert.Equal(31, await m_total); + } + + [Fact] + public static async Task TwoCapturesThatResolveToOneParameter_FailTheRunWithACaptureFix() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = Procedure( + "@total_count int output", + "set @total_count = 12;"); + await using SqlConnection connection = await OpenAsync(); + + DbCapture total_count = default; + DbCapture totalCount = default; + var ex = await Assert.ThrowsAsync( + async () => await connection.StoredProcedure("dbo." + procedure.Name) + .CaptureOutput(out total_count) + .CaptureOutput(out totalCount) + .ExecuteNonQueryAsync(Token)); + + Assert.Contains("both resolve to the output parameter", ex.Message); + Assert.Contains("two captures would read one value", ex.Message); + Assert.Contains("CaptureOutput(out DbCapture x, \"name\")", ex.Message); + Assert.DoesNotContain("[Column", ex.Message); + } + + [Fact] + public static async Task AModelCapturedWithAName_SaysTheNameWasNotUsed_AndGivesBothFixes() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = Procedure( + "@post_id int output", + "set @post_id = 4;"); + await using SqlConnection connection = await OpenAsync(); + + var ex = await Assert.ThrowsAsync( + async () => await connection.StoredProcedure("dbo." + procedure.Name) + .CaptureOutput(out DbCapture id, "post_id") + .ExecuteNonQueryAsync(Token)); + + Assert.Contains("The name 'post_id' was not used", ex.Message); + Assert.Contains("a model is read by its members", ex.Message); + Assert.Contains("CaptureOutput(out DbCapture x, \"post_id\")", ex.Message); + Assert.Contains("[Column(\"name\")]", ex.Message); + } + + // ---- a variable named after an input parameter ---- + + [Fact] + public static async Task AModelMember_NamedAfterAnInput_BecomesInputOutput_AndSqlServerRefuses() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = Procedure( + "@id int, @p_id int output", + "set @p_id = @id + 1;"); + await using SqlConnection connection = await OpenAsync(); + int id = 5; + + var ex = await Assert.ThrowsAsync( + async () => await connection.StoredProcedure("dbo." + procedure.Name) + .AddParam(id) + .ExecuteOutputAsync(Token)); + + Assert.Equal(8162, ex.Number); + } + + [Fact] + public static async Task ACapture_NamedAfterAnInput_IsSentAsOutput_AndSqlServerRefuses() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = Procedure( + "@id int, @p_id int output", + "set @p_id = @id + 1;"); + await using SqlConnection connection = await OpenAsync(); + DbCapture capture; + + var ex = await Assert.ThrowsAsync( + async () => await connection.StoredProcedure("dbo." + procedure.Name) + .CaptureOutput(out DbCapture id) + .ExecuteNonQueryAsync(Token)); + + Assert.Equal(8162, ex.Number); + capture = default; + Assert.Equal(default, capture); + } + + [Fact] + public static async Task OnATextCommand_AModelMemberAndACapture_TakeTheEarlierTier_AndSqlServerFails137() + { + LocalDbFixture.SkipUnlessAvailable(); + await using SqlConnection connection = await OpenAsync(); + + var member = await Assert.ThrowsAsync( + async () => await connection + .Command("select @p_id = @id + 1") + .AddParam("id", 5) + .ExecuteOutputAsync(Token)); + var capture = await Assert.ThrowsAsync( + async () => await connection + .Command("select @p_id = @id + 1") + .AddParam("id", 5) + .CaptureOutput(out DbCapture id) + .ExecuteNonQueryAsync(Token)); + var without = await Assert.ThrowsAsync( + async () => await connection + .Command("select @p_id = @id + 1") + .ExecuteOutputAsync(Token)); + + Assert.Equal(137, member.Number); + Assert.Equal(137, capture.Number); + Assert.Equal(137, without.Number); + } + + [Fact] + public static async Task TheControls_NamedAndPlain_GiveTheirValues() + { + LocalDbFixture.SkipUnlessAvailable(); + await using SqlConnection connection = await OpenAsync(); + + int named = await connection + .Command("select @p_id = @id + 1") + .AddParam("id", 5) + .ExecuteOutputAsync("p_id", Token); + IdOnly model = await connection + .Command("select @p_id = 7") + .ExecuteOutputAsync(Token); + + Assert.Equal(6, named); + Assert.Equal(7, model.Id); + } + + // ---- where the message says the name came from ---- + + [Fact] + public static async Task ACaptureThatMatchesNoMarker_SaysTheCommandText_NotProcedure() + { + LocalDbFixture.SkipUnlessAvailable(); + await using SqlConnection connection = await OpenAsync(); + + var onCommand = await Assert.ThrowsAsync( + async () => await connection + .Command("select @a = 1") + .CaptureOutput(out DbCapture nothing) + .ExecuteNonQueryAsync(Token)); + var onDefinition = await Assert.ThrowsAsync( + async () => await DbQuery.Text("select @a = 1") + .Map() + .Using(connection) + .CaptureOutput(out DbCapture nothing) + .ToListAsync(Token)); + + Assert.Contains("the command text", onCommand.Message); + Assert.Contains("of the command text", onCommand.Message); + Assert.Contains("the command text", onDefinition.Message); + Assert.Contains("of the command text", onDefinition.Message); + } + + [Fact] + public static async Task ACaptureThatMatchesNoParameter_NamesTheProcedure_AndTheNameLastFix() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = Procedure( + "@a int output", + "set @a = 1;"); + await using SqlConnection connection = await OpenAsync(); + + var ex = await Assert.ThrowsAsync( + async () => await connection.StoredProcedure("dbo." + procedure.Name) + .CaptureOutput(out DbCapture nothing) + .ExecuteNonQueryAsync(Token)); + + Assert.Contains("dbo." + procedure.Name, ex.Message); + Assert.Contains("CaptureOutput(out DbCapture x, name)", ex.Message); + } +} diff --git a/Tests/Open.Database.Extensions.Core.Tests/CaptureNameTests.cs b/Tests/Open.Database.Extensions.Core.Tests/CaptureNameTests.cs new file mode 100644 index 00000000..c4900b2d --- /dev/null +++ b/Tests/Open.Database.Extensions.Core.Tests/CaptureNameTests.cs @@ -0,0 +1,376 @@ +using System.ComponentModel.DataAnnotations.Schema; +using System.Data.Common; + +#nullable enable + +namespace Open.Database.Extensions.Tests; + +// The name of a capture: what the compiler supplies from the variable, what +// the caller types last, and the one rule that reads both (CaptureNames). +// Over the provider that records its parameters (CaptureConnection). +[ExcludeFromCodeCoverage] +public static class CaptureNameTests +{ + static CancellationToken Token + => TestContext.Current.CancellationToken; + + public sealed record PostId(int Value); + + public sealed record OnlyTotal(int Total); + + sealed class Holder + { + public DbCapture total; + public DbCapture Total; + } + + static void Contains(Exception ex, params string[] phrases) + { + foreach (string phrase in phrases) Assert.Contains(phrase, ex.Message); + } + + // ---- the rule, row by row ---- + + [Theory] + [InlineData("DbCapture total", "total")] + [InlineData("DbCapture total", "total")] + [InlineData("var count", "count")] + [InlineData("existing", "existing")] + [InlineData("@class", "class")] + [InlineData("this.total", "total")] + [InlineData("this._total", "_total")] + [InlineData("state.total", "total")] + [InlineData("m_total", "m_total")] + [InlineData("arr[0].Total", "Total")] + [InlineData("c . F", "F")] + [InlineData("DbCapture values", "values")] + [InlineData("DbCapture<(int, int)> pair", "pair")] + [InlineData("global::Open.Database.Extensions.DbCapture total", "total")] + [InlineData("DbCapture\n\t\t\ttotal", "total")] + [InlineData("DbCapture spaced", "spaced")] + [InlineData("total$", "total$")] + [InlineData("#rows", "#rows")] + [InlineData(":total", "total")] + [InlineData("@total", "total")] + [InlineData("dbo.total", "total")] + [InlineData("total", "total")] + public static void TheNameIsTheLastIdentifier_OrTheTypedValue( + string text, + string expected) + => Assert.Equal(expected, CaptureNames.From(text).Name); + + [Theory] + [InlineData("_")] + [InlineData("DbCapture _")] + [InlineData("arr[0]")] + [InlineData("")] + [InlineData(" ")] + [InlineData("@")] + [InlineData(":")] + [InlineData(null)] + public static void ANameThatCannotBeTaken_IsRefusedWithTheFix(string? text) + { + var ex = Assert.Throws( + () => CaptureNames.From(text)); + + Contains(ex, "CaptureOutput(out DbCapture x, \"total\")"); + } + + [Theory] + [InlineData("m_total", "m_total", "total")] + [InlineData("s_total", "s_total", "total")] + [InlineData("_total", "_total", "total")] + [InlineData("this.m_total", "m_total", "total")] + public static void AFieldPrefix_IsAlsoTriedWithoutIt( + string text, + string first, + string second) + => Assert.Equal( + [first, second], + CaptureNames.From(text).Candidates); + + [Fact] + public static void NoChainNameIsATried_Candidate() + => Assert.True(CaptureNames.From("state.total").Candidates.IsDefault); + + [Fact] + public static void OnlyTextsThatAreNotOnePlainName_GetACacheEntry() + { + // An expression text is worked out once (the same instance); a plain + // name makes a new value each time and keeps nothing. + Assert.Same( + CaptureNames.From("DbCapture total"), + CaptureNames.From("DbCapture total")); + Assert.NotSame( + CaptureNames.From("total"), + CaptureNames.From("total")); + string built = new(['t', 'o', 't', 'a', 'l']); + Assert.Equal("total", CaptureNames.From(built).Name); + } + + // ---- on a command: the overloads and what they read ---- + + [Fact] + public static async Task AVariableDeclaredInline_NamesTheParameter() + { + var c = new CaptureConnection(("total", 7)); + + await c.StoredProcedure("p") + .CaptureOutput(out DbCapture total) + .ExecuteNonQueryAsync(Token); + + Assert.Equal(7, await total); + Assert.Equal( + ParameterDirection.Output, + c.Last!.Named("total").Direction); + } + + [Fact] + public static async Task AnExistingLocal_AndANullableType_NameTheParameter() + { + var c = new CaptureConnection(("existing", 1), ("maybe", DBNull.Value)); +#pragma warning disable IDE0018, IDE0059 // An existing local is the case under test. + DbCapture existing; +#pragma warning restore IDE0018, IDE0059 + + await c.StoredProcedure("p") + .CaptureOutput(out existing) + .CaptureOutput(out DbCapture maybe) + .ExecuteNonQueryAsync(Token); + + Assert.Equal(1, await existing); + Assert.Null(await maybe); + } + + [Fact] + public static async Task AVerbatimIdentifier_DropsItsAt() + { + var c = new CaptureConnection(("class", 3)); + + await c.StoredProcedure("p") + .CaptureOutput(out DbCapture @class) + .ExecuteNonQueryAsync(Token); + + Assert.Equal(3, await @class); + } + + [Fact] + public static async Task AField_ANestedMember_AndAnElementsMember_NameTheParameter() + { + var holder = new Holder(); + var holders = new[] { new Holder() }; + var c = new CaptureConnection(("total", 1)); + var c2 = new CaptureConnection(("Total", 2)); + + await c.StoredProcedure("p") + .CaptureOutput(out holder.total) + .ExecuteNonQueryAsync(Token); + await c2.StoredProcedure("p") + .CaptureOutput(out holders[0].Total) + .ExecuteNonQueryAsync(Token); + + Assert.Equal(1, await holder.total); + Assert.Equal(2, await holders[0].Total); + } + + [Fact] + public static async Task ANameTypedLast_IsTheName() + { + var c = new CaptureConnection(("total", 9)); + + await c.StoredProcedure("p") + .CaptureOutput(out DbCapture whatever, "total") + .ExecuteNonQueryAsync(Token); + + Assert.Equal(9, await whatever); + } + + [Fact] + public static async Task NamedArguments_AreAcceptedInAnyOrder() + { + var c = new CaptureConnection(("a", 1m), ("b", 2m)); + + await c.StoredProcedure("p") + .CaptureOutput(name: "a", output: out DbCapture one) + .CaptureOutput(scale: 2, precision: 10, value: out DbCapture two, name: "b") + .ExecuteNonQueryAsync(Token); + + Assert.Equal(1, await one); + Assert.Equal(2m, await two); + } + + [Fact] + public static async Task AStringT_IsAValue() + { + var c = new CaptureConnection(("title", "hello")); + + await c.StoredProcedure("p") + .CaptureOutput(out DbCapture title) + .ExecuteNonQueryAsync(Token); + + Assert.Equal("hello", await title); + } + + [Fact] + public static async Task TheDecimalForms_InferTheirName_AndTakeATypedOne() + { + var c = new CaptureConnection(("amount", 1.5m), ("fee", DBNull.Value), ("tax", 2m)); + + await c.StoredProcedure("p") + .CaptureOutput(out var amount, 10, 2) + .CaptureOutputDecimal(out DbCapture fee, 10, 2) + .CaptureOutput(out DbCapture whatever, 10, 2, "tax") + .ExecuteNonQueryAsync(Token); + + Assert.Equal(1.5m, await amount); + Assert.Null(await fee); + Assert.Equal(2m, await whatever); + } + + [Fact] + public static void CaptureReturn_TakesNoName() + { + var c = new CaptureConnection(("", 3)); + + Assert.NotNull(c.StoredProcedure("p") + .CaptureReturn(out DbCapture _)); + } + + // ---- refusals at the call ---- + + [Fact] + public static void ADiscard_AnElementAccess_AndANull_AreRefusedAtTheCall() + { + var c = new CaptureConnection(("x", 1)); + var holders = new[] { new DbCapture() }; + + Contains( + Assert.Throws( + () => c.StoredProcedure("p").CaptureOutput(out DbCapture _)), + "a discard (_)", + "CaptureOutput(out DbCapture x, \"total\")"); + Contains( + Assert.Throws( + () => c.StoredProcedure("p").CaptureOutput(out holders[0])), + "element access (arr[0])"); + Contains( + Assert.Throws( + () => c.StoredProcedure("p").CaptureOutput(out DbCapture v, null)), + "The output parameter's name was not given", + "CaptureOutput(out DbCapture x, \"total\")"); + } + + [Theory] + [InlineData("total$", "total$")] + [InlineData("#rows", "#rows")] + [InlineData(":total", "total")] + [InlineData("@total", "total")] + [InlineData("dbo.total", "total")] + public static async Task ATypedName_IsAValue_OrItsLastIdentifier( + string typed, + string parameter) + { + var c = new CaptureConnection((parameter, 4)); + + await c.StoredProcedure("p") + .CaptureOutput(out DbCapture x, typed) + .ExecuteNonQueryAsync(Token); + + Assert.Equal(4, await x); + Assert.NotNull(c.Last!.Named(parameter)); + } + + [Fact] + public static async Task ATypedNameBuiltAtRunTime_InALoop_WorksEachTime() + { + for (int i = 0; i < 3; i++) + { + string name = "p" + i; + var c = new CaptureConnection((name, i)); + + await c.StoredProcedure("p") + .CaptureOutput(out DbCapture x, name) + .ExecuteNonQueryAsync(Token); + + Assert.Equal(i, await x); + } + } + + [Fact] + public static async Task AModel_NeverDerivesOrRefusesAName() + { + var c = new CaptureConnection(("Total", 5)); + + await c.StoredProcedure("p") + .CaptureOutput(out DbCapture _) + .ExecuteNonQueryAsync(Token); + var holders = new[] { new DbCapture() }; + var c2 = new CaptureConnection(("Total", 6)); + await c2.StoredProcedure("p") + .CaptureOutput(out holders[0]) + .ExecuteNonQueryAsync(Token); + var c3 = new CaptureConnection(("Total", 7)); + await c3.StoredProcedure("p") + .CaptureOutput(out DbCapture model, null) + .ExecuteNonQueryAsync(Token); + + Assert.Equal(new OnlyTotal(7), await model); + } + + [Fact] + public static void TheDecimalFormWithoutAShape_NamesBothForms() + { + var c = new CaptureConnection(("a", 1m)); + + Contains( + Assert.Throws( + () => c.StoredProcedure("p").CaptureOutput(out DbCapture _, "a")), + "A decimal output needs its precision and scale", + "CaptureOutput(out DbCapture x, 19, 4, \"a\")", + "CaptureOutputDecimal(out DbCapture x, 19, 4, \"a\")"); + } + + [Fact] + public static void EveryMessageThatNamesACaptureForm_NamesTheNameLastForm() + { + var c = new CaptureConnection(("a", 1)); + + Contains( + Assert.Throws( + () => c.StoredProcedure("p").CaptureOutput(out DbCapture _, "x") + .CaptureOutput(out DbCapture _)), + "CaptureOutput(out DbCapture x)"); + Contains( + Assert.Throws( + () => c.StoredProcedure("p").CaptureOutput(out DbCapture _, "x") + .CaptureOutput(out DbCapture _, "@X")), + "CaptureOutput(out DbCapture x)", + "Capture each parameter once"); + } + + [Fact] + public static async Task AnOverloadWithAByteLiteral_NeverBindsTheName() + { + var c = new CaptureConnection(("a", 1m)); + + // 10 and 2 are the precision and scale; the name comes from the variable. + await c.StoredProcedure("p") + .CaptureOutput(out DbCapture a, 10, 2) + .ExecuteNonQueryAsync(Token); + + Assert.Equal(1m, await a); + } + + [Fact] + public static void OnTheQueryViews_TheSameForms_Exist() + { + var c = new CaptureConnection(("total", 1)); + + _ = c.StoredProcedure("p").Map() + .CaptureOutput(out DbCapture _, "total"); + _ = c.StoredProcedure("p").Map().Skip(1) + .CaptureOutput(out DbCapture _, "total"); + _ = c.StoredProcedure("p").Map().Take(1) + .CaptureOutput(out DbCapture _, "total"); + } +} diff --git a/Tests/Open.Database.Extensions.Core.Tests/CaptureStreamTests.cs b/Tests/Open.Database.Extensions.Core.Tests/CaptureStreamTests.cs index b434ed45..dddc7113 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/CaptureStreamTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/CaptureStreamTests.cs @@ -26,7 +26,7 @@ static MappedQuery Query( out DbCapture total) => c.StoredProcedure("p") .Map() - .CaptureOutput("total", out total); + .CaptureOutput(out total, "total"); // ---- a run that fails ------------------------------------------------ @@ -615,7 +615,7 @@ sealed class PlainDbCommand(CaptureConnection connection) static MappedQuery OnCommand( OwnReaderCommand command, out DbCapture total) - => command.CaptureOutput("total", out total) + => command.CaptureOutput(out total, "total") .Map(); [Fact] @@ -626,7 +626,7 @@ public static void AQueryCapture_OnAReimplementingCommand_IsRefusedAtTheCall() MappedQuery query = command.Map(); var ex = Assert.Throws( - () => query.CaptureOutput("total", out _)); + () => query.CaptureOutput(out DbCapture _, "total")); Contains( ex, nameof(OwnReaderCommand), @@ -635,7 +635,7 @@ public static void AQueryCapture_OnAReimplementingCommand_IsRefusedAtTheCall() Assert.Throws( () => query.CaptureReturn(out _)); Assert.Throws( - () => query.Skip(1).CaptureOutput("total", out _)); + () => query.Skip(1).CaptureOutput(out DbCapture _, "total")); Assert.Equal(0, command.OwnReads); Assert.Equal(0, c.Executed); } @@ -718,14 +718,14 @@ public static async Task ACommandCapture_OnAReimplementingCommand_IsRefusedAtThe } case "AsObjectArrays": { - command.CaptureOutput("total", out total); + command.CaptureOutput(out total, "total"); run = async () => await command.AsObjectArrays().ToListAsync(Token); break; } default: { - command.CaptureOutput("total", out total); + command.CaptureOutput(out total, "total"); run = async () => await command.SingleResult() .Map() .ToListAsync(Token); @@ -823,7 +823,7 @@ public static async Task APlainSubclass_FillsItsCapture_OnBothForms() var c = new CaptureConnection(("total", 9)); List onCommand = await new PlainCommand(c) - .CaptureOutput("total", out DbCapture first) + .CaptureOutput(out DbCapture first, "total") .Map() .ToListAsync(Token); Assert.Equal(3, onCommand.Count); @@ -831,13 +831,13 @@ public static async Task APlainSubclass_FillsItsCapture_OnBothForms() List onQuery = await new PlainCommand(c) .Map() - .CaptureOutput("total", out DbCapture second) + .CaptureOutput(out DbCapture second, "total") .ToListAsync(Token); Assert.Equal(3, onQuery.Count); Assert.Equal(9, await second); List onDbCommand = await new PlainDbCommand(c) - .CaptureOutput("total", out DbCapture third) + .CaptureOutput(out DbCapture third, "total") .Map() .ToListAsync(Token); Assert.Equal(3, onDbCommand.Count); @@ -845,7 +845,7 @@ public static async Task APlainSubclass_FillsItsCapture_OnBothForms() List onDbQuery = await new PlainDbCommand(c) .Map() - .CaptureOutput("total", out DbCapture fourth) + .CaptureOutput(out DbCapture fourth, "total") .ToListAsync(Token); Assert.Equal(3, onDbQuery.Count); Assert.Equal(9, await fourth); @@ -862,14 +862,14 @@ public static async Task ALibraryCommand_WithACapture_NeedsNoLookup() var c = new CaptureConnection(("total", 9)); await new ExpressiveCommand(() => c, CommandType.StoredProcedure, "p") - .CaptureOutput("total", out DbCapture first) + .CaptureOutput(out DbCapture first, "total") .Map() .ToListAsync(Token); Assert.Equal(9, await first); await new ExpressiveDbCommand(() => c, CommandType.StoredProcedure, "p") .Map() - .CaptureOutput("total", out DbCapture second) + .CaptureOutput(out DbCapture second, "total") .ToListAsync(Token); Assert.Equal(9, await second); @@ -890,7 +890,7 @@ public static async Task ANullTransform_ThrowsBeforeArming() { var c = new CaptureConnection(("total", 9)); var command = c.StoredProcedure("p") - .CaptureOutput("total", out DbCapture total); + .CaptureOutput(out DbCapture total, "total"); var reader = (IExecuteReader)command; await Assert.ThrowsAsync( diff --git a/Tests/Open.Database.Extensions.Core.Tests/CaptureTests.cs b/Tests/Open.Database.Extensions.Core.Tests/CaptureTests.cs index 6007687f..0b34c079 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/CaptureTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/CaptureTests.cs @@ -41,7 +41,7 @@ public static async Task OnACommand_TheNextTerminalFillsIt() int rows = await c .StoredProcedure("p") - .CaptureOutput("total", out DbCapture total) + .CaptureOutput(out DbCapture total, "total") .ExecuteNonQueryAsync(Token); Assert.Equal(1, rows); @@ -73,8 +73,8 @@ public static async Task NamedCaptures_AndADecimal_OnOneCommand() await c .StoredProcedure("p") - .CaptureOutput("count", out DbCapture count) - .CaptureOutputDecimal("amount", 10, 2, out DbCapture amount) + .CaptureOutput(out DbCapture count, "count") + .CaptureOutputDecimal(out DbCapture amount, 10, 2, "amount") .ExecuteNonQueryAsync(Token); Assert.Equal(7, await count); @@ -105,8 +105,8 @@ public static async Task TheShapedForm_LetsTDecideNull() await c .StoredProcedure("p") - .CaptureOutput("a", 19, 4, out DbCapture a) - .CaptureOutput("b", 19, 4, out DbCapture b) + .CaptureOutputDecimal(out DbCapture a, 19, 4, "a") + .CaptureOutput(out DbCapture b, 19, 4, "b") .ExecuteNonQueryAsync(Token); Assert.Null(await a); @@ -122,7 +122,7 @@ public static async Task AddParam_AfterACapture_KeepsIt() await c .StoredProcedure("p") - .CaptureOutput("total", out DbCapture total) + .CaptureOutput(out DbCapture total, "total") .AddParam("other", 1) .ExecuteNonQueryAsync(Token); @@ -136,7 +136,7 @@ public static async Task ACommandWithACapture_RunsOnce() var c = new CaptureConnection(("total", 5)); var command = c .StoredProcedure("p") - .CaptureOutput("total", out DbCapture total); + .CaptureOutput(out DbCapture total, "total"); await command.ExecuteNonQueryAsync(Token); Assert.Equal(5, await total); @@ -156,9 +156,9 @@ public static async Task AnyAsyncAndCountAsync_OnACommand_FillIt() { var c = new CaptureConnection(("total", 5)); var any = c.StoredProcedure("p") - .CaptureOutput("total", out DbCapture first); + .CaptureOutput(out DbCapture first, "total"); var count = c.StoredProcedure("p") - .CaptureOutput("total", out DbCapture second); + .CaptureOutput(out DbCapture second, "total"); Assert.True(await any.AnyAsync(Token)); Assert.Equal(3, await count.CountAsync(Token)); @@ -180,7 +180,7 @@ public static void ASynchronousTerminal_Throws_AndArmsNothing() var c = new CaptureConnection(("total", 5)); var command = c .StoredProcedure("p") - .CaptureOutput("total", out DbCapture total); + .CaptureOutput(out DbCapture total, "total"); var ex = Assert.Throws( () => command.ExecuteNonQuery()); @@ -202,7 +202,7 @@ public static async Task ExecuteAsyncWithAFunction_IsRefused_AndFaultsIt() var c = new CaptureConnection(("total", 5)); var command = c .StoredProcedure("p") - .CaptureOutput("total", out DbCapture total); + .CaptureOutput(out DbCapture total, "total"); var ex = await Assert.ThrowsAsync( async () => await command.ExecuteAsync( @@ -220,7 +220,7 @@ public static async Task ExecuteOutputAsync_BesideACapture_IsRefused() var c = new CaptureConnection(("total", 5)); var command = c .StoredProcedure("p") - .CaptureOutput("total", out DbCapture total); + .CaptureOutput(out DbCapture total, "total"); var ex = await Assert.ThrowsAsync( async () => await command.ExecuteOutputAsync("other", Token)); @@ -272,7 +272,7 @@ public static async Task ExecuteScalarAsync_WithANullTransform_ArmsNothing() { var c = new CaptureConnection(("total", 5)); var command = c.StoredProcedure("p") - .CaptureOutput("total", out DbCapture total); + .CaptureOutput(out DbCapture total, "total"); await Assert.ThrowsAsync( async () => await command.ExecuteScalarAsync( @@ -316,7 +316,7 @@ public static async Task ExecuteReturnAsync_BesideANamedCapture_Runs() int code = await c .StoredProcedure("p") - .CaptureOutput("total", out DbCapture total) + .CaptureOutput(out DbCapture total, "total") .ExecuteReturnAsync(Token); Assert.Equal(4, code); @@ -340,14 +340,14 @@ public static void EachOutput_HasOneOwner_CheckedAtTheCall() Contains( Assert.Throws(() => c .StoredProcedure("p") - .CaptureOutput("total", out DbCapture _) + .CaptureOutput(out DbCapture _, "total") .CaptureOutput(out DbCapture _)), "reads its output parameters twice"); Contains( Assert.Throws(() => c .StoredProcedure("p") - .CaptureOutput("@Total", out DbCapture _) - .CaptureOutput("total", out DbCapture _)), + .CaptureOutput(out DbCapture _, "@Total") + .CaptureOutput(out DbCapture _, "total")), "reads output parameter @Total twice", "Capture each parameter once"); Contains( @@ -383,32 +383,26 @@ public static void TheArguments_AreCheckedAtTheCall() { var c = new CaptureConnection(); - Assert.Throws(() => c + Assert.Throws(() => c .StoredProcedure("p") - .CaptureOutput(null!, out DbCapture _)); + .CaptureOutput(out DbCapture _, null!)); Assert.Throws(() => c .StoredProcedure("p") - .CaptureOutput("@", out DbCapture _)); + .CaptureOutput(out DbCapture _, "@")); Assert.Throws(() => c .StoredProcedure("p") - .CaptureOutputDecimal("a", 0, 0, out DbCapture _)); - Assert.Throws(() => c - .StoredProcedure("p") - .CaptureOutput("a", 10, 2, out DbCapture _)); + .CaptureOutputDecimal(out DbCapture _, 0, 0, "a")); Assert.Throws(() => c .StoredProcedure("p") - .CaptureOutput("a", out DbCapture _)); + .CaptureOutput(out DbCapture _, "a")); // decimal? too: a decimal needs its precision and scale. Contains( Assert.Throws( () => c.StoredProcedure("p") - .CaptureOutput("a", out DbCapture _)), + .CaptureOutput(out DbCapture _, "a")), "A decimal output needs its precision and scale", - "CaptureOutputDecimal(\"a\", 19, 4, out …)"); - Assert.Throws(() => c - .StoredProcedure("p") - .CaptureOutput(out DbCapture _)); + "CaptureOutputDecimal(out DbCapture x, 19, 4, \"a\")"); } // ---- the mapped query ------------------------------------------------ @@ -421,7 +415,7 @@ public static async Task OnAQuery_TheTerminalFillsIt_BeforeItsTaskCompletes() List rows = await c .StoredProcedure("p") .Map() - .CaptureOutput("total", out DbCapture total) + .CaptureOutput(out DbCapture total, "total") .ToListAsync(Token); Assert.Equal(3, rows.Count); @@ -436,10 +430,10 @@ public static async Task FirstAsyncAndSingleAsync_WithNoRows_StillFillIt() var c = new CaptureConnection(("total", 9)) { Rows = 0 }; MappedQuery first = c.StoredProcedure("p") .Map() - .CaptureOutput("total", out DbCapture firstTotal); + .CaptureOutput(out DbCapture firstTotal, "total"); MappedQuery single = c.StoredProcedure("p") .Map() - .CaptureOutput("total", out DbCapture singleTotal); + .CaptureOutput(out DbCapture singleTotal, "total"); Contains( await Assert.ThrowsAsync( @@ -463,7 +457,7 @@ public static async Task TheSkipAndTakeViews_CarryIt() .StoredProcedure("p") .Map() .Skip(1) - .CaptureOutput("total", out DbCapture total) + .CaptureOutput(out DbCapture total, "total") .CaptureReturn(out DbCapture code) .ToListAsync(Token); List taken = await c @@ -493,14 +487,14 @@ public static async Task ACapture_SurvivesWithOptions_OnTheQueryAndTheSkipView() List rows = await c .StoredProcedure("p") .Map() - .CaptureOutput("total", out DbCapture total) + .CaptureOutput(out DbCapture total, "total") .WithOptions(QueryOptions.SingleResult) .ToListAsync(Token); List skipped = await c .StoredProcedure("p") .Map() .Skip(1) - .CaptureOutput("total", out DbCapture skipTotal) + .CaptureOutput(out DbCapture skipTotal, "total") .WithOptions(QueryOptions.SingleResult) .ToListAsync(Token); @@ -516,7 +510,7 @@ public static async Task Map_SharesTheCommandsCapture_TheFirstRunTakesIt() var c = new CaptureConnection(("total", 9)); var command = c .StoredProcedure("p") - .CaptureOutput("total", out DbCapture total); + .CaptureOutput(out DbCapture total, "total"); MappedQuery query = command.Map(); Assert.Equal(3, (await query.ToListAsync(Token)).Count); @@ -538,7 +532,7 @@ public static async Task ACaptureAddedToTheCommandAfterMap_IsFilled() var command = c.StoredProcedure("p"); MappedQuery query = command.Map(); - _ = command.CaptureOutput("total", out DbCapture total); + _ = command.CaptureOutput(out DbCapture total, "total"); Assert.Equal(3, (await query.ToListAsync(Token)).Count); Assert.Equal(9, await total); @@ -551,7 +545,7 @@ public static async Task AQueryWithACapture_RunsOnce() MappedQuery query = c .StoredProcedure("p") .Map() - .CaptureOutput("total", out DbCapture _); + .CaptureOutput(out DbCapture _, "total"); await query.ToListAsync(Token); Contains( @@ -568,7 +562,7 @@ public static async Task EveryBuilder_CarriesIt_AndItIsPartOfTheEquality() var c = new CaptureConnection(("total", 9)); MappedQuery plain = c.StoredProcedure("p").Map(); MappedQuery captured = plain - .CaptureOutput("total", out DbCapture total); + .CaptureOutput(out DbCapture total, "total"); MappedQuery copy = captured; Assert.NotEqual(plain, captured); @@ -593,11 +587,11 @@ public static async Task ASynchronousTerminal_OnAQuery_Throws_AndArmsNothing() MappedQuery query = c .StoredProcedure("p") .Map() - .CaptureOutput("total", out DbCapture total); + .CaptureOutput(out DbCapture total, "total"); Contains( Assert.Throws(() => query.ToList()), - "This query has CaptureOutput(\"total\")", + "This query has CaptureOutput(out DbCapture total)", "ToListAsync instead of ToList"); Assert.Throws(() => { _ = total.AsTask(); }); @@ -613,7 +607,7 @@ public static async Task CancelOnEarlyStop_IsRefused_AndFaultsIt() var query = c .StoredProcedure("p") .Map() - .CaptureOutput("total", out DbCapture total) + .CaptureOutput(out DbCapture total, "total") .CancelOnEarlyStop(); var ex = await Assert.ThrowsAsync( @@ -631,20 +625,12 @@ await Assert.ThrowsAsync( [Fact] public static void AQuery_ThatIsNotFromAnExpressiveCommand_RefusesIt() { - var c = new CaptureConnection(); FakeExecuteReader source = new(["Id"], [1]); - Contains( - Assert.Throws(() => DbQuery - .Text("select") - .Using(c) - .Map() - .CaptureOutput("total", out DbCapture _)), - "a query from a DbQuery definition cannot take a capture"); Contains( Assert.Throws(() => source .Map() - .CaptureOutput("total", out DbCapture _)), + .CaptureOutput(out DbCapture _, "total")), "this query reads from FakeExecuteReader, which cannot"); } @@ -660,7 +646,7 @@ public static async Task ItIsArmedAtTheCall_SoItCanBeAwaitedBeforeTheTerminal() MappedQuery query = c .StoredProcedure("p") .Map() - .CaptureOutput("total", out DbCapture total); + .CaptureOutput(out DbCapture total, "total"); ValueTask> pending = query.ToListAsync(Token); Task task = total.AsTask(); @@ -683,11 +669,11 @@ public static void BeforeTheTerminal_EveryMemberThrows() { var c = new CaptureConnection(); _ = c.StoredProcedure("p") - .CaptureOutput("total", out DbCapture total); + .CaptureOutput(out DbCapture total, "total"); Contains( Assert.Throws(() => total.GetAwaiter()), - "CaptureOutput(\"total\") has not started", + "CaptureOutput(out DbCapture total) has not started", "Call the query's terminal first"); Assert.Throws( () => total.ConfigureAwait(false)); @@ -716,7 +702,7 @@ public static async Task ACanceledToken_CancelsIt() MappedQuery query = c .StoredProcedure("p") .Map() - .CaptureOutput("total", out DbCapture total); + .CaptureOutput(out DbCapture total, "total"); await Assert.ThrowsAnyAsync( async () => await query.ToListAsync(canceled.Token)); @@ -732,7 +718,7 @@ public static async Task ConfigureAwait_ReadsIt() await c .StoredProcedure("p") - .CaptureOutput("total", out DbCapture total) + .CaptureOutput(out DbCapture total, "total") .ExecuteNonQueryAsync(Token); Assert.Equal(9, await total.ConfigureAwait(false)); @@ -747,7 +733,7 @@ public static async Task TwoRacingTerminals_OneRuns_TheOtherThrows() MappedQuery query = c .StoredProcedure("p") .Map() - .CaptureOutput("total", out DbCapture total); + .CaptureOutput(out DbCapture total, "total"); using var barrier = new Barrier(2); Task Run() @@ -835,7 +821,7 @@ static async Task FaultWithoutAwaiting() var query = c .StoredProcedure("p") .Map() - .CaptureOutput("total", out DbCapture total) + .CaptureOutput(out DbCapture total, "total") .CancelOnEarlyStop(); await Assert.ThrowsAsync( async () => await query.ToListAsync(Token)); @@ -846,7 +832,7 @@ static async Task FaultOnlyTheCapture(string name) { var c = new CaptureConnection((name, DBNull.Value)); var command = c.StoredProcedure("p") - .CaptureOutput(name, 19, 4, out DbCapture v); + .CaptureOutput(out DbCapture v, 19, 4, name); await command.ExecuteNonQueryAsync(Token); Assert.True(v.AsTask().IsFaulted); } @@ -863,7 +849,7 @@ public static async Task EveryStream_DeliversOnABreak(string kind) MappedQuery query = c .StoredProcedure("p") .Map() - .CaptureOutput("total", out DbCapture total); + .CaptureOutput(out DbCapture total, "total"); var forever = Timeout.InfiniteTimeSpan; int seen = kind switch @@ -898,7 +884,7 @@ public static async Task APooledBuffer_ClaimsAtTheCall_AndDelivers() MappedQuery query = c .StoredProcedure("p") .Map() - .CaptureOutput("total", out DbCapture total); + .CaptureOutput(out DbCapture total, "total"); using (PooledBuffer buffer = query.ToPooledBuffer(Token)) { @@ -920,7 +906,7 @@ public static async Task CancelingTheEnumeration_CancelsIt() IAsyncEnumerable rows = c .StoredProcedure("p") .Map() - .CaptureOutput("total", out DbCapture total) + .CaptureOutput(out DbCapture total, "total") .Stream(Timeout.InfiniteTimeSpan, Token); await Assert.ThrowsAnyAsync(async () => @@ -944,7 +930,7 @@ public static async Task AStream_FillsItWhenTheLoopEnds_EvenOnABreak() IAsyncEnumerable rows = c .StoredProcedure("p") .Map() - .CaptureOutput("total", out DbCapture total) + .CaptureOutput(out DbCapture total, "total") .Stream(Timeout.InfiniteTimeSpan, Token); Task? handed = null; @@ -970,7 +956,7 @@ public static async Task AStreamDisposedBeforeItsFirstRow_NeverRan() IAsyncEnumerable rows = c .StoredProcedure("p") .Map() - .CaptureOutput("total", out DbCapture total) + .CaptureOutput(out DbCapture total, "total") .Stream(Timeout.InfiniteTimeSpan, Token); await rows.GetAsyncEnumerator(Token).DisposeAsync(); @@ -1000,15 +986,15 @@ public static async Task ACommandCapture_AddedAfterMap_IsFilledToo( MappedQuery query; if (commandFirst) { - command.CaptureOutput("count", out count); + command.CaptureOutput(out count, "count"); query = command.Map() - .CaptureOutput("total", out total); + .CaptureOutput(out total, "total"); } else { query = command.Map() - .CaptureOutput("total", out total); - command.CaptureOutput("count", out count); + .CaptureOutput(out total, "total"); + command.CaptureOutput(out count, "count"); } if (stream) @@ -1035,8 +1021,8 @@ public static async Task ALateCommandCapture_ThatConflicts_ThrowsAtTheTerminal() var c = new CaptureConnection(("total", 9)); var command = c.StoredProcedure("p"); MappedQuery query = command.Map() - .CaptureOutput("total", out DbCapture own); - command.CaptureOutput("total", out DbCapture late); + .CaptureOutput(out DbCapture own, "total"); + command.CaptureOutput(out DbCapture late, "total"); Contains( await Assert.ThrowsAsync( @@ -1061,8 +1047,8 @@ public static void ALateCommandCapture_ThatConflicts_ThrowsAtASyncTerminal() var c = new CaptureConnection(("total", 9)); var command = c.StoredProcedure("p"); MappedQuery query = command.Map() - .CaptureOutput("total", out DbCapture _); - command.CaptureOutput("total", out DbCapture _); + .CaptureOutput(out DbCapture _, "total"); + command.CaptureOutput(out DbCapture _, "total"); Contains( Assert.Throws(() => query.ToList()), @@ -1076,8 +1062,8 @@ public static void ALateCommandCapture_ThatConflicts_ThrowsAtAStreamCall() var c = new CaptureConnection(("total", 9)); var command = c.StoredProcedure("p"); MappedQuery query = command.Map() - .CaptureOutput("total", out DbCapture _); - command.CaptureOutput("total", out DbCapture _); + .CaptureOutput(out DbCapture _, "total"); + command.CaptureOutput(out DbCapture _, "total"); Contains( Assert.Throws( @@ -1098,19 +1084,19 @@ public static async Task ACommandCapture_AddedAfterTheStreamIsMade_IsNotFilled( var c = new CaptureConnection(("total", 9), ("count", 4)); var command = c.StoredProcedure("p"); MappedQuery query = command.Map() - .CaptureOutput("total", out DbCapture total); + .CaptureOutput(out DbCapture total, "total"); if (buffer) { using PooledBuffer made = query.ToPooledBuffer(Token); - command.CaptureOutput("count", out DbCapture late); + command.CaptureOutput(out DbCapture late, "count"); _ = await made.Items; AssertNotFilled(c, late); } else { IAsyncEnumerable rows = query.ToPooledStream(Token); - command.CaptureOutput("count", out DbCapture late); + command.CaptureOutput(out DbCapture late, "count"); await foreach (Row _ in rows) { } AssertNotFilled(c, late); } diff --git a/Tests/Open.Database.Extensions.Core.Tests/PumpStreamOpenTests.cs b/Tests/Open.Database.Extensions.Core.Tests/PumpStreamOpenTests.cs index 2111751b..54cf1ef3 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/PumpStreamOpenTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/PumpStreamOpenTests.cs @@ -59,7 +59,7 @@ public static async Task CapturedStream_OverChunks_StartsNothing_UntilTheFirstPu DbTally tally = Tally(3); IAsyncEnumerable> stream = Read(tally) - .CaptureOutput("total", out DbCapture total) + .CaptureOutput(out DbCapture total, "total") .ToPooledBufferStream(Ct); Assert.IsType>>(stream); @@ -74,7 +74,7 @@ public static async Task CapturedStream_OverRows_StartsNothing_UntilTheFirstPull DbTally tally = Tally(3); IAsyncEnumerable stream = Read(tally) - .CaptureOutput("total", out DbCapture total) + .CaptureOutput(out DbCapture total, "total") .StreamBuffered(Long, 1, Ct); Assert.IsType>(stream); diff --git a/Tests/Open.Database.Extensions.LegacyCompiler.Tests/BoundCallCaptureBindingTests.cs b/Tests/Open.Database.Extensions.LegacyCompiler.Tests/BoundCallCaptureBindingTests.cs new file mode 100644 index 00000000..f6230132 --- /dev/null +++ b/Tests/Open.Database.Extensions.LegacyCompiler.Tests/BoundCallCaptureBindingTests.cs @@ -0,0 +1,98 @@ +using System; +using System.Data; +using System.Data.Common; +using Xunit; + +namespace Open.Database.Extensions.LegacyCompiler.Tests +{ + // The captures on a bound write and a bound scalar are extension methods of + // those kinds, and the type of the value comes only from a typed out + // declaration. They compile and build their calls at every language version + // of this project (C# 7.3, 9, 12 and 13), with the name taken from the + // variable or passed last. Nothing here runs a query. + public static class BoundCallCaptureBindingTests + { + sealed class NoConnection : DbConnection + { + public override string ConnectionString { get; set; } + public override string Database => ""; + public override string DataSource => ""; + public override string ServerVersion => ""; + public override ConnectionState State => ConnectionState.Closed; + public override void ChangeDatabase(string databaseName) => throw new NotSupportedException(); + public override void Close() { } + public override void Open() => throw new NotSupportedException(); + protected override DbTransaction BeginDbTransaction(IsolationLevel isolationLevel) => throw new NotSupportedException(); + protected override DbCommand CreateDbCommand() => throw new NotSupportedException(); + } + + [Fact] + public static void ATypedOutDeclaration_OnAWriteAndOnAScalar_Compiles() + { + var connection = new NoConnection(); + DbNonQuery write = DbNonQuery.Procedure("dbo.P"); + ScalarDbQuery scalar = DbQuery.Procedure("dbo.P").Scalar(); + DbCapture existing; + + BoundCall a = write.Using(connection) + .CaptureOutput(out DbCapture total) + .CaptureOutput(out existing) + .CaptureReturn(out DbCapture code); + BoundCall> b = scalar.Using(connection) + .CaptureOutput(out DbCapture scalarTotal) + .CaptureReturn(out DbCapture scalarCode); + + Assert.NotEqual(write.Using(connection), a); + Assert.NotEqual(scalar.Using(connection), b); + } + + [Fact] + public static void TheDecimalForms_OnAWriteAndOnAScalar_TakeOutVar() + { + var connection = new NoConnection(); + DbNonQuery write = DbNonQuery.Procedure("dbo.P"); + ScalarDbQuery scalar = DbQuery.Procedure("dbo.P").Scalar(); + + BoundCall a = write.Using(connection) + .CaptureOutput(out var amount, 18, 2) + .CaptureOutputDecimal(out var fee, 18, 2); + BoundCall> b = scalar.Using(connection) + .CaptureOutput(out var scalarAmount, 18, 2) + .CaptureOutputDecimal(out var scalarFee, 18, 2); + + DbCapture shaped = amount; + DbCapture nullable = fee; + DbCapture scalarShaped = scalarAmount; + DbCapture scalarNullable = scalarFee; + Assert.NotEqual(write.Using(connection), a); + Assert.NotEqual(scalar.Using(connection), b); + } + + [Fact] + public static void TheNamePassedLast_IsAccepted_OnEveryVersion() + { + var connection = new NoConnection(); + DbNonQuery write = DbNonQuery.Procedure("dbo.P"); + + BoundCall a = write.Using(connection) + .CaptureOutput(out DbCapture whatever, "total") + .CaptureOutput(out DbCapture amount, 18, 2, "amount"); + + Assert.NotEqual(write.Using(connection), a); + } + + [Fact] + public static void ADeclaredCaptureOnAWriteWithTheTypeArgument_Compiles() + { + var connection = new NoConnection(); + DbNonQuery write = DbNonQuery.Procedure("dbo.P"); + + BoundCall a = write.Using(connection) + .CaptureOutput(out var total, "total") + .CaptureReturn(out var code); + + DbCapture check = total; + Assert.NotEqual(write.Using(connection), a); + } + } +} diff --git a/docsite/articles/release-notes.md b/docsite/articles/release-notes.md index 67faabe4..12d4c983 100644 --- a/docsite/articles/release-notes.md +++ b/docsite/articles/release-notes.md @@ -10,7 +10,7 @@ Version 11 is `11.0.0-rc.16`. For moving a 10.x codebase, read [Coming from earl - **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. -- **Read output parameters: `ExecuteOutputAsync()`.** It maps a command's output parameters and return code into a model by name, with the `Map()` rules; `ExecuteOutputAsync(name)` reads one value, and `CaptureOutput(name, ...)` captures one; a name finds its parameter the way `AddParam`'s name does (exactly, else ignoring case, else ignoring case and underscores, else without a common prefix such as `p_`), so `"totalCount"` finds `@total_count`. A `decimal` declares its SQL type: `[Column(TypeName = "decimal(p,s)")]` on a member, or `ExecuteOutputAsync(name, precision, scale)` (`ExecuteOutputDecimalAsync`) for one value. See [Output parameters](expressive-commands.md#output-parameters). +- **Read output parameters: `ExecuteOutputAsync()`.** It maps a command's output parameters and return code into a model by name, with the `Map()` rules; `ExecuteOutputAsync(name)` reads one value, and `CaptureOutput(out DbCapture value, name)` captures one; a name finds its parameter the way `AddParam`'s name does (exactly, else ignoring case, else ignoring case and underscores, else without a common prefix such as `p_`), so `"totalCount"` finds `@total_count`. A `decimal` declares its SQL type: `[Column(TypeName = "decimal(p,s)")]` on a member, or `ExecuteOutputAsync(name, precision, scale)` (`ExecuteOutputDecimalAsync`) for one value. See [Output parameters](expressive-commands.md#output-parameters). - **New: captures, output parameters beside rows.** `CaptureOutput` (a model, one value, or a `decimal` with its precision and scale), `CaptureOutputDecimal` and `CaptureReturn` on an expressive command, a mapped query and its `Skip` and `Take` views give a `DbCapture` as an `out` argument; the async terminal fills it, and a stream fills it when its loop ends, a `break` included. A capture runs once and needs an async terminal; a query's run fills the captures its command has when the run starts, including one added after `Map`. Misuse throws at the call, except that the return code of a command that is not a stored procedure is refused when the run starts: `NotSupportedException` on a query made from a definition or one that does not read from an expressive command, `InvalidOperationException` otherwise. A command whose type re-implements `IExecuteReader` is refused too, as `NotSupportedException` on a query capture and `InvalidOperationException` when a command capture runs. See [Output parameters beside rows](expressive-commands.md#output-parameters-beside-rows). - **New: `ToArrayAsync` and `ToImmutableArrayAsync` on a `DbDataReader`.** Like `ToListAsync(transform)`, they read the remaining rows of the current result set through an asynchronous transform into pooled chunks and copy them once, into an array of exactly their number; on .NET 8 and later the immutable array wraps that array and does not copy it again (on .NET Standard it is a copy). - **Changed: the collecting terminals clear their value rows when no pool is offered.** `ToList`, `ToArray`, `ToImmutableArray`, `ToHashSet` and the dictionaries, asynchronous and synchronous, on a view or on a `DbDataReader`, copy their rows out and never show their pooled arrays, so they hide their pooling: a query that does not call `UsePool` now always clears the used rows of those arrays before they go back, plain value rows included, whatever the `Open.Database.Extensions.ClearPooledArrays` switch says. `UsePool(pool, clearOnReturn)` is followed as before, so `clearOnReturn: false` still keeps the rows. Rows that hold references were always cleared. The buffers and streams are unchanged: their default is still not to clear value rows. A chunk of 128 KB or more is cleared in the background, as before, and the allocation of a call is the same. From 20546c41b255fc0e5872a98bf7d4b2851683fb0c Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Wed, 2 Dec 2026 10:23:48 -0800 Subject: [PATCH 04/17] Samples use the name-last capture forms The output-parameter sample passes the name last, as the capture members now take it. Co-Authored-By: Claude Sonnet 5.5 --- docsite/samples/OutputParameters.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docsite/samples/OutputParameters.cs b/docsite/samples/OutputParameters.cs index 2ee83068..4849dc95 100644 --- a/docsite/samples/OutputParameters.cs +++ b/docsite/samples/OutputParameters.cs @@ -86,7 +86,7 @@ public static async Task Page( .StoredProcedure("[dbo].[PagePosts]") .AddParam(page) .Map() - .CaptureOutput("total", out DbCapture total) + .CaptureOutput(out DbCapture total, "total") .ToListAsync(cancellationToken); // Filled by the time the terminal's task completes: await it after. @@ -126,7 +126,7 @@ public static async Task Export( IAsyncEnumerable rows = Blog .StoredProcedure("[dbo].[ExportPosts]") .Map() - .CaptureOutput("exported", out DbCapture exported) + .CaptureOutput(out DbCapture exported, "exported") .ToPooledStream(cancellationToken); await foreach (PostRow row in rows) From 55f274e1815e07ebee7389106a428f4e0e9a28ec Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Wed, 2 Dec 2026 10:41:44 -0800 Subject: [PATCH 05/17] Captures always match over their own candidates A capture's name goes through the tiers over the candidates it carries, the name as written and, for a field prefix, the name without it, and never through the memo of the named outputs, which is keyed by the name and answers for one candidate. ExecuteOutputAsync's named forms and a definition's Output(name) keep that memo. Co-Authored-By: Claude Opus 5.5 --- Source/Core/OutputBinding.cs | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/Source/Core/OutputBinding.cs b/Source/Core/OutputBinding.cs index 41e438b5..bbcb55fd 100644 --- a/Source/Core/OutputBinding.cs +++ b/Source/Core/OutputBinding.cs @@ -158,17 +158,23 @@ public static void Resolve( string fix = OutputArguments.ExactNameFix(member.Form); - // One candidate, the name as given: remembered by that name. - if (member.Candidates.IsDefault) + // A named output or definition: one candidate, the name as given, + // remembered by that name. + if (member.Form != OutputForm.Capture) { return real.MatchName(member.Name, commandText, member.Display, fix); } - // Not NameSet.Match: its memo is keyed by the text of an argument - // expression, which AddParam shares, and its candidates include chain - // names. Not MatchName either: its memo answers for one candidate. + ImmutableArray candidates = member.Candidates.IsDefault + ? [DbQueryBinding.Bare(member.Name).ToString()] + : member.Candidates; + + // A capture: its own candidates. Not NameSet.Match: its memo is keyed by + // the text of an argument expression, which AddParam shares, and its + // candidates include chain names. Not MatchName either: its memo, keyed + // by the name, answers for one candidate. return ParameterNames.MatchBareAs( - member.Candidates, real.Names, real.BareNames, + candidates, real.Names, real.BareNames, member.Name, commandText, member.Display, fix); } From 21cf1e2675ea9425c8e97fd5147ccff936013060 Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Wed, 2 Dec 2026 10:43:28 -0800 Subject: [PATCH 06/17] Count only a test's own fault as unobserved; fix capture comments The unobserved-fault test listened to every unobserved task exception of the test run, so an unrelated test's exception failed it once. Its fault now names a unique procedure and only exceptions that carry that name are counted. It still fails if its own fault goes unobserved. The comments on captures now say that a query keeps only its own captures and a run combines them with the command's current ones, the command's first; a query from a definition has no command. Co-Authored-By: Claude Sonnet 5.5 --- Source/Core/Capture.cs | 9 +++++---- Source/Core/MappedQuery.Capture.cs | 12 +++++++----- .../CaptureDefinitionLocalDbTests.cs | 17 +++++++++++++++-- 3 files changed, 27 insertions(+), 11 deletions(-) diff --git a/Source/Core/Capture.cs b/Source/Core/Capture.cs index a301c80b..2f6e0c07 100644 --- a/Source/Core/Capture.cs +++ b/Source/Core/Capture.cs @@ -5,10 +5,11 @@ namespace Open.Database.Extensions; // // A capture call makes one source (a TaskCompletionSource the run completes) // and attaches it to the chain as a new, immutable CaptureSet: the sources so -// far plus the new one, appended. The command holds its set in one field; a -// mapped query holds its own in MappedQueryCore, and a query without one runs -// on its command, which uses the command's set: Map() shares the command's -// capture, and the first run by either route takes it. +// far plus the new one. The command holds its set in one field; a mapped +// query keeps only its own in MappedQueryCore, and a run combines them with +// the command's current set, the command's first. A query without its own runs +// on its command's set: Map() shares the command's capture, and the first +// run by either route takes it. A query from a definition has no command. // // The claim (the arm) is a compare-exchange on the set's first source. A set // only ever grows at its end, so two chain values that share a capture share diff --git a/Source/Core/MappedQuery.Capture.cs b/Source/Core/MappedQuery.Capture.cs index 78eb63e5..8a49516f 100644 --- a/Source/Core/MappedQuery.Capture.cs +++ b/Source/Core/MappedQuery.Capture.cs @@ -1,10 +1,12 @@ namespace Open.Database.Extensions; -// The captures of a mapped query (see Capture.cs). A query holds its own -// captures in MappedQueryCore, appended to its command's; a query without its -// own runs on its command, which fills the command's. Every builder carries -// them, and they are part of the equality by reference. The async run hands -// them to the command (ICaptureRunner); a synchronous run refuses them. +// The captures of a mapped query (see Capture.cs). A query keeps only its own +// captures in MappedQueryCore; a run combines them with the command's current +// ones, the command's first. A query without its own runs on its command, +// which fills the command's; a query from a definition has no command and +// fills only its own. Every builder carries them, and they are part of the +// equality by reference. The async run hands them to the command +// (ICaptureRunner); a synchronous run refuses them. readonly partial struct MappedQueryCore { /// diff --git a/Tests/Open.Database.Extensions.Core.Tests/CaptureDefinitionLocalDbTests.cs b/Tests/Open.Database.Extensions.Core.Tests/CaptureDefinitionLocalDbTests.cs index 9bed76f7..bd7b2139 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/CaptureDefinitionLocalDbTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/CaptureDefinitionLocalDbTests.cs @@ -430,14 +430,27 @@ public static async Task AnAwaitedFault_IsNotReportedAsUnobserved() { LocalDbFixture.SkipUnlessAvailable(); await using SqlConnection connection = await OpenAsync(); + // The fault names this procedure: an unobserved exception of any + // other test is not counted. + string missing = $"ode_cd_missing_{Guid.NewGuid():N}"; var unobserved = new List(); void Handler(object? sender, UnobservedTaskExceptionEventArgs e) - => unobserved.Add(e.Exception); + { + if (!e.Exception.ToString().Contains(missing, StringComparison.Ordinal)) + { + return; + } + + lock (unobserved) + { + unobserved.Add(e.Exception); + } + } TaskScheduler.UnobservedTaskException += Handler; try { MappedQuery query = DbQuery - .Procedure("dbo.ode_cd_missing") + .Procedure("dbo." + missing) .Map() .Using(connection) .CaptureOutput(out DbCapture page); From 02a05ac5b119bdd950e4343aec0eb9618af6c48a Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Wed, 2 Dec 2026 10:51:51 -0800 Subject: [PATCH 07/17] Show outputs and captures on stored definitions first The output samples now lead with the definition form: a static readonly definition, then per call Using, the parameters and the capture. The ad hoc command form follows each one. New samples cover typed values with outputs, the return code of a definition, a model capture, a write and a scalar with captures, a pooled stream, and the ways a capture takes its name. The samples run against procedures created in tempdb when LocalDB is available, and Program.cs checks what they return. The expressive commands article, the release notes and the what's new page describe definitions that declare and read outputs, and captures on the calls of a stored definition. Co-Authored-By: Claude Sonnet 5.5 --- docsite/articles/expressive-commands.md | 56 +++- docsite/articles/release-notes.md | 4 +- docsite/articles/whats-new-11.md | 2 + docsite/samples/OutputParameters.cs | 302 +++++++++++++++++-- docsite/samples/OutputParametersSqlServer.cs | 112 +++++++ docsite/samples/Program.cs | 52 ++++ 6 files changed, 499 insertions(+), 29 deletions(-) create mode 100644 docsite/samples/OutputParametersSqlServer.cs diff --git a/docsite/articles/expressive-commands.md b/docsite/articles/expressive-commands.md index 76e023c7..f095ff3c 100644 --- a/docsite/articles/expressive-commands.md +++ b/docsite/articles/expressive-commands.md @@ -78,7 +78,7 @@ A write is a `DbNonQuery`, made with `Text` or `Procedure` and run with `Execute [!code-csharp[](../samples/WritesAndScalars.cs#writes_and_scalars)] -Both take the same sources as a query, and their values before or after `Using`; `Params()` declares typed values. Set a timeout with `SetTimeout` on a `DbNonQuery`, or on the `DbQuery` before `Scalar()`. Output and return parameters are not supported here: use a command for them (see [Return values and output parameters](#return-values-and-output-parameters)). +Both take the same sources as a query, and their values before or after `Using`; `Params()` declares typed values. Set a timeout with `SetTimeout` on a `DbNonQuery`, or on the `DbQuery` before `Scalar()`. A write that sets output parameters is a `DbNonQuery` too: `Output()` declares what it reads and `ExecuteReturnAsync()` reads a procedure's return code (see [Output parameters](#output-parameters)). `Output()` is on `DbNonQuery` (outputs without rows), `Scalar()` on `DbQuery`; a query that reads rows takes its outputs with a capture on each call (see [Output parameters beside rows](#output-parameters-beside-rows)). ## Building a command where you need it @@ -191,7 +191,11 @@ 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: +`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): + +[!code-csharp[](../samples/OutputParameters.cs#sql_server_output_def_return)] + +Ad hoc, on a command: [!code-csharp[](../samples/SqlServer.cs#sql_server_return)] @@ -201,7 +205,11 @@ A result set and the return value are readable on the chain; output parameters a ### Output parameters -`ExecuteOutputAsync()` runs the command and reads its output parameters, and its return code, into one model. Each member `Map()` would read is an output parameter, and the model is built by the same rules (records, constructors, `required`, conversions, `[NullPolicy]`): +A write that reads its outputs is declared once with `Output()` on a `DbNonQuery`, stored in a `static readonly` field; each call binds it with `Using`, adds its values and reads the outputs with `ExecuteOutputAsync()`. The outputs, and the return code, are read into one model. Each member `Map()` would read is an output parameter, and the model is built by the same rules (records, constructors, `required`, conversions, `[NullPolicy]`). The model is checked when the definition is declared, so a model that cannot be read fails there, not on the first call (in a static field, as the inner exception of a `TypeInitializationException`); a name is matched against the procedure's parameters when the call runs. + +[!code-csharp[](../samples/OutputParameters.cs#sql_server_output_def_model)] + +An ad hoc command does the same: `ExecuteOutputAsync()` runs the command and reads the model. [!code-csharp[](../samples/OutputParameters.cs#sql_server_output_model)] @@ -209,13 +217,23 @@ A result set and the return value are readable on the chain; output parameters a - **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]`. - **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. +- **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. One value, and a decimal with its precision and scale: +[!code-csharp[](../samples/OutputParameters.cs#sql_server_output_def_named)] + +Ad hoc, on a command: + [!code-csharp[](../samples/OutputParameters.cs#sql_server_output_named)] +Typed values (`Params()`) and `Output()` combine in either order: + +[!code-csharp[](../samples/OutputParameters.cs#sql_server_output_def_typed)] + +A `decimal` member declares its type in the model: + [!code-csharp[](../samples/OutputParameters.cs#sql_server_output_decimal)] There is no blocking form. Known limits: @@ -231,21 +249,41 @@ There is no blocking form. Known limits: ### Output parameters beside rows -`ExecuteOutputAsync` runs the command for its outputs alone. To read rows and outputs from one call, capture the outputs: `CaptureOutput` (a model, one value, or a `decimal` with its precision and scale, as `ExecuteOutputAsync` takes them), `CaptureOutputDecimal` and `CaptureReturn` give a `DbCapture` as an `out` argument, and the query's async terminal fills it. Await the capture after the terminal: +`ExecuteOutputAsync` and `Output()` read a write's outputs alone. To read rows and outputs from one call, capture the outputs on the call: `CaptureOutput` (a model, one value, or a `decimal` with its precision and scale, as `Output()` takes them), `CaptureOutputDecimal` and `CaptureReturn` give a `DbCapture` as an `out` argument, and the call's async terminal fills it. Await the capture after the terminal. + +The definition is declared once, in a `static readonly` field, and each call binds it with `Using`, adds its values, and then captures. A capture is per call, after `Using` and the parameters, and never on the stored definition: it is filled once, so a definition that held one could run only once. + +[!code-csharp[](../samples/OutputParameters.cs#sql_server_output_def_capture_list)] + +Ad hoc, a capture goes on a command, before `Map`: [!code-csharp[](../samples/OutputParameters.cs#sql_server_output_capture_list)] -A capture can go on the command, before `Map`; the query runs the command and fills it. The return code needs a stored procedure, which is checked when the command runs (its type can be set after the capture), not at the capture call: +A capture takes the name of its variable: `CaptureOutput(out DbCapture total)` reads the parameter `@total`, found by the four tiers a name is matched by (exactly, ignoring case, ignoring case and underscores, without a common prefix), so a variable `totalCount` finds `@total_count`. A local declared in the call, a local declared earlier and a field (`out this.total`) all name it. When the variable's name differs, pass the name last: `CaptureOutput(out DbCapture count, "total")`. A discard (`out _`), an element access (`out totals[0]`) and a null name derive no name, and throw with that fix. A capture of a model needs no name: its members name the parameters, as they do for `Output()`. The compiler fills the name from the variable in C# 10 and later; with an older language version, pass the name last. + +[!code-csharp[](../samples/OutputParameters.cs#sql_server_output_def_names)] + +Several outputs in one capture are a model: + +[!code-csharp[](../samples/OutputParameters.cs#sql_server_output_def_capture_model)] + +A write and a scalar capture the same way, and their terminal returns the rows affected, or the value, beside the outputs. A decimal takes its precision and scale: `CaptureOutput(out DbCapture total, 19, 4)`, or `CaptureOutputDecimal(out DbCapture total, 19, 4)` for a NULL. A call that already reads its outputs (`Output()`) takes no capture; it reads them itself. + +[!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: + +[!code-csharp[](../samples/OutputParameters.cs#sql_server_output_def_capture_return)] [!code-csharp[](../samples/OutputParameters.cs#sql_server_output_capture_return)] A stream fills its captures when the loop ends, and a `break` still fills them: the read is closed, not canceled, and closing it waits for the server to send the rest of the response. The stall timeout does not bound that wait, so a large or slow response keeps the loop's exit waiting; a token you passed (to the call, the enumerator or the command) still cancels the read, and the capture is then canceled. If a stream may stop early and you cannot wait, do not capture on it: read the outputs with `ExecuteOutputAsync`. Await the capture after the loop; awaiting it inside the loop throws, since the loop would wait on itself (`AsTask()` there hands it to code that runs later): -[!code-csharp[](../samples/OutputParameters.cs#sql_server_output_capture_stream)] +[!code-csharp[](../samples/OutputParameters.cs#sql_server_output_def_capture_stream)] -The recommended form for a query is the definition: `static readonly MappedDbQuery X = DbQuery.Procedure("…").Map();`, then `X.Using(factory).AddParam(…)` and the terminal per call (see [Map the definition too](#map-the-definition-too)). A query made from a definition does not take a capture, so these samples use the ad hoc form. A capture is per call: it goes after the parameters, never on a stored definition. +[!code-csharp[](../samples/OutputParameters.cs#sql_server_output_capture_stream)] -- **Once.** A command or query that carries a capture runs once: a second run throws, and needs a new capture. A query made by `Map` shares the command's capture: the first run, by either route, fills it. +- **Once.** A command, a query or a bound call that carries a capture runs once: a second run throws, and needs a new capture. A query made by `Map` shares the command's capture: the first run, by either route, fills it. - **Async only.** A synchronous terminal, `ExecuteAsync(command => ...)`, `CancelOnEarlyStop()` and `ExecuteOutputAsync` beside a capture throw `InvalidOperationException`; so does `ExecuteReturnAsync` beside `CaptureReturn`. - **Checked at the call.** A type that cannot be read and two captures of one output (the same name twice, or a model beside another capture) throw at the capture call, before anything runs; a command capture added after a query was made from it, and conflicting with the query's own, throws when the terminal or stream is called. A run fills every capture its command has when it starts, a later one included; a stream or buffer takes them when it is made. - **Not on a command that re-implements `IExecuteReader`.** A capture reads through the library's reader, which such a command replaces, so it is refused: a capture on the query throws `NotSupportedException` at the call, and one on the command is refused when a mapped query over it runs, with `InvalidOperationException`, before anything executes; the command's own terminals do not use the re-implemented reader. Read the outputs with `ExecuteOutputAsync` instead. diff --git a/docsite/articles/release-notes.md b/docsite/articles/release-notes.md index 12d4c983..73ccf227 100644 --- a/docsite/articles/release-notes.md +++ b/docsite/articles/release-notes.md @@ -11,7 +11,9 @@ Version 11 is `11.0.0-rc.16`. For moving a 10.x codebase, read [Coming from earl - **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. - **Read output parameters: `ExecuteOutputAsync()`.** It maps a command's output parameters and return code into a model by name, with the `Map()` rules; `ExecuteOutputAsync(name)` reads one value, and `CaptureOutput(out DbCapture value, name)` captures one; a name finds its parameter the way `AddParam`'s name does (exactly, else ignoring case, else ignoring case and underscores, else without a common prefix such as `p_`), so `"totalCount"` finds `@total_count`. A `decimal` declares its SQL type: `[Column(TypeName = "decimal(p,s)")]` on a member, or `ExecuteOutputAsync(name, precision, scale)` (`ExecuteOutputDecimalAsync`) for one value. See [Output parameters](expressive-commands.md#output-parameters). -- **New: captures, output parameters beside rows.** `CaptureOutput` (a model, one value, or a `decimal` with its precision and scale), `CaptureOutputDecimal` and `CaptureReturn` on an expressive command, a mapped query and its `Skip` and `Take` views give a `DbCapture` as an `out` argument; the async terminal fills it, and a stream fills it when its loop ends, a `break` included. A capture runs once and needs an async terminal; a query's run fills the captures its command has when the run starts, including one added after `Map`. Misuse throws at the call, except that the return code of a command that is not a stored procedure is refused when the run starts: `NotSupportedException` on a query made from a definition or one that does not read from an expressive command, `InvalidOperationException` otherwise. A command whose type re-implements `IExecuteReader` is refused too, as `NotSupportedException` on a query capture and `InvalidOperationException` when a command capture runs. See [Output parameters beside rows](expressive-commands.md#output-parameters-beside-rows). +- **New: captures, output parameters beside rows.** `CaptureOutput` (a model, one value, or a `decimal` with its precision and scale), `CaptureOutputDecimal` and `CaptureReturn` on an expressive command, a mapped query and its `Skip` and `Take` views give a `DbCapture` as an `out` argument; the async terminal fills it, and a stream fills it when its loop ends, a `break` included. A capture runs once and needs an async terminal; a query's run fills the captures its command has when the run starts, including one added after `Map`. Misuse throws at the call, except that the return code of a command that is not a stored procedure is refused when the run starts: `NotSupportedException` on a query that does not read from an expressive command, `InvalidOperationException` otherwise. A command whose type re-implements `IExecuteReader` is refused too, as `NotSupportedException` on a query capture and `InvalidOperationException` when a command capture runs. See [Output parameters beside rows](expressive-commands.md#output-parameters-beside-rows). +- **New: definitions declare and read outputs.** `DbNonQuery.Procedure(name).Output()` declares that a write reads its output parameters and return code into a model; `Output(name)`, `Output(name, precision, scale)` and `OutputDecimal(name, precision, scale)` read one value. A bound call reads it with `ExecuteOutputAsync()`, and `ExecuteReturnAsync()` reads a stored procedure's return code. The model is checked when the definition is declared; `Params()` combines with `Output` in either order. See [Output parameters](expressive-commands.md#output-parameters). +- **New: captures on the calls of a stored definition.** `CaptureOutput`, `CaptureOutputDecimal` and `CaptureReturn` go on the call that `Using` and `AddParam` make from a definition: a mapped query, a write or a scalar. A capture is per call, never on the stored definition. It takes the name of its variable, as in `CaptureOutput(out DbCapture total)`, with the name passed last when it differs. See [Output parameters beside rows](expressive-commands.md#output-parameters-beside-rows). - **New: `ToArrayAsync` and `ToImmutableArrayAsync` on a `DbDataReader`.** Like `ToListAsync(transform)`, they read the remaining rows of the current result set through an asynchronous transform into pooled chunks and copy them once, into an array of exactly their number; on .NET 8 and later the immutable array wraps that array and does not copy it again (on .NET Standard it is a copy). - **Changed: the collecting terminals clear their value rows when no pool is offered.** `ToList`, `ToArray`, `ToImmutableArray`, `ToHashSet` and the dictionaries, asynchronous and synchronous, on a view or on a `DbDataReader`, copy their rows out and never show their pooled arrays, so they hide their pooling: a query that does not call `UsePool` now always clears the used rows of those arrays before they go back, plain value rows included, whatever the `Open.Database.Extensions.ClearPooledArrays` switch says. `UsePool(pool, clearOnReturn)` is followed as before, so `clearOnReturn: false` still keeps the rows. Rows that hold references were always cleared. The buffers and streams are unchanged: their default is still not to clear value rows. A chunk of 128 KB or more is cleared in the background, as before, and the allocation of a call is the same. - **Changed: the synchronous `ToList()` reads into pooled chunks, as `ToListAsync` does.** On a view or a reader it grew a list of its own, and so allocated the growth as well as the result and rented no pooled array; it now reads into the chain of pooled arrays and copies the rows once into a list of exactly their number, so the copy-out clearing above applies to it too. The growth is gone: 100,000 `int` rows allocate about 400 KB instead of about 1.05 MB, and 1,000 rows about 28.8 KB instead of 33.2 KB. diff --git a/docsite/articles/whats-new-11.md b/docsite/articles/whats-new-11.md index 1cb8c723..2ffad3ae 100644 --- a/docsite/articles/whats-new-11.md +++ b/docsite/articles/whats-new-11.md @@ -132,6 +132,8 @@ The blocking calls (`Execute`, `ExecuteNonQuery`, `ExecuteScalar`, `ExecuteReade - **No direction on the chain.** `AddParam`, `AddParamIf` and `AddReturnParam` no longer take a `ParameterDirection`, so a parameter added on the chain is an input; `AddReturnParam` is gone. Calls that never passed a direction compile unchanged; `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`. To set a direction, use `ExecuteAsync(command => ...)` with the raw `AddParameter`, `AddParameterType` and `AddReturnParameter` extensions. `Param` has no `direction` constructor parameter and no `Direction` property. - **Output parameters into a model.** `ExecuteOutputAsync()` reads a command's output parameters and return code into a model by name (`ExecuteOutputAsync(name)` for one value): see [Output parameters](expressive-commands.md#output-parameters). - **Output parameters beside rows.** `CaptureOutput`, `CaptureOutputDecimal` and `CaptureReturn` on a command or a mapped query give a `DbCapture` that the async terminal fills, so one call returns rows and outputs: see [Output parameters beside rows](expressive-commands.md#output-parameters-beside-rows). +- **Definitions declare and read outputs.** `DbNonQuery.Procedure(name).Output()` declares what a write reads; a bound call reads it with `ExecuteOutputAsync()`, and `ExecuteReturnAsync()` reads a stored procedure's return code: see [Output parameters](expressive-commands.md#output-parameters). +- **Captures on the calls of a stored definition.** `CaptureOutput`, `CaptureOutputDecimal` and `CaptureReturn` go on the call made with `Using` and `AddParam`, never on the stored definition; the name of the variable names the capture, and a name passed last is used when it differs: see [Output parameters beside rows](expressive-commands.md#output-parameters-beside-rows). See [Parameters](expressive-commands.md#name-a-parameter-from-its-argument). diff --git a/docsite/samples/OutputParameters.cs b/docsite/samples/OutputParameters.cs index 4849dc95..174df115 100644 --- a/docsite/samples/OutputParameters.cs +++ b/docsite/samples/OutputParameters.cs @@ -4,19 +4,40 @@ namespace Samples; -// Compile-only: this needs a SQL Server, so Program.cs never calls it. +// The SQL Server procedures these samples call are created in tempdb by +// OutputParametersSqlServer, and Program.cs runs the samples against them +// when LocalDB is available; Blog is the factory it points at them. public static class OutputParameters { - static readonly SqlConnectionFactory Blog = new(@"Server=(localdb)\MSSQLLocalDB;Database=Blog;Integrated Security=true"); + public static SqlConnectionFactory Blog { get; set; } + = new(@"Server=(localdb)\MSSQLLocalDB;Database=Blog;Integrated Security=true"); - #region sql_server_output_model + #region sql_server_output_def_model // The procedure declares @id and @created_utc as OUTPUT and ends with a RETURN code. // ReturnValue reads the return code; every other member is an output parameter. public record AddPostResult(int Id, DateTime CreatedUtc, int ReturnValue); + // Declared once. The model is checked here, not on the first call. + static readonly OutputDbNonQuery AddPost + = DbNonQuery.Procedure("[dbo].[AddPost]").Output(); + public static async Task Model( string title, CancellationToken cancellationToken) + { + AddPostResult created = await AddPost.Using(Blog) + .AddParam(title) + .ExecuteOutputAsync(cancellationToken); + + return created; + } + #endregion + + // The same call ad hoc: nothing declared, the command built where it runs. + #region sql_server_output_model + public static async Task ModelAdHoc( + string title, + CancellationToken cancellationToken) { AddPostResult created = await Blog .StoredProcedure("[dbo].[AddPost]") @@ -27,7 +48,41 @@ public static async Task Model( } #endregion - public static async Task Named( + #region sql_server_output_def_named + // One output parameter, read by its name. A name finds its parameter as + // AddParam's does, so "total" finds @total and "postId" finds @post_id. + static readonly OutputDbNonQuery AddPostId + = DbNonQuery.Procedure("[dbo].[AddPost]").Output("id"); + + // One decimal output needs its precision and scale; OutputDecimal gives + // a decimal? for a procedure that can set the output to NULL. + static readonly OutputDbNonQuery PostsTotal + = DbNonQuery.Procedure("[dbo].[CountPosts]") + .Output("total", 19, 4); + + static readonly OutputDbNonQuery MaybePostsTotal + = DbNonQuery.Procedure("[dbo].[CountPosts]") + .OutputDecimal("total", 19, 4); + + public static async Task<(int Id, decimal Total, decimal? Maybe)> Named( + string title, + CancellationToken cancellationToken) + { + int id = await AddPostId.Using(Blog) + .AddParam(title) + .ExecuteOutputAsync(cancellationToken); + + decimal total = await PostsTotal.Using(Blog) + .ExecuteOutputAsync(cancellationToken); + + decimal? maybe = await MaybePostsTotal.Using(Blog) + .ExecuteOutputAsync(cancellationToken); + + return (id, total, maybe); + } + #endregion + + public static async Task<(int Id, decimal Total, decimal? Maybe)> NamedAdHoc( string title, CancellationToken cancellationToken) { @@ -49,10 +104,7 @@ public static async Task Named( .ExecuteOutputDecimalAsync("total", 19, 4, cancellationToken); #endregion - _ = total; - _ = maybe; - - return id; + return (id, total, maybe); } #region sql_server_output_decimal @@ -61,43 +113,146 @@ public record Totals( int Count, [property: Column(TypeName = "decimal(19,4)")] decimal Total); + static readonly OutputDbNonQuery CountPosts + = DbNonQuery.Procedure("[dbo].[CountPosts]").Output(); + public static async Task Decimals( CancellationToken cancellationToken) { - Totals totals = await Blog - .StoredProcedure("[dbo].[CountPosts]") - .ExecuteOutputAsync(cancellationToken); + Totals totals = await CountPosts.Using(Blog) + .ExecuteOutputAsync(cancellationToken); return totals; } #endregion - #region sql_server_output_capture_list + #region sql_server_output_def_typed + public readonly record struct NewPost(string Title); + + // Typed values and outputs, in either order: Output() + // then Params() declares the same definition. + static readonly OutputDbNonQuery AddTypedPost + = DbNonQuery.Procedure("[dbo].[AddPost]") + .Params() + .Output(); + + public static async Task Typed( + string title, + CancellationToken cancellationToken) + { + AddPostResult created = await AddTypedPost.Using(Blog) + .AddParams(new NewPost(title)) + .ExecuteOutputAsync(cancellationToken); + + return created; + } + #endregion + + #region sql_server_output_def_return + // A stored procedure's RETURN code, read as the call's result. + static readonly DbNonQuery DeletePost + = DbNonQuery.Procedure("[dbo].[DeletePost]"); + + public static async Task Delete( + int id, + CancellationToken cancellationToken) + { + int code = await DeletePost.Using(Blog) + .AddParam(id) + .ExecuteReturnAsync(cancellationToken); + + return code; + } + #endregion + + #region sql_server_output_def_capture_list public record PostRow(int Id, string Title); public record PostPage(List Rows, int Total); // A page of posts, and the total the procedure sets as an OUTPUT. + static readonly MappedDbQuery PagePosts = DbQuery.Procedure("[dbo].[PagePosts]") + .Map(); + public static async Task Page( int page, CancellationToken cancellationToken) + { + // The capture is per call: after Using and the parameters, never on + // the stored definition. + List rows = await PagePosts.Using(Blog) + .AddParam(page) + .CaptureOutput(out DbCapture total) + .ToListAsync(cancellationToken); + + // Filled by the time the terminal's task completes: await it after. + return new PostPage(rows, await total); + } + #endregion + + #region sql_server_output_capture_list + public static async Task PageAdHoc( + int page, + CancellationToken cancellationToken) { List rows = await Blog .StoredProcedure("[dbo].[PagePosts]") .AddParam(page) .Map() - .CaptureOutput(out DbCapture total, "total") + .CaptureOutput(out DbCapture total) .ToListAsync(cancellationToken); - // Filled by the time the terminal's task completes: await it after. return new PostPage(rows, await total); } #endregion - #region sql_server_output_capture_return + #region sql_server_output_def_capture_model + // Several outputs in one capture: a model, read as ExecuteOutputAsync reads + // it. Its members name the parameters, so the variable's name is not used. + public record PageInfo(int Total, int Pages); + + public static async Task<(List Rows, PageInfo Info)> PageWithInfo( + int page, + CancellationToken cancellationToken) + { + List rows = await PagePosts.Using(Blog) + .AddParam(page) + .CaptureOutput(out DbCapture info) + .ToListAsync(cancellationToken); + + return (rows, await info); + } + #endregion + + #region sql_server_output_def_capture_return + static readonly MappedDbQuery ArchivePosts + = DbQuery.Procedure("[dbo].[ArchivePosts]").Map(); + public static async Task> Archive( DateTime before, CancellationToken cancellationToken) + { + // The return code is read beside the rows. + List archived = await ArchivePosts.Using(Blog) + .AddParam(before) + .CaptureReturn(out DbCapture status) + .ToListAsync(cancellationToken); + + int code = await status; + if (code != 0) + { + throw new InvalidOperationException( + $"ArchivePosts returned {code}."); + } + + return archived; + } + #endregion + + #region sql_server_output_capture_return + public static async Task> ArchiveAdHoc( + DateTime before, + CancellationToken cancellationToken) { // On the command: the query Map makes runs it, and fills it. List archived = await Blog @@ -118,15 +273,72 @@ public static async Task> Archive( } #endregion - #region sql_server_output_capture_stream + #region sql_server_output_def_capture_write + // A write returns its rows affected, and the outputs beside them. + static readonly DbNonQuery InsertPost + = DbNonQuery.Procedure("[dbo].[AddPost]"); + + // A scalar returns its value, and the outputs beside it. + static readonly ScalarDbQuery PostCount + = DbQuery.Procedure("[dbo].[CountPosts]").Scalar(); + + public static async Task<(int Rows, int Id)> Insert( + string title, + CancellationToken cancellationToken) + { + int rows = await InsertPost.Using(Blog) + .AddParam(title) + .CaptureOutput(out DbCapture id) + .ExecuteNonQueryAsync(cancellationToken); + + return (rows, await id); + } + + public static async Task<(int Count, decimal Total)> Count( + CancellationToken cancellationToken) + { + int count = await PostCount.Using(Blog) + .CaptureOutput(out DbCapture total, 19, 4) + .ExecuteScalarAsync(cancellationToken); + + return (count, await total); + } + #endregion + + #region sql_server_output_def_capture_stream + static readonly MappedDbQuery ExportPosts + = DbQuery.Procedure("[dbo].[ExportPosts]").Map(); + public static async Task Export( TextWriter writer, CancellationToken cancellationToken) + { + IAsyncEnumerable rows = ExportPosts.Using(Blog) + .CaptureOutput(out DbCapture exported) + .ToPooledStream(cancellationToken); + + await foreach (PostRow row in rows) + { + await writer.WriteLineAsync( + row.Title.AsMemory(), + cancellationToken); + } + + // Complete once the loop has ended, a break included: await it + // after the loop, never inside it. + return await exported; + } + #endregion + + #region sql_server_output_capture_stream + public static async Task ExportAdHoc( + TextWriter writer, + CancellationToken cancellationToken) { IAsyncEnumerable rows = Blog .StoredProcedure("[dbo].[ExportPosts]") .Map() - .CaptureOutput(out DbCapture exported, "exported") + .CaptureOutput(out DbCapture exported) .ToPooledStream(cancellationToken); await foreach (PostRow row in rows) @@ -136,12 +348,64 @@ await writer.WriteLineAsync( cancellationToken); } - // Complete once the loop has ended, a break included: await it - // after the loop, never inside it. return await exported; } #endregion + #region sql_server_output_def_names + // A capture is named after its variable: out DbCapture total finds + // @total, by the same four tiers as AddParam, so totalCount finds + // @total_count too. + public sealed class PagePager + { + // A field: the last identifier, _total, finds @total as total does. + DbCapture _total; + + public async Task PageAsync( + int page, + CancellationToken cancellationToken) + { + await PagePosts.Using(Blog) + .AddParam(page) + .CaptureOutput(out this._total) + .ToListAsync(cancellationToken); + + return await this._total; + } + } + + public static async Task Names( + int page, + CancellationToken cancellationToken) + { + // A local declared in the call: the usual form. + await PagePosts.Using(Blog) + .AddParam(page) + .CaptureOutput(out DbCapture total) + .ToListAsync(cancellationToken); + int first = await total; + + // A local that exists already. + await PagePosts.Using(Blog) + .AddParam(page) + .CaptureOutput(out total) + .ToListAsync(cancellationToken); + int second = await total; + + // A name passed last, when the variable's name differs. + await PagePosts.Using(Blog) + .AddParam(page) + .CaptureOutput(out DbCapture count, "total") + .ToListAsync(cancellationToken); + + // Refused, naming the fix: a discard (out _), an element access + // (out totals[0]) or a null name derives no name; pass it last, + // CaptureOutput(out DbCapture x, "total"). A model (above) never + // needs one: its members name the parameters. + return first + second + await count; + } + #endregion + public static async Task Raw( string title, CancellationToken cancellationToken) diff --git a/docsite/samples/OutputParametersSqlServer.cs b/docsite/samples/OutputParametersSqlServer.cs new file mode 100644 index 00000000..c63ffb0c --- /dev/null +++ b/docsite/samples/OutputParametersSqlServer.cs @@ -0,0 +1,112 @@ +using Microsoft.Data.SqlClient; + +namespace Samples; + +// The SQL Server side of OutputParameters: the procedures its samples call, +// created in tempdb and dropped when the scope is disposed. Program.cs calls +// TryStartAsync after LittleCodeSqlServer has shown that LocalDB can be reached. +public sealed class OutputParametersSqlServer : IAsyncDisposable +{ + static readonly string[] Names = + [ + "AddPost", "CountPosts", "PagePosts", "ArchivePosts", "ExportPosts", "DeletePost", + ]; + + OutputParametersSqlServer() { } + + public static async Task StartAsync( + CancellationToken cancellationToken) + { + await ExecuteAsync(DropAll, cancellationToken); + + await ExecuteAsync( + """ + create procedure dbo.AddPost + @title nvarchar(100), + @id int = null output, + @created_utc datetime2 = null output + as + set @id = 7; + set @created_utc = '2026-01-02T03:04:05'; + return 3; + """, + cancellationToken); + + await ExecuteAsync( + """ + create procedure dbo.CountPosts + @count int = null output, + @total decimal(19,4) = null output + as + set @count = 3; + set @total = 12.5; + select 3; + """, + cancellationToken); + + await ExecuteAsync( + """ + create procedure dbo.PagePosts + @page int, + @total int = null output, + @pages int = null output + as + set @total = 42; + set @pages = 5; + select 1 as Id, N'One' as Title + union all + select 2, N'Two'; + """, + cancellationToken); + + await ExecuteAsync( + """ + create procedure dbo.ArchivePosts + @before datetime2 + as + select 1 as Id, N'One' as Title; + return 0; + """, + cancellationToken); + + await ExecuteAsync( + """ + create procedure dbo.ExportPosts + @exported int output + as + set @exported = 2; + select 1 as Id, N'One' as Title + union all + select 2, N'Two'; + """, + cancellationToken); + + await ExecuteAsync( + """ + create procedure dbo.DeletePost + @id int + as + return 1; + """, + cancellationToken); + + return new OutputParametersSqlServer(); + } + + public ValueTask DisposeAsync() + => new(ExecuteAsync(DropAll, CancellationToken.None)); + + static string DropAll + => string.Concat(Names.Select(static name => $"drop procedure if exists dbo.{name}; ")); + + static async Task ExecuteAsync( + string sql, + CancellationToken cancellationToken) + { + await using var connection = new SqlConnection(LittleCodeSqlServer.ConnectionString); + await connection.OpenAsync(cancellationToken); + await using var command = connection.CreateCommand(); + command.CommandText = sql; + await command.ExecuteNonQueryAsync(cancellationToken); + } +} diff --git a/docsite/samples/Program.cs b/docsite/samples/Program.cs index a0f2d999..5028a98d 100644 --- a/docsite/samples/Program.cs +++ b/docsite/samples/Program.cs @@ -606,6 +606,58 @@ await ThrowsAsync(() => HowLittleCode.CollectAsync(od && HowLittleCode.Fingerprint(await HowLittleCode.SearchPostsEfAsync(serverEf, searchAuthor, searchTitle, littleCodeToken)) == expectedSearch && HowLittleCode.Fingerprint(await HowLittleCode.SearchPostsAdoAsync(serverConnectionString, searchAuthor, searchTitle, littleCodeToken)) == expectedSearch, "how little code, task 4 (SQL Server): the stored procedure with two parameters returns the same row in all four"); + + // Output parameters: each sample runs against procedures created in tempdb. + OutputParameters.Blog = new SqlConnectionFactory(serverConnectionString); + await using OutputParametersSqlServer outputProcedures = await OutputParametersSqlServer.StartAsync(littleCodeToken); + var createdAt = new DateTime(2026, 1, 2, 3, 4, 5); + var addPostResult = new OutputParameters.AddPostResult(7, createdAt, 3); + Check( + await OutputParameters.Model("T", littleCodeToken) == addPostResult + && await OutputParameters.ModelAdHoc("T", littleCodeToken) == addPostResult + && await OutputParameters.Typed("T", littleCodeToken) == addPostResult, + "output parameters: a stored definition, an ad hoc command and typed values read the same model"); + Check( + await OutputParameters.Named("T", littleCodeToken) == (7, 12.5m, 12.5m) + && await OutputParameters.NamedAdHoc("T", littleCodeToken) == (7, 12.5m, 12.5m), + "output parameters: one value, a decimal and a nullable decimal are read by name, on a definition and ad hoc"); + Check( + await OutputParameters.Decimals(littleCodeToken) == new OutputParameters.Totals(3, 12.5m), + "output parameters: a decimal member declares its type with Column"); + Check( + await OutputParameters.Delete(1, littleCodeToken) == 1, + "output parameters: a definition reads the return code with ExecuteReturnAsync"); + OutputParameters.PostPage definitionPage = await OutputParameters.Page(1, littleCodeToken); + OutputParameters.PostPage adHocPage = await OutputParameters.PageAdHoc(1, littleCodeToken); + Check( + definitionPage.Total == 42 && adHocPage.Total == 42 + && definitionPage.Rows.Select(static row => row.Id).SequenceEqual([1, 2]) + && adHocPage.Rows.Select(static row => row.Id).SequenceEqual([1, 2]), + "output parameters: a capture on a call of a stored definition and on an ad hoc command give the rows and the output"); + (List infoRows, OutputParameters.PageInfo info) = await OutputParameters.PageWithInfo(1, littleCodeToken); + Check( + infoRows.Count == 2 && info == new OutputParameters.PageInfo(42, 5), + "output parameters: a model capture reads several outputs beside the rows"); + Check( + (await OutputParameters.Archive(createdAt, littleCodeToken)).Count == 1 + && (await OutputParameters.ArchiveAdHoc(createdAt, littleCodeToken)).Count == 1, + "output parameters: CaptureReturn reads the return code beside the rows, on a definition and ad hoc"); + Check( + await OutputParameters.Insert("T", littleCodeToken) == (-1, 7), + "output parameters: a captured write on a definition gives its rows affected and the output"); + Check( + await OutputParameters.Count(littleCodeToken) == (3, 12.5m), + "output parameters: a captured scalar on a definition gives its value and the output"); + Check( + await OutputParameters.Names(1, littleCodeToken) == 126 + && await new OutputParameters.PagePager().PageAsync(1, littleCodeToken) == 42, + "output parameters: a capture is named by a declared local, an earlier local, a field or a name passed last"); + using StringWriter exported = new(); + Check( + await OutputParameters.Export(exported, littleCodeToken) == 2 + && await OutputParameters.ExportAdHoc(exported, littleCodeToken) == 2 + && exported.ToString().Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries).SequenceEqual(["One", "Two", "One", "Two"]), + "output parameters: a capture on a stream is filled when the loop ends, on a definition and ad hoc"); } } From 36fa94de9e33a1a5068a091f820c4ec7c6e8b8e7 Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Wed, 2 Dec 2026 10:54:05 -0800 Subject: [PATCH 08/17] Test captures through a definition on channels and blocks A query made from a stored definition now has tests that its capture is filled when a Channel reader, a bounded Channel reader, a source block or a target block finishes its pass. A capture added before or after a parameter on a bound write gives the same call, and a named output called ReturnValue reads the declared parameter, not the return code. Co-Authored-By: Claude Sonnet 5.5 --- .../CaptureDefinitionLocalDbTests.cs | 96 +++++++++++++++++++ .../OutputDefinitionTests.cs | 17 ++++ 2 files changed, 113 insertions(+) diff --git a/Tests/Open.Database.Extensions.Core.Tests/CaptureDefinitionLocalDbTests.cs b/Tests/Open.Database.Extensions.Core.Tests/CaptureDefinitionLocalDbTests.cs index bd7b2139..46d19bb6 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/CaptureDefinitionLocalDbTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/CaptureDefinitionLocalDbTests.cs @@ -1,5 +1,6 @@ using Microsoft.Data.SqlClient; using System.ComponentModel.DataAnnotations.Schema; +using System.Threading.Tasks.Dataflow; #nullable enable @@ -469,4 +470,99 @@ await Assert.ThrowsAnyAsync( Assert.Empty(unobserved); } + + [Fact] + public static async Task ACaptureBeforeOrAfterAddParam_OnABoundCall_IsTheSameCall() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = Procedure( + "@id int, @doubled int output", + "set @doubled = @id * 2;"); + await using SqlConnection connection = await OpenAsync(); + DbNonQuery write = DbNonQuery.Procedure("dbo." + procedure.Name); + + BoundCall before = write + .Using(connection) + .CaptureOutput(out DbCapture first, "doubled") + .AddParam("id", 2); + BoundCall after = write + .Using(connection) + .AddParam("id", 3) + .CaptureOutput(out DbCapture second, "doubled"); + + await before.ExecuteNonQueryAsync(Token); + await after.ExecuteNonQueryAsync(Token); + + Assert.Equal(4, await first); + Assert.Equal(6, await second); + } + + public static TheoryData ChannelAndBlockEntries + => new( + "ToChannelReader", + "ToBoundedChannelReader", + "AsSourceBlock", + "ToTargetBlock"); + + // The Channel and Dataflow terminals of a query from a definition fill a + // capture when their pass ends, as those of a command do. + [Theory] + [MemberData(nameof(ChannelAndBlockEntries))] + public static async Task AChannelOrABlock_FromADefinition_FillsTheCapture( + string entry) + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = PageProcedure(); + await using SqlConnection connection = await OpenAsync(); + MappedQuery query = Rows(procedure) + .Using(connection) + .CaptureOutput(out DbCapture page); + + var ids = new List(); + switch (entry) + { + case "ToChannelReader": + await foreach (Row row in query + .ToChannelReader(Token) + .ReadAllAsync(Token)) + { + ids.Add(row.Id); + } + + break; + case "ToBoundedChannelReader": + await foreach (Row row in query + .ToBoundedChannelReader(1, Token) + .ReadAllAsync(Token)) + { + ids.Add(row.Id); + } + + break; + case "AsSourceBlock": + IReceivableSourceBlock source = query.AsSourceBlock(Token); + while (await source.OutputAvailableAsync(Token)) + { + while (source.TryReceive(out Row? row)) + { + ids.Add(row.Id); + } + } + + await source.Completion; + break; + default: + var target = new BufferBlock(); + Assert.Equal(3, await query.ToTargetBlock(target, Token)); + if (target.TryReceiveAll(out IList? received)) + { + ids.AddRange(received.Select(static row => row.Id)); + } + + break; + } + + Assert.Equal([1, 2, 3], ids); + Assert.Equal(new Page(31, 3), await page); + } } diff --git a/Tests/Open.Database.Extensions.Core.Tests/OutputDefinitionTests.cs b/Tests/Open.Database.Extensions.Core.Tests/OutputDefinitionTests.cs index e8e49d03..2aea82cf 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/OutputDefinitionTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/OutputDefinitionTests.cs @@ -452,6 +452,23 @@ public static async Task TypedParams_AndOutput_WorkInEitherOrder() Assert.Equal(10, second); } + [Fact] + public static async Task ReturnValue_InTheNamedForm_NamesADeclaredParameter_NotTheReturnCode() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = Procedure( + "@ReturnValue int output", + "set @ReturnValue = 3; return 9;"); + await using SqlConnection connection = await OpenAsync(); + + int value = await Proc(procedure) + .Output("ReturnValue") + .Using(connection) + .ExecuteOutputAsync(Token); + + Assert.Equal(3, value); + } + [Fact] public static async Task AFailedOutputMatch_ForgetsTheNames_SoTheNextCallReadsThemAgain() { From 023224f2fb850a08eb1b03cdfb39dfac1eaf7c1e Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Wed, 2 Dec 2026 11:07:06 -0800 Subject: [PATCH 09/17] Fix review findings on output definitions and captures Correct two comments: the terminal throws when its own conversion fails while the captures keep the values already delivered, and the capture name cache holds one weak entry per distinct non-plain text. An empty typed capture name now gets a message for typed text, not the one about the compiler. A leading underscore is no longer a capture name candidate of its own; only m_ and s_ are stripped, and the matcher's underscore tier handles the rest. The doc line says the same. Add tests: a model capture beside ExecuteReturnAsync reads each value once (fake connection and SQL Server definition); a decimal shape with a non-decimal capture does not compile and infers DbCapture on a command and on a mapped query. Drop duplicate name rows, a repeated comment and a trailing blank line. Co-Authored-By: Claude Sonnet 5.5 --- Source/Core/BoundCall.cs | 2 -- Source/Core/CaptureNames.cs | 20 +++++++----- Source/Core/DbQueryRunner.Output.cs | 6 ++-- Source/Core/MappedQuery.Capture.cs | 1 - Source/Core/Output.docs.xml | 2 +- .../BoundCallCaptureCompileTests.cs | 31 +++++++++++++++++++ .../CaptureDefinitionLocalDbTests.cs | 18 +++++++++++ .../CaptureNameTests.cs | 30 ++++++++++++++---- .../CaptureTests.cs | 14 +++++++++ 9 files changed, 105 insertions(+), 19 deletions(-) diff --git a/Source/Core/BoundCall.cs b/Source/Core/BoundCall.cs index 72e249ff..89461c5b 100644 --- a/Source/Core/BoundCall.cs +++ b/Source/Core/BoundCall.cs @@ -185,8 +185,6 @@ public BoundCall Using( // DbQuery.Using throws ArgumentNullException for a null source. => Bind(Definition.Using(factory)); - // A call made here has no captures: a capture is added after Using, on the - // bound call. BoundCall Bind(DbQueryUsing root) => new(root.WithParams(_list)); } diff --git a/Source/Core/CaptureNames.cs b/Source/Core/CaptureNames.cs index 2daec6d2..3400facc 100644 --- a/Source/Core/CaptureNames.cs +++ b/Source/Core/CaptureNames.cs @@ -13,15 +13,17 @@ sealed class CaptureName(string name) /// /// Gets the names the capture is matched by, most specific first: the name - /// as written, then without a field prefix (m_total gives - /// total). The default value means only . + /// as written, then without an m_ or s_ prefix + /// (m_total gives total). A leading underscore is left to the + /// matcher's underscore tier. The default value means only + /// . /// public ImmutableArray Candidates { get; } = Prefixed(name); static ImmutableArray Prefixed(string name) { int prefix = ParameterNames.FieldPrefixLength(name, 0, name.Length); - return prefix == 0 + return prefix < 2 ? default : [name, name[prefix..]]; } @@ -35,9 +37,10 @@ static ImmutableArray Prefixed(string name) /// static class CaptureNames { - // Texts that are not one plain name are worked out once each: they are - // compile-time literals, so the table holds one entry per call site, and - // it does not keep them alive. A plain name has no entry. + // Texts that are not one plain name are worked out once each. The table + // holds one entry per distinct such text, weakly: an entry is released with + // its text, so a typed text built at runtime adds entries until it is + // collected. A plain name has no entry. static readonly ConditionalWeakTable Cache = new(); sealed class Parsed(CaptureName? name) @@ -123,11 +126,14 @@ static bool IsPlain(string text) "CA2208:Instantiate argument exceptions correctly")] static ArgumentException NoName(string? text) => new( - (string.IsNullOrWhiteSpace(text) + (text is null ? "The output parameter's name was not given: the compiler did " + "not supply the variable's name (that needs a C# 10 compiler " + "or newer, and a dynamic call gives none), or null was " + "passed. " + : string.IsNullOrWhiteSpace(text) + ? "The output parameter's name is empty: the name passed last " + + "has no characters. " : $"Cannot take the output parameter's name from '{text}': a " + "discard (_) and an element access (arr[0]) have no name. ") + "Declare a variable named after the parameter, or pass the name " diff --git a/Source/Core/DbQueryRunner.Output.cs b/Source/Core/DbQueryRunner.Output.cs index afafd300..138d9df9 100644 --- a/Source/Core/DbQueryRunner.Output.cs +++ b/Source/Core/DbQueryRunner.Output.cs @@ -213,8 +213,10 @@ static async ValueTask CapturedAsync( execute, (value, output) => { - // The conversion happens once, in each capture; its - // failure is the capture's, never the terminal's. + // The conversion of each capture happens once, there. The + // terminal's own conversion may still throw: the terminal + // throws, and the captures keep the values already + // delivered. run.Deliver(output); return convert(value, output); }, diff --git a/Source/Core/MappedQuery.Capture.cs b/Source/Core/MappedQuery.Capture.cs index 8a49516f..f7be7da2 100644 --- a/Source/Core/MappedQuery.Capture.cs +++ b/Source/Core/MappedQuery.Capture.cs @@ -347,4 +347,3 @@ public MappedQueryWithTake CaptureReturn( return captured; } } - diff --git a/Source/Core/Output.docs.xml b/Source/Core/Output.docs.xml index 85bc050f..2526b78b 100644 --- a/Source/Core/Output.docs.xml +++ b/Source/Core/Output.docs.xml @@ -158,7 +158,7 @@ is optional. A single value reads the parameter named after the variable (out DbCapture<int> total reads @total; the last identifier of out this.total or out state.total is total), or the name passed last (CaptureOutput(out DbCapture<int> x, "total")). One rule reads both: the last identifier, with a leading @ or : dropped; - a field prefix (m_, s_, _) is also tried without it. + a field prefix (m_ or s_) is also tried without it. A model maps by its members and ignores the name: it never derives or refuses one, and a member that matches no parameter says so in its message. Name the variable after the output parameter, or pass the name last; a variable named after an input parameter with a value is sent as , and a variable named after an input parameter without a default is refused by SQL Server (error 8162 for a procedure, diff --git a/Tests/Open.Database.Extensions.Core.Tests/BoundCallCaptureCompileTests.cs b/Tests/Open.Database.Extensions.Core.Tests/BoundCallCaptureCompileTests.cs index 2d13550a..32392900 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/BoundCallCaptureCompileTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/BoundCallCaptureCompileTests.cs @@ -144,4 +144,35 @@ public static void ACaptureOnACallMadeFromOutput_OrOnAScalarWithTheTypeArgument_ errors.All(static d => d.Id == "CS1929"), Show(errors)); } + + [Theory] + [InlineData("c.StoredProcedure(\"p\")")] + [InlineData("c.StoredProcedure(\"p\").Map()")] + public static void ADecimalShape_WithANonDecimalCapture_DoesNotCompile_OnACommandAndAMappedQuery( + string receiver) + { + Diagnostic[] errors = Errors( + "static void M(DbConnection c) { var call = " + receiver + + ".CaptureOutput(out DbCapture x, 19, 4); }"); + + Assert.NotEmpty(errors); + Assert.Contains(errors, static d => d.Severity == DiagnosticSeverity.Error); + Assert.True( + // Seen: no argument converts to the decimal form (CS1503). + errors.All(static d => d.Id == "CS1503"), + Show(errors)); + } + + [Theory] + [InlineData("c.StoredProcedure(\"p\")")] + [InlineData("c.StoredProcedure(\"p\").Map()")] + public static void ADecimalShape_InfersADecimalCapture_OnACommandAndAMappedQuery( + string receiver) + { + Diagnostic[] errors = Errors( + "static void M(DbConnection c) { var call = " + receiver + + ".CaptureOutput(out var x, 19, 4); DbCapture check = x; }"); + + Assert.True(errors.Length == 0, Show(errors)); + } } diff --git a/Tests/Open.Database.Extensions.Core.Tests/CaptureDefinitionLocalDbTests.cs b/Tests/Open.Database.Extensions.Core.Tests/CaptureDefinitionLocalDbTests.cs index 46d19bb6..e97a60cd 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/CaptureDefinitionLocalDbTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/CaptureDefinitionLocalDbTests.cs @@ -388,6 +388,24 @@ await DbNonQuery.Procedure("dbo." + procedure.Name) Assert.Equal(new WithCode(8, 3), await model); } + [Fact] + public static async Task ExecuteReturnAsync_BesideAModelCapture_OnADefinition_ReadsEachValueOnce() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = Procedure( + "@total int output, @pages int output", + "set @total = 8; set @pages = 5; return 3;"); + await using SqlConnection connection = await OpenAsync(); + + int code = await DbNonQuery.Procedure("dbo." + procedure.Name) + .Using(connection) + .CaptureOutput(out DbCapture model) + .ExecuteReturnAsync(Token); + + Assert.Equal(3, code); + Assert.Equal(new Page(8, 5), await model); + } + [Fact] public static void CaptureReturn_OnATextDefinition_ThrowsAtTheCaptureCall() { diff --git a/Tests/Open.Database.Extensions.Core.Tests/CaptureNameTests.cs b/Tests/Open.Database.Extensions.Core.Tests/CaptureNameTests.cs index c4900b2d..0d69550f 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/CaptureNameTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/CaptureNameTests.cs @@ -48,11 +48,6 @@ static void Contains(Exception ex, params string[] phrases) [InlineData("global::Open.Database.Extensions.DbCapture total", "total")] [InlineData("DbCapture\n\t\t\ttotal", "total")] [InlineData("DbCapture spaced", "spaced")] - [InlineData("total$", "total$")] - [InlineData("#rows", "#rows")] - [InlineData(":total", "total")] - [InlineData("@total", "total")] - [InlineData("dbo.total", "total")] [InlineData("total", "total")] public static void TheNameIsTheLastIdentifier_OrTheTypedValue( string text, @@ -79,7 +74,6 @@ public static void ANameThatCannotBeTaken_IsRefusedWithTheFix(string? text) [Theory] [InlineData("m_total", "m_total", "total")] [InlineData("s_total", "s_total", "total")] - [InlineData("_total", "_total", "total")] [InlineData("this.m_total", "m_total", "total")] public static void AFieldPrefix_IsAlsoTriedWithoutIt( string text, @@ -89,6 +83,30 @@ public static void AFieldPrefix_IsAlsoTriedWithoutIt( [first, second], CaptureNames.From(text).Candidates); + [Theory] + [InlineData("_total")] + [InlineData("this._total")] + public static void ALeadingUnderscore_IsLeftToTheMatchersUnderscoreTier( + string text) + => Assert.True(CaptureNames.From(text).Candidates.IsDefault); + + [Theory] + [InlineData("")] + [InlineData(" ")] + [InlineData("\t")] + public static void AnEmptyTypedName_IsRefusedAsTypedText_NotAsTheCompilersFault( + string text) + { + var ex = Assert.Throws( + () => CaptureNames.From(text)); + + Contains( + ex, + "The output parameter's name is empty", + "CaptureOutput(out DbCapture x, \"total\")"); + Assert.DoesNotContain("compiler", ex.Message); + } + [Fact] public static void NoChainNameIsATried_Candidate() => Assert.True(CaptureNames.From("state.total").Candidates.IsDefault); diff --git a/Tests/Open.Database.Extensions.Core.Tests/CaptureTests.cs b/Tests/Open.Database.Extensions.Core.Tests/CaptureTests.cs index 0b34c079..7a19b333 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/CaptureTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/CaptureTests.cs @@ -323,6 +323,20 @@ public static async Task ExecuteReturnAsync_BesideANamedCapture_Runs() Assert.Equal(5, await total); } + [Fact] + public static async Task ExecuteReturnAsync_BesideAModelCapture_ReadsEachValueOnce() + { + var c = new CaptureConnection(("Total", 7), ("Pages", 2), ("", 3)); + + int code = await c + .StoredProcedure("p") + .CaptureOutput(out DbCapture page) + .ExecuteReturnAsync(Token); + + Assert.Equal(3, code); + Assert.Equal(new PageInfo(7, 2), await page); + } + // ---- one owner per output -------------------------------------------- [Fact] From 7febd4d3a474d60100e063a5fc8298afad65b7d8 Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Wed, 2 Dec 2026 11:10:20 -0800 Subject: [PATCH 10/17] Tidy the output parameter samples and docs Sample chains follow the layout rule: the first call on the receiver's line, one call per line, and each long definition broken after the equals sign. The sample Blog factory is static readonly again, and the harness supplies its connection string through an environment variable set before the class is first used. The raw command sample now returns the return code it reads, and the harness checks it. The ad hoc capture prose matches the samples, a field capture notes that it holds one call's capture, the field comment no longer implies an underscore prefix is stripped, and the name rule lists m_ and s_ as the field prefixes. Long harness lines are wrapped. Co-Authored-By: Claude Sonnet 5.5 --- docsite/articles/expressive-commands.md | 6 +- docsite/samples/OutputParameters.cs | 68 ++++++++++---------- docsite/samples/OutputParametersSqlServer.cs | 9 ++- docsite/samples/Program.cs | 15 ++++- 4 files changed, 56 insertions(+), 42 deletions(-) diff --git a/docsite/articles/expressive-commands.md b/docsite/articles/expressive-commands.md index f095ff3c..1aa4bce0 100644 --- a/docsite/articles/expressive-commands.md +++ b/docsite/articles/expressive-commands.md @@ -136,7 +136,7 @@ A name you write is sent exactly as written: the library never adds or removes a For a stored procedure the name is settled when the command runs. The provider reports the procedure's real parameter names (SQL Server does), and each argument is matched to one of them: 1. Exactly, else ignoring case, else ignoring case and underscores: `TitleContains` finds `@title_contains`. -2. Else with one common parameter prefix dropped from the real name (`p_`, `in_`, `i_`, `prm_`, `par_`, `v_`, or a lone `p` before a capital letter): `Author` finds `@p_author` and `@pAuthor`. A field prefix on the argument (`m_author`, `s_author`, `_author`) is also tried without it. +2. Else with one common parameter prefix dropped from the real name (`p_`, `in_`, `i_`, `prm_`, `par_`, `v_`, or a lone `p` before a capital letter): `Author` finds `@p_author` and `@pAuthor`. A field prefix on the argument (`m_author`, `s_author`) is also tried without it. 3. A chain tries its longer endings first, each through all of those steps before the next: `order.Customer.Id` tries `orderCustomerId`, `CustomerId`, then `Id`, so `@customer_id` and `@p_customer_id` are chosen over a bare `@id`. For example `AddParam(search.Author)` sends `@p_author` when the procedure declares that, `@Author` or `@author` when it declares one of those, and throws when it declares none of them. The prefix step (rule 2) can bind a parameter whose name only starts like a prefix: `Stock` finds `@in_stock`, `Value` finds `@par_value` and `Progress` finds `@in_progress`. When that is not the parameter you mean, name it yourself: `AddParam("stock", stock)`. @@ -255,11 +255,11 @@ The definition is declared once, in a `static readonly` field, and each call bin [!code-csharp[](../samples/OutputParameters.cs#sql_server_output_def_capture_list)] -Ad hoc, a capture goes on a command, before `Map`: +Ad hoc, a capture goes on the command: [!code-csharp[](../samples/OutputParameters.cs#sql_server_output_capture_list)] -A capture takes the name of its variable: `CaptureOutput(out DbCapture total)` reads the parameter `@total`, found by the four tiers a name is matched by (exactly, ignoring case, ignoring case and underscores, without a common prefix), so a variable `totalCount` finds `@total_count`. A local declared in the call, a local declared earlier and a field (`out this.total`) all name it. When the variable's name differs, pass the name last: `CaptureOutput(out DbCapture count, "total")`. A discard (`out _`), an element access (`out totals[0]`) and a null name derive no name, and throw with that fix. A capture of a model needs no name: its members name the parameters, as they do for `Output()`. The compiler fills the name from the variable in C# 10 and later; with an older language version, pass the name last. +A capture takes the name of its variable: `CaptureOutput(out DbCapture total)` reads the parameter `@total`, found by the four tiers a name is matched by (exactly, ignoring case, ignoring case and underscores, without a common prefix), so a variable `totalCount` finds `@total_count`. A local declared in the call, a local declared earlier and a field (`out this.total`) all name it. A field holds one call's capture, so use it for one call at a time. When the variable's name differs, pass the name last: `CaptureOutput(out DbCapture count, "total")`. A discard (`out _`), an element access (`out totals[0]`) and a null name derive no name, and throw with that fix. A capture of a model needs no name: its members name the parameters, as they do for `Output()`. The compiler fills the name from the variable in C# 10 and later; with an older language version, pass the name last. [!code-csharp[](../samples/OutputParameters.cs#sql_server_output_def_names)] diff --git a/docsite/samples/OutputParameters.cs b/docsite/samples/OutputParameters.cs index 174df115..459a01f6 100644 --- a/docsite/samples/OutputParameters.cs +++ b/docsite/samples/OutputParameters.cs @@ -6,11 +6,14 @@ namespace Samples; // The SQL Server procedures these samples call are created in tempdb by // OutputParametersSqlServer, and Program.cs runs the samples against them -// when LocalDB is available; Blog is the factory it points at them. +// when LocalDB is available, pointing Blog at them through ConnectionVariable. public static class OutputParameters { - public static SqlConnectionFactory Blog { get; set; } - = new(@"Server=(localdb)\MSSQLLocalDB;Database=Blog;Integrated Security=true"); + public const string ConnectionVariable = "SAMPLES_BLOG_CONNECTION"; + + static readonly SqlConnectionFactory Blog = new( + Environment.GetEnvironmentVariable(ConnectionVariable) + ?? @"Server=(localdb)\MSSQLLocalDB;Database=Blog;Integrated Security=true"); #region sql_server_output_def_model // The procedure declares @id and @created_utc as OUTPUT and ends with a RETURN code. @@ -19,7 +22,8 @@ public record AddPostResult(int Id, DateTime CreatedUtc, int ReturnValue); // Declared once. The model is checked here, not on the first call. static readonly OutputDbNonQuery AddPost - = DbNonQuery.Procedure("[dbo].[AddPost]").Output(); + = DbNonQuery.Procedure("[dbo].[AddPost]") + .Output(); public static async Task Model( string title, @@ -39,8 +43,7 @@ public static async Task ModelAdHoc( string title, CancellationToken cancellationToken) { - AddPostResult created = await Blog - .StoredProcedure("[dbo].[AddPost]") + AddPostResult created = await Blog.StoredProcedure("[dbo].[AddPost]") .AddParam(title) .ExecuteOutputAsync(cancellationToken); @@ -52,7 +55,8 @@ public static async Task ModelAdHoc( // One output parameter, read by its name. A name finds its parameter as // AddParam's does, so "total" finds @total and "postId" finds @post_id. static readonly OutputDbNonQuery AddPostId - = DbNonQuery.Procedure("[dbo].[AddPost]").Output("id"); + = DbNonQuery.Procedure("[dbo].[AddPost]") + .Output("id"); // One decimal output needs its precision and scale; OutputDecimal gives // a decimal? for a procedure that can set the output to NULL. @@ -88,19 +92,16 @@ static readonly OutputDbNonQuery MaybePostsTotal { #region sql_server_output_named // One output parameter, read by its name. - int id = await Blog - .StoredProcedure("[dbo].[AddPost]") + int id = await Blog.StoredProcedure("[dbo].[AddPost]") .AddParam(title) .ExecuteOutputAsync("id", cancellationToken); // One decimal output needs its precision and scale. - decimal total = await Blog - .StoredProcedure("[dbo].[CountPosts]") + decimal total = await Blog.StoredProcedure("[dbo].[CountPosts]") .ExecuteOutputAsync("total", 19, 4, cancellationToken); // The same, returning null when the procedure sets the output to NULL. - decimal? maybe = await Blog - .StoredProcedure("[dbo].[CountPosts]") + decimal? maybe = await Blog.StoredProcedure("[dbo].[CountPosts]") .ExecuteOutputDecimalAsync("total", 19, 4, cancellationToken); #endregion @@ -114,7 +115,8 @@ public record Totals( [property: Column(TypeName = "decimal(19,4)")] decimal Total); static readonly OutputDbNonQuery CountPosts - = DbNonQuery.Procedure("[dbo].[CountPosts]").Output(); + = DbNonQuery.Procedure("[dbo].[CountPosts]") + .Output(); public static async Task Decimals( CancellationToken cancellationToken) @@ -171,8 +173,9 @@ public record PostRow(int Id, string Title); public record PostPage(List Rows, int Total); // A page of posts, and the total the procedure sets as an OUTPUT. - static readonly MappedDbQuery PagePosts = DbQuery.Procedure("[dbo].[PagePosts]") - .Map(); + static readonly MappedDbQuery PagePosts + = DbQuery.Procedure("[dbo].[PagePosts]") + .Map(); public static async Task Page( int page, @@ -195,8 +198,7 @@ public static async Task PageAdHoc( int page, CancellationToken cancellationToken) { - List rows = await Blog - .StoredProcedure("[dbo].[PagePosts]") + List rows = await Blog.StoredProcedure("[dbo].[PagePosts]") .AddParam(page) .Map() .CaptureOutput(out DbCapture total) @@ -226,7 +228,8 @@ public record PageInfo(int Total, int Pages); #region sql_server_output_def_capture_return static readonly MappedDbQuery ArchivePosts - = DbQuery.Procedure("[dbo].[ArchivePosts]").Map(); + = DbQuery.Procedure("[dbo].[ArchivePosts]") + .Map(); public static async Task> Archive( DateTime before, @@ -254,9 +257,8 @@ public static async Task> ArchiveAdHoc( DateTime before, CancellationToken cancellationToken) { - // On the command: the query Map makes runs it, and fills it. - List archived = await Blog - .StoredProcedure("[dbo].[ArchivePosts]") + // On the command: the capture is filled when the Map query finishes. + List archived = await Blog.StoredProcedure("[dbo].[ArchivePosts]") .AddParam(before) .CaptureReturn(out DbCapture status) .Map() @@ -280,7 +282,8 @@ static readonly DbNonQuery InsertPost // A scalar returns its value, and the outputs beside it. static readonly ScalarDbQuery PostCount - = DbQuery.Procedure("[dbo].[CountPosts]").Scalar(); + = DbQuery.Procedure("[dbo].[CountPosts]") + .Scalar(); public static async Task<(int Rows, int Id)> Insert( string title, @@ -307,7 +310,8 @@ static readonly ScalarDbQuery PostCount #region sql_server_output_def_capture_stream static readonly MappedDbQuery ExportPosts - = DbQuery.Procedure("[dbo].[ExportPosts]").Map(); + = DbQuery.Procedure("[dbo].[ExportPosts]") + .Map(); public static async Task Export( TextWriter writer, @@ -335,8 +339,7 @@ public static async Task ExportAdHoc( TextWriter writer, CancellationToken cancellationToken) { - IAsyncEnumerable rows = Blog - .StoredProcedure("[dbo].[ExportPosts]") + IAsyncEnumerable rows = Blog.StoredProcedure("[dbo].[ExportPosts]") .Map() .CaptureOutput(out DbCapture exported) .ToPooledStream(cancellationToken); @@ -358,7 +361,8 @@ await writer.WriteLineAsync( // @total_count too. public sealed class PagePager { - // A field: the last identifier, _total, finds @total as total does. + // A field: the last identifier, _total, finds @total (underscores are ignored). + // It holds one call's capture, so use the pager for one call at a time. DbCapture _total; public async Task PageAsync( @@ -406,7 +410,7 @@ await PagePosts.Using(Blog) } #endregion - public static async Task Raw( + public static async Task<(int Id, int ReturnCode)> Raw( string title, CancellationToken cancellationToken) { @@ -414,8 +418,7 @@ public static async Task Raw( // To set a direction yourself, work on the raw command. int id = 0; int returned = 0; - await Blog - .StoredProcedure("[dbo].[AddPost]") + await Blog.StoredProcedure("[dbo].[AddPost]") .ExecuteAsync(async command => { command.AddParameter("title", title); @@ -430,9 +433,8 @@ await Blog id = (int)output.Value!; returned = (int)returnCode.Value!; }); - #endregion - _ = returned; - return id; + return (id, returned); + #endregion } } diff --git a/docsite/samples/OutputParametersSqlServer.cs b/docsite/samples/OutputParametersSqlServer.cs index c63ffb0c..3eb2e2f5 100644 --- a/docsite/samples/OutputParametersSqlServer.cs +++ b/docsite/samples/OutputParametersSqlServer.cs @@ -9,7 +9,8 @@ public sealed class OutputParametersSqlServer : IAsyncDisposable { static readonly string[] Names = [ - "AddPost", "CountPosts", "PagePosts", "ArchivePosts", "ExportPosts", "DeletePost", + "AddPost", "CountPosts", "PagePosts", + "ArchivePosts", "ExportPosts", "DeletePost", ]; OutputParametersSqlServer() { } @@ -97,13 +98,15 @@ public ValueTask DisposeAsync() => new(ExecuteAsync(DropAll, CancellationToken.None)); static string DropAll - => string.Concat(Names.Select(static name => $"drop procedure if exists dbo.{name}; ")); + => string.Concat( + Names.Select(static name => $"drop procedure if exists dbo.{name}; ")); static async Task ExecuteAsync( string sql, CancellationToken cancellationToken) { - await using var connection = new SqlConnection(LittleCodeSqlServer.ConnectionString); + await using var connection = new SqlConnection( + LittleCodeSqlServer.ConnectionString); await connection.OpenAsync(cancellationToken); await using var command = connection.CreateCommand(); command.CommandText = sql; diff --git a/docsite/samples/Program.cs b/docsite/samples/Program.cs index 5028a98d..1f3a9dc4 100644 --- a/docsite/samples/Program.cs +++ b/docsite/samples/Program.cs @@ -608,7 +608,10 @@ await ThrowsAsync(() => HowLittleCode.CollectAsync(od "how little code, task 4 (SQL Server): the stored procedure with two parameters returns the same row in all four"); // Output parameters: each sample runs against procedures created in tempdb. - OutputParameters.Blog = new SqlConnectionFactory(serverConnectionString); + // Set before OutputParameters is first used: its Blog reads it once. + Environment.SetEnvironmentVariable( + OutputParameters.ConnectionVariable, + serverConnectionString); await using OutputParametersSqlServer outputProcedures = await OutputParametersSqlServer.StartAsync(littleCodeToken); var createdAt = new DateTime(2026, 1, 2, 3, 4, 5); var addPostResult = new OutputParameters.AddPostResult(7, createdAt, 3); @@ -634,7 +637,8 @@ await OutputParameters.Delete(1, littleCodeToken) == 1, && definitionPage.Rows.Select(static row => row.Id).SequenceEqual([1, 2]) && adHocPage.Rows.Select(static row => row.Id).SequenceEqual([1, 2]), "output parameters: a capture on a call of a stored definition and on an ad hoc command give the rows and the output"); - (List infoRows, OutputParameters.PageInfo info) = await OutputParameters.PageWithInfo(1, littleCodeToken); + (List infoRows, OutputParameters.PageInfo info) + = await OutputParameters.PageWithInfo(1, littleCodeToken); Check( infoRows.Count == 2 && info == new OutputParameters.PageInfo(42, 5), "output parameters: a model capture reads several outputs beside the rows"); @@ -652,11 +656,16 @@ await OutputParameters.Count(littleCodeToken) == (3, 12.5m), await OutputParameters.Names(1, littleCodeToken) == 126 && await new OutputParameters.PagePager().PageAsync(1, littleCodeToken) == 42, "output parameters: a capture is named by a declared local, an earlier local, a field or a name passed last"); + Check( + await OutputParameters.Raw("T", littleCodeToken) == (7, 3), + "output parameters: the raw command reads an output and the return code after it runs"); using StringWriter exported = new(); Check( await OutputParameters.Export(exported, littleCodeToken) == 2 && await OutputParameters.ExportAdHoc(exported, littleCodeToken) == 2 - && exported.ToString().Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries).SequenceEqual(["One", "Two", "One", "Two"]), + && exported.ToString() + .Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries) + .SequenceEqual(["One", "Two", "One", "Two"]), "output parameters: a capture on a stream is filled when the loop ends, on a definition and ad hoc"); } } From 63aee0d979a3c900bec53606e23a9d06110df177 Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Wed, 2 Dec 2026 11:10:44 -0800 Subject: [PATCH 11/17] Say "empty or only white space" for a typed capture name with no characters A name of only white space has characters, so the message now says it is empty or only white space. Co-Authored-By: Claude Opus 5.5 --- Source/Core/CaptureNames.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Source/Core/CaptureNames.cs b/Source/Core/CaptureNames.cs index 3400facc..19913c62 100644 --- a/Source/Core/CaptureNames.cs +++ b/Source/Core/CaptureNames.cs @@ -133,7 +133,7 @@ static ArgumentException NoName(string? text) + "passed. " : string.IsNullOrWhiteSpace(text) ? "The output parameter's name is empty: the name passed last " - + "has no characters. " + + "is empty or only white space. " : $"Cannot take the output parameter's name from '{text}': a " + "discard (_) and an element access (arr[0]) have no name. ") + "Declare a variable named after the parameter, or pass the name " From 67aa2145174b1af8e6bc683adc43e35fe370599a Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Wed, 2 Dec 2026 11:19:01 -0800 Subject: [PATCH 12/17] Pin the capture types in the binding tests without unused locals The language-version binding tests declared captures they never used, which the analyzers report. Each capture now goes through a helper that compiles only when the value has the expected type. The existing-local case keeps its declaration on purpose. Co-Authored-By: Claude Opus 5.5 --- .../BoundCallCaptureBindingTests.cs | 25 +++++++++++++++---- 1 file changed, 20 insertions(+), 5 deletions(-) diff --git a/Tests/Open.Database.Extensions.LegacyCompiler.Tests/BoundCallCaptureBindingTests.cs b/Tests/Open.Database.Extensions.LegacyCompiler.Tests/BoundCallCaptureBindingTests.cs index f6230132..ad38b73f 100644 --- a/Tests/Open.Database.Extensions.LegacyCompiler.Tests/BoundCallCaptureBindingTests.cs +++ b/Tests/Open.Database.Extensions.LegacyCompiler.Tests/BoundCallCaptureBindingTests.cs @@ -32,7 +32,10 @@ public static void ATypedOutDeclaration_OnAWriteAndOnAScalar_Compiles() var connection = new NoConnection(); DbNonQuery write = DbNonQuery.Procedure("dbo.P"); ScalarDbQuery scalar = DbQuery.Procedure("dbo.P").Scalar(); + // An existing local is the case under test, so it is not inlined. +#pragma warning disable IDE0018 DbCapture existing; +#pragma warning restore IDE0018 BoundCall a = write.Using(connection) .CaptureOutput(out DbCapture total) @@ -42,6 +45,11 @@ public static void ATypedOutDeclaration_OnAWriteAndOnAScalar_Compiles() .CaptureOutput(out DbCapture scalarTotal) .CaptureReturn(out DbCapture scalarCode); + Typed>(total); + Typed>(existing); + Typed>(code); + Typed>(scalarTotal); + Typed>(scalarCode); Assert.NotEqual(write.Using(connection), a); Assert.NotEqual(scalar.Using(connection), b); } @@ -60,10 +68,10 @@ public static void TheDecimalForms_OnAWriteAndOnAScalar_TakeOutVar() .CaptureOutput(out var scalarAmount, 18, 2) .CaptureOutputDecimal(out var scalarFee, 18, 2); - DbCapture shaped = amount; - DbCapture nullable = fee; - DbCapture scalarShaped = scalarAmount; - DbCapture scalarNullable = scalarFee; + Typed>(amount); + Typed>(fee); + Typed>(scalarAmount); + Typed>(scalarFee); Assert.NotEqual(write.Using(connection), a); Assert.NotEqual(scalar.Using(connection), b); } @@ -78,6 +86,8 @@ public static void TheNamePassedLast_IsAccepted_OnEveryVersion() .CaptureOutput(out DbCapture whatever, "total") .CaptureOutput(out DbCapture amount, 18, 2, "amount"); + Typed>(whatever); + Typed>(amount); Assert.NotEqual(write.Using(connection), a); } @@ -91,8 +101,13 @@ public static void ADeclaredCaptureOnAWriteWithTheTypeArgument_Compiles() .CaptureOutput(out var total, "total") .CaptureReturn(out var code); - DbCapture check = total; + Typed>(total); + Typed>(code); Assert.NotEqual(write.Using(connection), a); } + + // Compiles only when the value is a T: pins the type that a capture's + // out declaration gets. + static void Typed(T value) => _ = value; } } From c3ec44597359d81925f8b2479f892d5b20f3faf9 Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Wed, 2 Dec 2026 12:26:45 -0800 Subject: [PATCH 13/17] Pass the layout step to the captured run instead of a bool The captured write and scalar runs took a bool that chose whether the return code is read. They now take the function that gives the layout the run reads: the captures' layout as is, or with the return code after it. Co-Authored-By: Claude Opus 5.5 --- Source/Core/DbQueryRunner.Output.cs | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/Source/Core/DbQueryRunner.Output.cs b/Source/Core/DbQueryRunner.Output.cs index 138d9df9..a1d452ac 100644 --- a/Source/Core/DbQueryRunner.Output.cs +++ b/Source/Core/DbQueryRunner.Output.cs @@ -139,7 +139,7 @@ public static ValueTask ReturnAsync( cancellationToken) : CapturedAsync( definition, source, call, - captures, readReturn: true, + captures, WithReturn, static (command, token) => command.ExecuteNonQueryAsync(token), static (_, run) => RowMap.ConvertScalar( run.Value(run.Layout.Members.Length - 1)), @@ -160,7 +160,7 @@ public static ValueTask NonQueryCapturedAsync( CancellationToken cancellationToken) => CapturedAsync( definition, source, call, - captures, readReturn: false, + captures, static layout => layout, static (command, token) => command.ExecuteNonQueryAsync(token), static (count, _) => count, cancellationToken); @@ -181,7 +181,7 @@ public static ValueTask ScalarCapturedAsync( CancellationToken cancellationToken) => CapturedAsync( definition, source, call, - captures, readReturn: false, + captures, static layout => layout, static (command, token) => command.ExecuteScalarAsync(token), static (value, _) => RowMap.ConvertScalar( value, @@ -190,13 +190,14 @@ public static ValueTask ScalarCapturedAsync( // Claims the captures, runs, and completes every capture on every exit: // the claim is the first statement, reached synchronously from the - // terminal. + // terminal. The layout function gives what the run reads: the captures' + // layout as is, or with the return code after it. static async ValueTask CapturedAsync( DbQuery definition, object source, ParamList call, CaptureHolder captures, - bool readReturn, + Func layout, Func> execute, Func convert, CancellationToken cancellationToken) @@ -204,12 +205,9 @@ static async ValueTask CapturedAsync( CaptureRun run = captures.Start(cancellationToken); try { - OutputLayout layout = readReturn - ? WithReturn(run.Set.Layout) - : run.Set.Layout; return await ExecuteWithOutputAsync( definition, source, call, - new OutputRun(layout), + new OutputRun(layout(run.Set.Layout)), execute, (value, output) => { From b7dd4713a1a2cc76e422da38c3ec519d7e22f682 Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Wed, 2 Dec 2026 12:49:19 -0800 Subject: [PATCH 14/17] Check a definition's outputs against the procedure's metadata A stored definition's call that reads output parameters now reads the procedure's parameter metadata, once, as a command's call does, so an output on an input parameter or a decimal with a lower scale is refused before the run on both paths. The metadata tests use the name-last capture forms and cover a definition and a capture on its call. Co-Authored-By: Claude Opus 5.5 --- Source/Core/BoundCall.cs | 3 + Source/Core/DbQueryRunner.Output.cs | 26 ++++++++ .../OutputMetadataLocalDbTests.cs | 65 +++++++++++++++++-- 3 files changed, 90 insertions(+), 4 deletions(-) diff --git a/Source/Core/BoundCall.cs b/Source/Core/BoundCall.cs index 89461c5b..47044b1b 100644 --- a/Source/Core/BoundCall.cs +++ b/Source/Core/BoundCall.cs @@ -326,6 +326,9 @@ public static ValueTask ExecuteNonQueryAsync( /// /// A task that represents the asynchronous operation; its result is the model, or the one value. /// Before the command executes: an output matches no parameter, or two match one, or is a value, which is bound to nothing. + /// + /// + /// /// A value does not convert, or is NULL and the type does not take it. /// is canceled. public static ValueTask ExecuteOutputAsync( diff --git a/Source/Core/DbQueryRunner.Output.cs b/Source/Core/DbQueryRunner.Output.cs index a1d452ac..5f7f5e65 100644 --- a/Source/Core/DbQueryRunner.Output.cs +++ b/Source/Core/DbQueryRunner.Output.cs @@ -36,6 +36,24 @@ static OutputLayout WithReturn(OutputLayout layout) []); } + // A call that reads an output parameter of a procedure is checked against + // the procedure's parameter metadata, as a command's call is: read once for + // a procedure's own set of names, then kept with it. + static ValueTask EnsureMetadataAsync( + DbConnection connection, + DbQuery definition, + NameSet? names, + OutputRun output, + CancellationToken cancellationToken) + => output.Layout.HasOutputParameter + && names is { Home: not null, Names.Length: > 0, Metadata: null } + ? ProcedureParameterMetadata.EnsureAsync( + connection, + definition.CommandText, + names, + cancellationToken) + : default; + // As Make, then the outputs: resolved with the names and added after the // values, which a value of the same name turns into InputOutput. static DbCommand MakeWithOutput( @@ -266,6 +284,10 @@ static async ValueTask ExecuteWithOutputAsync( lease.Connection, cancellationToken) .ConfigureAwait(false); + await EnsureMetadataAsync( + lease.Connection, definition, names, output, + cancellationToken) + .ConfigureAwait(false); built = MakeWithOutput( lease.Connection, lease.Transaction, definition, call, names, output); @@ -347,6 +369,10 @@ public static async ValueTask RunCapturedAsync( lease.Connection, cancellationToken) .ConfigureAwait(false); + await EnsureMetadataAsync( + lease.Connection, definition, names, output, + cancellationToken) + .ConfigureAwait(false); built = MakeWithOutput( lease.Connection, lease.Transaction, definition, call, names, output); diff --git a/Tests/Open.Database.Extensions.Core.Tests/OutputMetadataLocalDbTests.cs b/Tests/Open.Database.Extensions.Core.Tests/OutputMetadataLocalDbTests.cs index 0df0ce5f..e4133fa6 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/OutputMetadataLocalDbTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/OutputMetadataLocalDbTests.cs @@ -84,16 +84,73 @@ public static async Task AnInputParameter_ThrowsBeforeTheRun_ForANamedOutputAndA Assert.Contains("an input parameter (mode IN)", named.Message); var captured = await Assert.ThrowsAsync(async () => await connection.StoredProcedure(name) - .CaptureOutput("id", out DbCapture id) + .CaptureOutput(out DbCapture id) .Map() .ToListAsync(Token)); - Assert.Contains("CaptureOutput(\"id\") reads '@id'", captured.Message); + Assert.Contains("CaptureOutput(out DbCapture id) reads '@id'", captured.Message); Assert.Contains("Declare the parameter OUTPUT in the procedure", captured.Message); Assert.Equal(0, LocalDbFixture.Count(table.Name)); } } + // A stored definition's call checks the same metadata as a command's call, on its own: nothing else has called the procedure first. + [Fact] + public static async Task AnInputParameter_ThrowsBeforeTheRun_ForADefinitionAndACaptureOnItsCall() + { + 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 output = await Assert.ThrowsAsync(async () => await DbNonQuery.Procedure(name) + .Output() + .Using(connection) + .ExecuteOutputAsync(Token)); + Assert.Contains("PostId.Id reads '@id' of dbo.", output.Message); + Assert.Contains("an input parameter (mode IN)", output.Message); + + var captured = await Assert.ThrowsAsync(async () => await DbQuery.Procedure(name) + .Map() + .Using(connection) + .CaptureOutput(out DbCapture id) + .ToListAsync(Token)); + Assert.Contains("reads '@id'", captured.Message); + Assert.Contains("an input parameter (mode IN)", captured.Message); + + Assert.Equal(0, LocalDbFixture.Count(table.Name)); + } + } + + [Fact] + public static async Task ADecimalScaleCheck_AlsoCoversADefinition() + { + 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 DbNonQuery.Procedure(name) + .Output() + .Using(connection) + .ExecuteOutputAsync(Token)); + Assert.Contains("has the scale 3, so the value would be rounded to 2 decimal places", ex.Message); + Assert.Equal(0, LocalDbFixture.Count(table.Name)); + + Total3 kept = await DbNonQuery.Procedure(name) + .Output() + .Using(connection) + .ExecuteOutputAsync(Token); + Assert.Equal(1.234m, kept.Total); + } + } + // 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() @@ -165,7 +222,7 @@ public static async Task ADecimalScaleCheck_AlsoCoversTheNamedAndCapturedForms() 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) + .CaptureOutputDecimal(out DbCapture total, 10, 2) .Map() .ToListAsync(Token)); Assert.Contains("Pass a scale of 3 or more", captured.Message); @@ -173,7 +230,7 @@ public static async Task ADecimalScaleCheck_AlsoCoversTheNamedAndCapturedForms() 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) + .CaptureOutputDecimal(out DbCapture kept, 10, 3, "total") .Map() .ToListAsync(Token); Assert.Equal([1], rows.Select(static r => r.N)); From 0fcbf9ad0aa1c9280370913542d33fdf7caa3cb8 Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Wed, 2 Dec 2026 12:57:37 -0800 Subject: [PATCH 15/17] Expect the metadata refusal in the capture name tests An output named after an input parameter of a procedure is now refused before the run, from the procedure's metadata, instead of by SQL Server. Co-Authored-By: Claude Opus 5.5 --- .../CaptureNameLocalDbTests.cs | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/Tests/Open.Database.Extensions.Core.Tests/CaptureNameLocalDbTests.cs b/Tests/Open.Database.Extensions.Core.Tests/CaptureNameLocalDbTests.cs index 80fe0672..587c2411 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/CaptureNameLocalDbTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/CaptureNameLocalDbTests.cs @@ -132,7 +132,7 @@ public static async Task AModelCapturedWithAName_SaysTheNameWasNotUsed_AndGivesB // ---- a variable named after an input parameter ---- [Fact] - public static async Task AModelMember_NamedAfterAnInput_BecomesInputOutput_AndSqlServerRefuses() + public static async Task AModelMember_NamedAfterAnInput_BecomesInputOutput_AndIsRefusedBeforeTheRun() { LocalDbFixture.SkipUnlessAvailable(); using LocalDbFixture.Scratch procedure = Procedure( @@ -141,16 +141,18 @@ public static async Task AModelMember_NamedAfterAnInput_BecomesInputOutput_AndSq await using SqlConnection connection = await OpenAsync(); int id = 5; - var ex = await Assert.ThrowsAsync( + // The procedure's metadata reports @id as mode IN: refused before the run. + var ex = await Assert.ThrowsAsync( async () => await connection.StoredProcedure("dbo." + procedure.Name) .AddParam(id) .ExecuteOutputAsync(Token)); - Assert.Equal(8162, ex.Number); + Assert.Contains("IdOnly.Id reads '@id'", ex.Message); + Assert.Contains("an input parameter (mode IN)", ex.Message); } [Fact] - public static async Task ACapture_NamedAfterAnInput_IsSentAsOutput_AndSqlServerRefuses() + public static async Task ACapture_NamedAfterAnInput_IsSentAsOutput_AndIsRefusedBeforeTheRun() { LocalDbFixture.SkipUnlessAvailable(); using LocalDbFixture.Scratch procedure = Procedure( @@ -159,12 +161,14 @@ public static async Task ACapture_NamedAfterAnInput_IsSentAsOutput_AndSqlServerR await using SqlConnection connection = await OpenAsync(); DbCapture capture; - var ex = await Assert.ThrowsAsync( + // The procedure's metadata reports @id as mode IN: refused before the run. + var ex = await Assert.ThrowsAsync( async () => await connection.StoredProcedure("dbo." + procedure.Name) .CaptureOutput(out DbCapture id) .ExecuteNonQueryAsync(Token)); - Assert.Equal(8162, ex.Number); + Assert.Contains("CaptureOutput(out DbCapture id) reads '@id'", ex.Message); + Assert.Contains("an input parameter (mode IN)", ex.Message); capture = default; Assert.Equal(default, capture); } From d9b6c6b3d33c7b4494e36539b94d15845303dfe8 Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Wed, 2 Dec 2026 13:29:20 -0800 Subject: [PATCH 16/17] Include a definition's outputs in its equality Two definitions of one procedure that read different outputs compared equal, and so did their bound calls. The outputs are now compared by value (a named output builds its layout per declaration), and a definition without outputs hashes as before. Co-Authored-By: Claude Opus 5.5 --- Source/Core/DbQuery.cs | 10 ++- Source/Core/OutputLayout.cs | 76 +++++++++++++++++++ .../OutputDefinitionTests.cs | 21 +++++ 3 files changed, 105 insertions(+), 2 deletions(-) diff --git a/Source/Core/DbQuery.cs b/Source/Core/DbQuery.cs index ae69e0db..e747c402 100644 --- a/Source/Core/DbQuery.cs +++ b/Source/Core/DbQuery.cs @@ -375,7 +375,8 @@ public bool Equals(DbQuery? other) && string.Equals( CommandText, other.CommandText, - StringComparison.Ordinal)); + StringComparison.Ordinal) + && OutputLayout.Same(Output, other.Output)); /// public override bool Equals(object? obj) @@ -388,7 +389,12 @@ public override int GetHashCode() { int h = StringComparer.Ordinal.GetHashCode(CommandText); h = h * 31 + (int)Kind; - return h * 31 + Timeout; + h = h * 31 + Timeout; + + // A definition without outputs hashes as before. + return Output is null + ? h + : h * 31 + OutputLayout.Hash(Output); } } } diff --git a/Source/Core/OutputLayout.cs b/Source/Core/OutputLayout.cs index 72ca1ee1..9d63dfdd 100644 --- a/Source/Core/OutputLayout.cs +++ b/Source/Core/OutputLayout.cs @@ -116,6 +116,26 @@ public OutputMember( /// How the parameter is sent; for the return code, which is the provider's own. public readonly OutputWire? Wire; + + /// + /// Gets whether two members read the same output the same way. + /// + /// A member. + /// A member. + /// when every part that shapes the read is equal. + public static bool Same(OutputMember a, OutputMember b) + => ReferenceEquals(a, b) + || a.Form == b.Form + && a.Named == b.Named + && a.Exact == b.Exact + && a.IsReturnValue == b.IsReturnValue + && string.Equals(a.Name, b.Name, StringComparison.Ordinal) + && string.Equals(a.Label, b.Label, StringComparison.Ordinal) + && string.Equals(a.Display, b.Display, StringComparison.Ordinal) + && a.Candidates.IsDefault == b.Candidates.IsDefault + && (a.Candidates.IsDefault + || a.Candidates.SequenceEqual(b.Candidates, StringComparer.Ordinal)) + && OutputWire.Same(a.Wire, b.Wire); } /// @@ -182,6 +202,21 @@ sealed class OutputWire(DbType type, int size, byte precision, byte scale) /// Whether precision and scale are set. public bool HasPrecision => Precision != 0; + /// + /// Gets whether two wires send the parameter the same way. + /// + /// A wire, or . + /// A wire, or . + /// when both are , or their type, size, precision and scale are equal. + public static bool Same(OutputWire? a, OutputWire? b) + => ReferenceEquals(a, b) + || a is not null + && b is not null + && a.Type == b.Type + && a.Size == b.Size + && a.Precision == b.Precision + && a.Scale == b.Scale; + /// /// Sets the size, precision and scale on a parameter (not its type). /// @@ -333,6 +368,47 @@ public OutputLayout(OutputMember member) /// Whether a member reads a parameter (not only the return code). public readonly bool HasOutputParameter; + + /// + /// Gets whether two layouts read the same outputs the same way. + /// + /// + /// By value: a model's layout is built once, but a named output builds + /// its layout per declaration. + /// + /// A layout, or . + /// A layout, or . + /// when both are , or both read the same members. + public static bool Same(OutputLayout? a, OutputLayout? b) + { + if (ReferenceEquals(a, b)) return true; + if (a is null + || b is null + || a.Members.Length != b.Members.Length + || !string.Equals(a.Model, b.Model, StringComparison.Ordinal)) + { + return false; + } + + for (int i = 0; i < a.Members.Length; i++) + { + if (!OutputMember.Same(a.Members[i], b.Members[i])) return false; + } + + return true; + } + + /// + /// Gets a hash code that agrees with . + /// + /// The layout, or . + /// The hash code; 0 for . + public static int Hash(OutputLayout? layout) + => layout is null + ? 0 + : unchecked( + StringComparer.Ordinal.GetHashCode(layout.Model) * 31 + + layout.Members.Length); } /// diff --git a/Tests/Open.Database.Extensions.Core.Tests/OutputDefinitionTests.cs b/Tests/Open.Database.Extensions.Core.Tests/OutputDefinitionTests.cs index 2aea82cf..4e359fed 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/OutputDefinitionTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/OutputDefinitionTests.cs @@ -44,6 +44,27 @@ static DbNonQuery Proc(LocalDbFixture.Scratch procedure) // ---- declaration: no server ---- + // Two definitions of one procedure that read different outputs are two + // calls; the same outputs declared twice are one, with one hash code. + [Fact] + public static void TheOutputs_ArePartOfTheEquality() + { + var connection = new SqlConnection("Server=nowhere"); + OutputDbNonQuery a = DbNonQuery.Procedure("dbo.P").Output("a"); + OutputDbNonQuery sameAsA = DbNonQuery.Procedure("dbo.P").Output("a"); + OutputDbNonQuery b = DbNonQuery.Procedure("dbo.P").Output("b"); + OutputDbNonQuery scale2 = DbNonQuery.Procedure("dbo.P").Output("a", 10, 2); + OutputDbNonQuery scale4 = DbNonQuery.Procedure("dbo.P").Output("a", 10, 4); + OutputDbNonQuery model = DbNonQuery.Procedure("dbo.P").Output(); + OutputDbNonQuery sameModel = DbNonQuery.Procedure("dbo.P").Output(); + + Assert.Equal(a.Using(connection), sameAsA.Using(connection)); + Assert.Equal(a.Using(connection).GetHashCode(), sameAsA.Using(connection).GetHashCode()); + Assert.NotEqual(a.Using(connection), b.Using(connection)); + Assert.NotEqual(scale2.Using(connection), scale4.Using(connection)); + Assert.Equal(model.Using(connection), sameModel.Using(connection)); + } + [Fact] public static void AModel_IsCheckedWhenDeclared_NamingTheDefinitionAndTheModel() { From b839db1b93f088b4971795696627d778de3716aa Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Wed, 2 Dec 2026 13:29:20 -0800 Subject: [PATCH 17/17] Format the ExecuteOutputAsync refusal text only when it is thrown ExecuteOutputAsync built the text of the refusal beside a capture on every call. It now passes a constant format and the model, and the text is formatted only when a capture is there. Co-Authored-By: Claude Opus 5.5 --- Source/Core/ExpressiveCommandBase.Capture.cs | 15 ++++++++++++--- Source/Core/ExpressiveCommandBase.Output.cs | 4 ++-- .../CaptureTests.cs | 9 +++++++++ 3 files changed, 23 insertions(+), 5 deletions(-) diff --git a/Source/Core/ExpressiveCommandBase.Capture.cs b/Source/Core/ExpressiveCommandBase.Capture.cs index 8e2b7e26..5dae398c 100644 --- a/Source/Core/ExpressiveCommandBase.Capture.cs +++ b/Source/Core/ExpressiveCommandBase.Capture.cs @@ -1,4 +1,5 @@ using System.Diagnostics; +using System.Globalization; namespace Open.Database.Extensions; @@ -314,14 +315,22 @@ static async ValueTask InvokeAsync( /// Refuses ExecuteOutputAsync on a command that carries a capture: /// two readers of one parameter set. /// - /// The ExecuteOutputAsync form, for the - /// message. + /// The ExecuteOutputAsync form, for the + /// message, with {0} where the model goes. + /// The model's type name, or the parameter's name in + /// the named form. /// The command carries a /// capture; the capture is completed with the same exception. - void RefuseBesideCaptures(string call) + // The text is formatted only on the refusal: a call without a capture + // allocates nothing here. + void RefuseBesideCaptures(string callFormat, string model) { if (_captures is { } captures) { + string call = string.Format( + CultureInfo.InvariantCulture, + callFormat, + model); throw captures.Refuse( new InvalidOperationException( CaptureMessages.OutputBeside(captures, call))); diff --git a/Source/Core/ExpressiveCommandBase.Output.cs b/Source/Core/ExpressiveCommandBase.Output.cs index 526bc66e..0374d07f 100644 --- a/Source/Core/ExpressiveCommandBase.Output.cs +++ b/Source/Core/ExpressiveCommandBase.Output.cs @@ -70,7 +70,7 @@ public ValueTask ExecuteOutputAsync( OutputLayout layout = OutputLayout.Get(); if (layout.HasReturnValue) ThrowUnlessProcedure(layout); - RefuseBesideCaptures($"ExecuteOutputAsync<{layout.Model}>()"); + RefuseBesideCaptures("ExecuteOutputAsync<{0}>()", layout.Model); // Thrown synchronously, not through the returned task. CancellationToken.ThrowIfCancellationRequested(); @@ -281,7 +281,7 @@ ValueTask RunNamedAsync(OutputLayout layout, CancellationToken cancellatio { // Before the cancel: a capture on the command is completed by the // refusal. - RefuseBesideCaptures($"ExecuteOutputAsync(\"{layout.Model}\")"); + RefuseBesideCaptures("ExecuteOutputAsync(\"{0}\")", layout.Model); // Thrown synchronously, not through the returned task. CancellationToken.ThrowIfCancellationRequested(); diff --git a/Tests/Open.Database.Extensions.Core.Tests/CaptureTests.cs b/Tests/Open.Database.Extensions.Core.Tests/CaptureTests.cs index 7a19b333..fd854f39 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/CaptureTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/CaptureTests.cs @@ -229,6 +229,15 @@ public static async Task ExecuteOutputAsync_BesideACapture_IsRefused() "ExecuteOutputAsync(\"other\")"); await Assert.ThrowsAsync( async () => await total); + + var model = await Assert.ThrowsAsync( + async () => await c + .StoredProcedure("p") + .CaptureOutput(out DbCapture _, "total") + .ExecuteOutputAsync(Token)); + Contains(model, + "reads its output parameters twice", + "ExecuteOutputAsync()"); Assert.Equal(0, c.Executed); }