diff --git a/Source/Core/BoundCall.cs b/Source/Core/BoundCall.cs index 332ae864..47044b1b 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. @@ -27,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. @@ -39,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) @@ -83,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); } } } @@ -262,11 +284,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. /// @@ -282,9 +306,255 @@ public static ValueTask ExecuteScalarAsync( public static ValueTask ExecuteNonQueryAsync( this BoundCall call, CancellationToken cancellationToken = default) - => DbQueryRunner.NonQueryAsync( - call.Call.Definition, + => 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 + /// 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."); + } + + // 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, + 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. + 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. + 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 17c77705..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 @@ -33,7 +34,7 @@ enum CaptureKind : byte Model, /// One output parameter by name: - /// CaptureOutput<TValue>(name, …) and + /// CaptureOutput(out DbCapture<int> total) and /// CaptureOutputDecimal. Named, @@ -215,20 +216,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 +240,8 @@ static ImmutableArray Named(OutputLayout layout) members.Add(new OutputMember( member, $"{member.Display} of {capture}", - OutputForm.Capture)); + OutputForm.Capture, + receivedName)); } return members.MoveToImmutable(); @@ -425,6 +430,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. @@ -798,83 +834,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 its name + /// gives. + /// The model type, or the type of the value. + /// 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(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), - name, + OutputValue.Shaped( + name.Name, precision, scale, + display, OutputForm.Capture, name.Candidates), + name.Name, display); } @@ -1017,13 +1074,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/CaptureNames.cs b/Source/Core/CaptureNames.cs new file mode 100644 index 00000000..19913c62 --- /dev/null +++ b/Source/Core/CaptureNames.cs @@ -0,0 +1,142 @@ +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 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 < 2 + ? 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. 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) + { + 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( + (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 " + + "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 " + + "last: CaptureOutput(out DbCapture x, \"total\").", + "name"); +} 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..e747c402 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 @@ -354,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) @@ -367,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); } } } @@ -382,15 +409,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 +427,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 +436,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 +456,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 +472,7 @@ public DbQueryUsing Using( IDbConnectionPool pool) where TConnection : DbConnection => new( - _definition, + Definition, pool ?? throw new ArgumentNullException( nameof(pool))); @@ -453,7 +481,7 @@ public DbQueryUsing Using( IDbConnectionFactory factory) where TConnection : DbConnection => new( - _definition, + Definition, factory ?? throw new ArgumentNullException( nameof(factory))); } diff --git a/Source/Core/DbQueryCall.cs b/Source/Core/DbQueryCall.cs index a1a8112d..d6b87780 100644 --- a/Source/Core/DbQueryCall.cs +++ b/Source/Core/DbQueryCall.cs @@ -346,6 +346,17 @@ 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 new file mode 100644 index 00000000..5f7f5e65 --- /dev/null +++ b/Source/Core/DbQueryRunner.Output.cs @@ -0,0 +1,447 @@ +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], + []); + } + + // 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( + 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, WithReturn, + 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, static layout => layout, + 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, static layout => layout, + 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. 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, + Func layout, + Func> execute, + Func convert, + CancellationToken cancellationToken) + { + CaptureRun run = captures.Start(cancellationToken); + try + { + return await ExecuteWithOutputAsync( + definition, source, call, + new OutputRun(layout(run.Set.Layout)), + execute, + (value, output) => + { + // 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); + }, + cancellationToken) + .ConfigureAwait(false); + } + catch (Exception ex) + { + 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(); + } + } + + // 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); + await EnsureMetadataAsync( + lease.Connection, definition, names, output, + 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); + await EnsureMetadataAsync( + lease.Connection, definition, names, output, + 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; + } + // 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/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.Capture.cs b/Source/Core/ExpressiveCommandBase.Capture.cs index 4d9fb0f7..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; @@ -79,42 +80,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 +109,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 +132,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; @@ -334,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 32e1a7fd..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(); @@ -364,289 +364,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; - } - - 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.")); - } - } - - // Only a procedure's own set has metadata, and only once it was read. - if (names is { Home: not null }) - { - CheckMetadata(layout, resolved, names, where); - } - - run.Names = resolved; - } - - /// - /// Checks the output members against what the database says about the parameters they resolved to, when it said. - /// - /// - /// Only the exact mode IN counts; a mode that is anything else, or missing, does not (the metadata has no third state, because "not known" and "not mode IN" never differ in what the call does). A scale is compared only when it is known. - /// - /// The call's members. - /// The parameter each member resolved to; for the return code. - /// The procedure's set. - /// The procedure, for the messages. - /// - /// A member reads a parameter whose mode is IN, or declares a scale lower than the procedure's. - /// - static void CheckMetadata( - OutputLayout layout, string?[] resolved, - NameSet names, string where) - { - if (names.Metadata is not { IsKnown: true } metadata) return; - - for (int i = 0; i < resolved.Length; i++) - { - OutputMember member = layout.Members[i]; - if (member.IsReturnValue - || resolved[i] is not { } name - || names.Find(name) is not { } entry) - { - continue; - } - - if (metadata.IsModeIn(entry.Index)) - { - throw new InvalidOperationException( - $"{member.Display} reads '{entry.Real}' of {where} as an " - + "output parameter, but the database reports that " - + "parameter as an input parameter (mode IN), so the " - + "call would be refused. Declare the parameter OUTPUT in the " - + "procedure, or remove the member. If the procedure was " - + "changed since it was first called, call again."); - } + => OutputBinding.Resolve(run, names, Type, Command); - int declared = metadata.Scale(entry.Index); - if (member.Wire is { Type: DbType.Decimal, HasPrecision: true } wire - && declared > wire.Scale) - { - string fix = member.Named - ? $"Pass a scale of {declared} or more" - : "Declare the member as [Column(TypeName = " - + $"\"decimal({wire.Precision},{declared})\")] or higher"; - - throw new InvalidOperationException( - $"{member.Display} has the scale {wire.Scale}, but " - + $"'{entry.Real}' of {where} has the scale {declared}, " - + "so the value would be rounded to " - + $"{wire.Scale} decimal places. {fix}, or declare the " - + $"parameter in the procedure with the scale {wire.Scale}. " - + "If the procedure was changed since it was first " - + "called, call again."); - } - } - } - - static InvalidOperationException NoOutputMatch( - OutputMember member, - ImmutableArray real, - 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/MappedQuery.Capture.cs b/Source/Core/MappedQuery.Capture.cs index b4fd321c..f7be7da2 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 { /// @@ -35,6 +37,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 +60,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 +124,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 +140,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); @@ -146,44 +159,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. /// /// @@ -191,16 +188,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; @@ -217,15 +211,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; @@ -252,57 +243,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; @@ -323,57 +297,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; 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 - 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_ 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, + 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). @@ -174,46 +192,40 @@ - - 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 . @@ -227,7 +239,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. @@ -258,8 +270,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. @@ -272,11 +285,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). @@ -326,4 +356,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..01a2d630 --- /dev/null +++ b/Source/Core/OutputBinding.cs @@ -0,0 +1,425 @@ +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; or, when the database said, a member + /// reads a parameter of mode IN or declares a lower + /// scale than the procedure's. + /// + 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; + } + + 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 + ? "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.")); + } + } + + // Only a procedure's own set has metadata, and only once it was read. + if (names is { Home: not null }) + { + CheckMetadata(layout, resolved, names, where); + } + + run.Names = resolved; + } + + /// + /// Checks the output members against what the database says about the parameters they resolved to, when it said. + /// + /// + /// Only the exact mode IN counts; a mode that is anything else, or missing, does not (the metadata has no third state, because "not known" and "not mode IN" never differ in what the call does). A scale is compared only when it is known. + /// + /// The call's members. + /// The parameter each member resolved to; for the return code. + /// The procedure's set. + /// The procedure, for the messages. + /// + /// A member reads a parameter whose mode is IN, or declares a scale lower than the procedure's. + /// + static void CheckMetadata( + OutputLayout layout, string?[] resolved, + NameSet names, string where) + { + if (names.Metadata is not { IsKnown: true } metadata) return; + + for (int i = 0; i < resolved.Length; i++) + { + OutputMember member = layout.Members[i]; + if (member.IsReturnValue + || resolved[i] is not { } name + || names.Find(name) is not { } entry) + { + continue; + } + + if (metadata.IsModeIn(entry.Index)) + { + throw new InvalidOperationException( + $"{member.Display} reads '{entry.Real}' of {where} as an " + + "output parameter, but the database reports that " + + "parameter as an input parameter (mode IN), so the " + + "call would be refused. Declare the parameter OUTPUT in the " + + "procedure, or remove the member. If the procedure was " + + "changed since it was first called, call again."); + } + + int declared = metadata.Scale(entry.Index); + if (member.Wire is { Type: DbType.Decimal, HasPrecision: true } wire + && declared > wire.Scale) + { + string fix = member.Named + ? $"Pass a scale of {declared} or more" + : "Declare the member as [Column(TypeName = " + + $"\"decimal({wire.Precision},{declared})\")] or higher"; + + throw new InvalidOperationException( + $"{member.Display} has the scale {wire.Scale}, but " + + $"'{entry.Real}' of {where} has the scale {declared}, " + + "so the value would be rounded to " + + $"{wire.Scale} decimal places. {fix}, or declare the " + + $"parameter in the procedure with the scale {wire.Scale}. " + + "If the procedure was changed since it was first " + + "called, call again."); + } + } + } + + // 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 = OutputArguments.ExactNameFix(member.Form); + + // 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); + } + + 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( + 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 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, " + + "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."); + } + + 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\")]."); + } + + /// + /// 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 31938cc1..9d63dfdd 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; @@ -58,14 +62,22 @@ 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; IsReturnValue = member.IsReturnValue; Wire = member.Wire; Named = member.Named; + Candidates = member.Candidates; Display = display; Form = form; } @@ -84,6 +96,15 @@ 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; + /// 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; @@ -95,6 +116,26 @@ public OutputMember(OutputMember member, string display, OutputForm form) /// 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); } /// @@ -110,6 +151,10 @@ enum OutputForm : byte /// CaptureOutput, CaptureOutputDecimal and /// CaptureReturn. Capture, + + /// Output<T> and OutputDecimal, which declare + /// the outputs of a definition. + Definition, } /// @@ -157,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). /// @@ -308,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); } /// @@ -347,15 +448,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,15 +627,26 @@ 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 == OutputForm.Capture - ? $"CaptureOutput<{Shape.TypeName(typeof(T))}>(\"{name}\")" - : $"The output parameter '{name}'"; + string display = form switch + { + OutputForm.Capture + => $"CaptureOutput(out DbCapture<{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( @@ -550,7 +657,8 @@ public static OutputLayout Get( wire, display, named: true, - form)); + form, + candidates)); } /// @@ -566,27 +674,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( @@ -601,17 +700,20 @@ 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 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) + string? display = null, + OutputForm form = OutputForm.Execute, + ImmutableArray candidates = default) { Debug.Assert(Reason == OutputValueRefusal.DecimalNeedsShape); - OutputForm form = display is null - ? OutputForm.Execute - : OutputForm.Capture; display ??= $"The output parameter '{name}'"; return new( new OutputMember( @@ -621,45 +723,31 @@ 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) { 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}.", @@ -718,6 +806,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. /// @@ -726,7 +834,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]; @@ -747,7 +855,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. @@ -818,6 +926,90 @@ 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. + /// + /// 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(out DbCapture<{type}> x, {argument})", + 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(out DbCapture x, 19, 4, {argument})", + 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(out DbCapture x, 19, 4, {argument})", + 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. @@ -842,11 +1034,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. @@ -868,11 +1057,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) { @@ -908,15 +1094,21 @@ 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 with CaptureOutputDecimal(out DbCapture " + + $"{name}, precision, scale), which gives 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/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 e4f699a4..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 @@ -128,3 +112,51 @@ 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 +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> +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..32392900 --- /dev/null +++ b/Tests/Open.Database.Extensions.Core.Tests/BoundCallCaptureCompileTests.cs @@ -0,0 +1,178 @@ +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)); + } + + [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 new file mode 100644 index 00000000..e97a60cd --- /dev/null +++ b/Tests/Open.Database.Extensions.Core.Tests/CaptureDefinitionLocalDbTests.cs @@ -0,0 +1,586 @@ +using Microsoft.Data.SqlClient; +using System.ComponentModel.DataAnnotations.Schema; +using System.Threading.Tasks.Dataflow; + +#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 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() + { + 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(); + // 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) + { + if (!e.Exception.ToString().Contains(missing, StringComparison.Ordinal)) + { + return; + } + + lock (unobserved) + { + unobserved.Add(e.Exception); + } + } + TaskScheduler.UnobservedTaskException += Handler; + try + { + MappedQuery query = DbQuery + .Procedure("dbo." + 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); + } + + [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/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..587c2411 --- /dev/null +++ b/Tests/Open.Database.Extensions.Core.Tests/CaptureNameLocalDbTests.cs @@ -0,0 +1,264 @@ +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_AndIsRefusedBeforeTheRun() + { + 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; + + // 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.Contains("IdOnly.Id reads '@id'", ex.Message); + Assert.Contains("an input parameter (mode IN)", ex.Message); + } + + [Fact] + public static async Task ACapture_NamedAfterAnInput_IsSentAsOutput_AndIsRefusedBeforeTheRun() + { + 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; + + // 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.Contains("CaptureOutput(out DbCapture id) reads '@id'", ex.Message); + Assert.Contains("an input parameter (mode IN)", ex.Message); + 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..0d69550f --- /dev/null +++ b/Tests/Open.Database.Extensions.Core.Tests/CaptureNameTests.cs @@ -0,0 +1,394 @@ +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")] + 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("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); + + [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); + + [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..fd854f39 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)); @@ -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); } @@ -272,7 +281,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,13 +325,27 @@ 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); 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] @@ -340,14 +363,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 +406,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 +438,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 +453,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 +480,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 +510,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 +533,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 +555,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 +568,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 +585,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 +610,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 +630,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 +648,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 +669,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 +692,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 +725,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 +741,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 +756,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 +844,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 +855,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 +872,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 +907,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 +929,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 +953,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 +979,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 +1009,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 +1044,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 +1070,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 +1085,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 +1107,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/OutputDefinitionTests.cs b/Tests/Open.Database.Extensions.Core.Tests/OutputDefinitionTests.cs new file mode 100644 index 00000000..4e359fed --- /dev/null +++ b/Tests/Open.Database.Extensions.Core.Tests/OutputDefinitionTests.cs @@ -0,0 +1,514 @@ +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 ---- + + // 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() + { + 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 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() + { + 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)); + } +} 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)); 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..ad38b73f --- /dev/null +++ b/Tests/Open.Database.Extensions.LegacyCompiler.Tests/BoundCallCaptureBindingTests.cs @@ -0,0 +1,113 @@ +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(); + // 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) + .CaptureOutput(out existing) + .CaptureReturn(out DbCapture code); + BoundCall> b = scalar.Using(connection) + .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); + } + + [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); + + Typed>(amount); + Typed>(fee); + Typed>(scalarAmount); + Typed>(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"); + + Typed>(whatever); + Typed>(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); + + 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; + } +} diff --git a/docsite/articles/expressive-commands.md b/docsite/articles/expressive-commands.md index 98220601..f056ec75 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 @@ -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)`. @@ -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,14 +217,24 @@ 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. - **Checked before the run.** When the procedure's parameter metadata is available (SQL Server, and any provider whose ADO.NET `ProcedureParameters` schema collection answers), a member on a parameter whose mode is `IN` (an input parameter), and a `decimal` member whose scale is lower than the parameter's, throw `InvalidOperationException` before the command runs, naming the member, the parameter and the fix. A higher scale passes, and no precision is checked. The metadata only checks: it never supplies a value, a type or a scale. It is read once per procedure, only for a call that reads an output parameter. Without it the call runs and the provider's own error applies. One value, and a decimal with its precision and scale: +[!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: @@ -234,21 +252,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 the command: [!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. 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)] + +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 3bb6c113..58ee72c2 100644 --- a/docsite/articles/release-notes.md +++ b/docsite/articles/release-notes.md @@ -11,8 +11,10 @@ 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). -- **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). +- **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 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 2ee83068..459a01f6 100644 --- a/docsite/samples/OutputParameters.cs +++ b/docsite/samples/OutputParameters.cs @@ -4,22 +4,46 @@ 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, pointing Blog at them through ConnectionVariable. public static class OutputParameters { - static readonly SqlConnectionFactory Blog = new(@"Server=(localdb)\MSSQLLocalDB;Database=Blog;Integrated Security=true"); + public const string ConnectionVariable = "SAMPLES_BLOG_CONNECTION"; - #region sql_server_output_model + 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. // 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 Blog - .StoredProcedure("[dbo].[AddPost]") + 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]") .AddParam(title) .ExecuteOutputAsync(cancellationToken); @@ -27,32 +51,61 @@ 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) { #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 - _ = total; - _ = maybe; - - return id; + return (id, total, maybe); } #region sql_server_output_decimal @@ -61,32 +114,78 @@ 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) { - List rows = await Blog - .StoredProcedure("[dbo].[PagePosts]") + // The capture is per call: after Using and the parameters, never on + // the stored definition. + List rows = await PagePosts.Using(Blog) .AddParam(page) - .Map() - .CaptureOutput("total", out DbCapture total) + .CaptureOutput(out DbCapture total) .ToListAsync(cancellationToken); // Filled by the time the terminal's task completes: await it after. @@ -94,14 +193,72 @@ public static async Task Page( } #endregion - #region sql_server_output_capture_return + #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) + .ToListAsync(cancellationToken); + + return new PostPage(rows, await total); + } + #endregion + + #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) { - // On the command: the query Map makes runs it, and fills it. - List archived = await Blog - .StoredProcedure("[dbo].[ArchivePosts]") + // 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 capture is filled when the Map query finishes. + List archived = await Blog.StoredProcedure("[dbo].[ArchivePosts]") .AddParam(before) .CaptureReturn(out DbCapture status) .Map() @@ -118,15 +275,50 @@ 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 = Blog - .StoredProcedure("[dbo].[ExportPosts]") - .Map() - .CaptureOutput("exported", out DbCapture exported) + IAsyncEnumerable rows = ExportPosts.Using(Blog) + .CaptureOutput(out DbCapture exported) .ToPooledStream(cancellationToken); await foreach (PostRow row in rows) @@ -142,7 +334,83 @@ await writer.WriteLineAsync( } #endregion - public static async Task Raw( + #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) + .ToPooledStream(cancellationToken); + + await foreach (PostRow row in rows) + { + await writer.WriteLineAsync( + row.Title.AsMemory(), + cancellationToken); + } + + 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 (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( + 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<(int Id, int ReturnCode)> Raw( string title, CancellationToken cancellationToken) { @@ -150,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); @@ -166,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 new file mode 100644 index 00000000..3eb2e2f5 --- /dev/null +++ b/docsite/samples/OutputParametersSqlServer.cs @@ -0,0 +1,115 @@ +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..1f3a9dc4 100644 --- a/docsite/samples/Program.cs +++ b/docsite/samples/Program.cs @@ -606,6 +606,67 @@ 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. + // 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); + 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"); + 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"]), + "output parameters: a capture on a stream is filled when the loop ends, on a definition and ad hoc"); } }