diff --git a/Source/Core/Capture.cs b/Source/Core/Capture.cs index 98e8d8fe..17c77705 100644 --- a/Source/Core/Capture.cs +++ b/Source/Core/Capture.cs @@ -408,24 +408,14 @@ sealed class CaptureSet : CaptureHolder /// The new capture. /// when it is attached on a /// mapped query. - /// Whether the command is a stored - /// procedure. /// The new set. - /// The capture reads the return - /// code of a command that is not a stored procedure, or reads what another - /// capture reads. + /// The capture reads what + /// another capture reads. public static CaptureSet With( CaptureSet? set, ICaptureSource source, - bool onQuery, - bool isProcedure) + bool onQuery) { - if (source.ReadsReturn && !isProcedure) - { - throw new InvalidOperationException( - CaptureMessages.NotProcedure(source)); - } - if (set is null) return new([source], onQuery); string noun = onQuery ? "query" : "command"; @@ -435,9 +425,67 @@ public static CaptureSet With( return new([.. set.Sources, source], onQuery || set.OnQuery); } + /// + /// 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. + /// + /// The command's captures. + /// The query's own captures. + /// A set of the command's sources, then the query's own. + /// A capture of the command + /// and one of the query read the same output or the return code: the + /// command got its capture after the query was made. + public static CaptureSet Combine(CaptureSet command, CaptureSet own) + { + foreach (ICaptureSource first in command.Sources) + { + foreach (ICaptureSource second in own.Sources) + ThrowIfSameOwner(first, second, "query"); + } + + return new([.. command.Sources, .. own.Sources], onQuery: true); + } + + /// + /// The last set made by , with the command's set + /// it was made for. + /// + sealed class Combination(CaptureSet command, CaptureSet result) + { + public readonly CaptureSet Command = command; + + public readonly CaptureSet Result = result; + } + + Combination? _combined; + + /// + /// Gets what a run fills: the command's captures as they are now, + /// combined with these (see ). + /// + /// + /// The last answer is kept for the command's set it was made for, so the + /// calls of one run (a stream and its reader, say) get the same set. + /// + /// The command's captures now. + /// The set the run claims. + /// See + /// . + public CaptureSet CombinedWith(CaptureSet command) + { + Combination? last = Volatile.Read(ref _combined); + if (last is not null && ReferenceEquals(last.Command, command)) + return last.Result; + + // Two threads may both combine: the sets are the same. + var made = new Combination(command, Combine(command, this)); + Volatile.Write(ref _combined, made); + return made.Result; + } + // One owner per output and per return code: a model reads every output, so // it shares them with no other capture. - static void ThrowIfSameOwner( + public static void ThrowIfSameOwner( ICaptureSource first, ICaptureSource second, string noun) @@ -983,4 +1031,18 @@ public static string NotFromCommand(ICaptureSource source, Type reader) + $"this query reads from {reader.Name}, which cannot. " + "Build it from an expressive command, " + "or read the outputs with ExecuteOutputAsync."; + + public static string ReplacedReader(string display, Type command) + => $"{display} reads through the library's reader, " + + $"which {command.Name} replaces by re-implementing IExecuteReader, " + + "so the outputs would never be read. " + + "Capture on a command that does not re-implement IExecuteReader, " + + "or read the outputs with ExecuteOutputAsync."; + + public static string ReplacementUnknown(Type command, string reason) + => $"Could not tell whether {command.Name} re-implements " + + $"IExecuteReader, which a capture needs to know ({reason}). " + + "Read the outputs with ExecuteOutputAsync, " + + "or capture on a command type that can be examined " + + "(reflection on its interfaces must be allowed)."; } diff --git a/Source/Core/ExpressiveCommand.cs b/Source/Core/ExpressiveCommand.cs index b898fb01..88034c81 100644 --- a/Source/Core/ExpressiveCommand.cs +++ b/Source/Core/ExpressiveCommand.cs @@ -135,4 +135,11 @@ protected override void AddParams(IDbCommand command) else if (p.NullDbType is { } nullType) np.DbType = nullType; // a NULL carries no type, so give it the argument's } } + + /// + /// Gets whether this is exactly , which a capture + /// needs no lookup for. + /// + internal override bool IsLibraryCommand + => GetType() == typeof(ExpressiveCommand); } diff --git a/Source/Core/ExpressiveCommandBase.Capture.cs b/Source/Core/ExpressiveCommandBase.Capture.cs index 76ddd539..4d9fb0f7 100644 --- a/Source/Core/ExpressiveCommandBase.Capture.cs +++ b/Source/Core/ExpressiveCommandBase.Capture.cs @@ -17,9 +17,12 @@ interface ICaptureRunner /// . CaptureSet? Captures { get; } - /// Gets whether the command is a stored procedure, which has a - /// return code. - bool IsProcedure { get; } + /// Gets whether the command's type re-implements + /// , which a capture cannot read + /// through. + /// The type could not be + /// examined. + bool ReplacesReader { get; } /// Executes a reader on the command, filling the given /// captures. @@ -97,6 +100,8 @@ public TThis CaptureOutput(out DbCapture output) /// /// + /// public TThis CaptureOutput(string name, out DbCapture value) { @@ -114,6 +119,8 @@ public TThis CaptureOutput(string name, out DbCapture value) /// /// + /// public TThis CaptureOutput( string name, @@ -137,6 +144,8 @@ public TThis CaptureOutput( /// /// + /// public TThis CaptureOutputDecimal( string name, @@ -173,14 +182,24 @@ void Attach(ICaptureSource source) => _captures = CaptureSet.With( _captures, source, - onQuery: false, - Type == CommandType.StoredProcedure); + onQuery: false); CaptureSet? ICaptureRunner.Captures => _captures; - bool ICaptureRunner.IsProcedure - => Type == CommandType.StoredProcedure; + /// + /// Gets whether this is exactly one of the library's own command types, + /// which never re-implement the reader, so a capture needs no lookup. + /// + /// + /// Overridden by each concrete library command as an exact type test + /// (those types are not sealed, and a subclass is looked up). + /// + internal virtual bool IsLibraryCommand + => false; + + bool ICaptureRunner.ReplacesReader + => !IsLibraryCommand && ReaderReplacement.Of(GetType()); ValueTask ICaptureRunner.ExecuteReaderAsync( CaptureHolder captures, @@ -234,8 +253,8 @@ async ValueTask ExecuteCapturedAsync( "ExecuteOutputAsync refuses a command that carries a capture " + "at its call."); - // The kind was checked at the capture call; the command's type can - // change after it. + // Checked here, not at the capture call: the command's type can be + // set after a capture is added. if (run.Set.ReadsReturn && Type != CommandType.StoredProcedure) { throw run.Set.NotProcedure(); diff --git a/Source/Core/ExpressiveCommandBase.Output.cs b/Source/Core/ExpressiveCommandBase.Output.cs index fa7b5fae..8ec985a3 100644 --- a/Source/Core/ExpressiveCommandBase.Output.cs +++ b/Source/Core/ExpressiveCommandBase.Output.cs @@ -95,7 +95,7 @@ static async (cmd, _, run) => /// and reads one output parameter, converted to . /// /// - /// + /// /// /// /// @@ -220,7 +220,7 @@ static async ValueTask NotNullAsync(string name, ValueTask va /// /// /// - /// + /// /// /// /// @@ -411,7 +411,15 @@ void ResolveOutputs(OutputRun run, NameSet? names) continue; } - resolved[i] = (member.Exact ? real!.Find(member.Name)?.Real : real!.Match(member.Name, Command, member.Display)) + 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); } @@ -425,7 +433,9 @@ void ResolveOutputs(OutputRun run, NameSet? names) 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. " - + "Name each member's parameter with [Column(\"name\")], or remove one of them."); + + (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.")); } } diff --git a/Source/Core/ExpressiveCommandBase.cs b/Source/Core/ExpressiveCommandBase.cs index f8386fa0..5009f7c3 100644 --- a/Source/Core/ExpressiveCommandBase.cs +++ b/Source/Core/ExpressiveCommandBase.cs @@ -396,6 +396,10 @@ protected TThis AddParam(Param param) /// A you pass always wins. /// The overloads have no type to use: /// pass a database type. + /// A passed as the value, as in + /// AddParam("@id", DbType.Int32) on a command whose database type + /// is not (the SQL Server commands), is a value, and + /// is sent as one: pass the database type as the third argument. /// /// is . /// is empty or white space. @@ -1947,6 +1951,13 @@ ValueTask IExecuteReader.ExecuteReaderAsync(Func /// . /// /// + /// + /// At the call, before anything runs and not in the returned task: + /// is a model, which cannot hold the return code. + /// Use int (or int?, long, an enum), or read it with + /// a ReturnValue member of an output model + /// (ExecuteOutputAsync<TOut>()). + /// /// public ValueTask ExecuteReturnAsync( CancellationToken cancellationToken = default) diff --git a/Source/Core/ExpressiveDbCommand.cs b/Source/Core/ExpressiveDbCommand.cs index f216c92d..07ff69c9 100644 --- a/Source/Core/ExpressiveDbCommand.cs +++ b/Source/Core/ExpressiveDbCommand.cs @@ -148,4 +148,11 @@ protected override void AddParams(DbCommand command) else if (p.NullDbType is { } nullType) np.DbType = nullType; // a NULL carries no type, so give it the argument's } } + + /// + /// Gets whether this is exactly , which a capture + /// needs no lookup for. + /// + internal override bool IsLibraryCommand + => GetType() == typeof(ExpressiveDbCommand); } diff --git a/Source/Core/MappedQuery.Capture.cs b/Source/Core/MappedQuery.Capture.cs index 19c3c7b0..b4fd321c 100644 --- a/Source/Core/MappedQuery.Capture.cs +++ b/Source/Core/MappedQuery.Capture.cs @@ -16,7 +16,18 @@ readonly partial struct MappedQueryCore // CancelOnEarlyStop(). Without a capture it costs a type check of the // command and a field read. CaptureHolder? Captured() - => _captures ?? (_command as ICaptureRunner)?.Captures; + { + if (_captures is not CaptureSet own) + { + return _captures ?? (_command as ICaptureRunner)?.Captures; + } + + // The command's captures as they are now, then the query's own: a + // capture added to the command after the query was made is filled too. + return _command is ICaptureRunner { Captures: { } command } + ? own.CombinedWith(command) + : own; + } /// /// Gets the run a stream or a buffer claimed, or . @@ -29,11 +40,15 @@ public CaptureRun? CapturedRun /// /// The capture, its arguments checked. /// A copy of the query that carries the capture. - /// A default value, a capture - /// of the return code of a command that is not a stored procedure, or a + /// A default value, or a /// capture that reads what another one reads. + /// The command's type could not + /// be examined for a re-implemented reader (see + /// ). /// The query does not read from an - /// expressive command. + /// expressive command, or the command's type re-implements + /// , which a capture cannot read + /// through. public MappedQueryCore WithCapture(ICaptureSource source) { EnsureCommand(); @@ -47,12 +62,27 @@ public MappedQueryCore WithCapture(ICaptureSource source) throw new NotSupportedException( CaptureMessages.NotFromCommand(source, _command!.GetType())); } + if (runner.ReplacesReader) + { + throw new NotSupportedException( + CaptureMessages.ReplacedReader( + source.Display, + _command!.GetType())); + } + + // The query keeps only its own. A run takes the command's captures as + // they are then, first, so the query and the command share the first + // capture and one run claims them. A conflict with what the command + // has now is refused here, without storing it. + if (runner.Captures is { } current) + { + foreach (ICaptureSource other in current.Sources) + CaptureSet.ThrowIfSameOwner(other, source, "query"); + } - // Appended to the command's, so the query and the command share the - // first capture, and one run claims them. CaptureSet captures = CaptureSet.With( - _captures as CaptureSet ?? runner.Captures, - source, onQuery: true, runner.IsProcedure); + _captures as CaptureSet, + source, onQuery: true); return new( _command, _call, _source, _skip, _take, Options, Config, captures); @@ -137,6 +167,8 @@ public MappedQuery CaptureOutput(out DbCapture output) /// /// + /// public MappedQuery CaptureOutput( string name, @@ -156,6 +188,8 @@ public MappedQuery CaptureOutput( /// /// + /// public MappedQuery CaptureOutput( string name, @@ -179,6 +213,8 @@ public MappedQuery CaptureOutput( /// /// + /// public MappedQuery CaptureOutputDecimal( string name, diff --git a/Source/Core/MappedQuery.cs b/Source/Core/MappedQuery.cs index 05865a93..67c034cc 100644 --- a/Source/Core/MappedQuery.cs +++ b/Source/Core/MappedQuery.cs @@ -495,15 +495,56 @@ 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). - // It is taken even when a subclass re-implements IExecuteReader, so the - // claim and the completion never depend on that override. + // 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. ValueTask ExecuteReaderAsync(TState state, Func> transform, CommandBehavior behavior, CancellationToken token) - => Captured() is { } captures - ? ((ICaptureRunner)_command!).ExecuteReaderAsync( - captures, state, transform, behavior, token) - : _call.IsBound + { + if (Captured() is not { } captures) + { + return _call.IsBound ? _call.RunAsync(state, transform, behavior, token) : Command.ExecuteReaderAsync(state, transform, behavior, token); + } + + var runner = (ICaptureRunner)_command!; + Exception? refusal = ReaderRefusal(runner, captures, token); + return refusal is null + ? runner.ExecuteReaderAsync( + captures, state, transform, behavior, token) + : new ValueTask(Task.FromException(refusal)); + } + + // The exception that refuses a captured run on a command that replaces its + // reader, or null. A type that cannot be examined is refused too. + Exception? ReaderRefusal( + ICaptureRunner runner, + CaptureHolder captures, + CancellationToken token) + { + Exception refusal; + try + { + if (!runner.ReplacesReader) + { + return null; + } + + refusal = new InvalidOperationException( + CaptureMessages.ReplacedReader( + captures.Set.Displays, + _command!.GetType())); + } + catch (InvalidOperationException ex) + { + refusal = ex; + } + + return captures.Refuse(refusal, token); + } /// /// Runs an execution that opted in with CancelOnEarlyStop(). diff --git a/Source/Core/NameSet.cs b/Source/Core/NameSet.cs index 26795a07..fe5005c0 100644 --- a/Source/Core/NameSet.cs +++ b/Source/Core/NameSet.cs @@ -25,6 +25,9 @@ sealed class NameSet // One write lock: a match is written once, then only read, and a lock per processor would be most of what a set takes. readonly ConcurrentDictionary _matches = new(concurrencyLevel: 1, capacity: 4, StringComparer.Ordinal); + /// The real name each given name matched, by the name as the caller gave it (see ). + readonly ConcurrentDictionary _nameMatches = new(concurrencyLevel: 1, capacity: 4, StringComparer.Ordinal); + /// Initializes a new instance from the names as the provider reported them (a leading @ is fine); never the default array, but may be empty. /// The names. /// Where a procedure's set is kept (see ). @@ -104,6 +107,33 @@ public int GetHashCode(string obj) return entries.TryGetValue(name, out Entry? found) ? found : null; } + /// + /// The real name that a name given as it is stands for, or when it matches none: the way an argument of AddParam matches, from one candidate that is the name itself. + /// + /// + /// The four tiers, exact first, a lower tier only when no higher one matches. + /// The answer is remembered apart from , which is keyed by argument text. + /// An ambiguity throws and is not remembered. + /// + /// The name as the caller gave it, with or without its @. + /// The procedure's name or the command text, for the message of an ambiguity. + /// What matches, for the message of an ambiguity. + /// What to do about an ambiguity. + /// The real name, or when the name matches none. + /// The name fits more than one parameter equally well. + public string? MatchName(string name, string procedure, string subject, string fix) + { + if (_nameMatches.TryGetValue(name, out string? remembered)) return remembered; + + string bare = name.Length > 0 && name[0] == '@' ? name[1..] : name; + + // Two threads may both match and store: the answer is the same. + string? found = ParameterNames.MatchBareAs([bare], Names, BareNames, name, procedure, subject, fix); + if (_nameMatches.Count < MaxMatches) _nameMatches[name] = found; + + return found; + } + Dictionary BuildEntries() { var entries = new Dictionary(Names.Length, BareComparer.Instance); diff --git a/Source/Core/Output.docs.xml b/Source/Core/Output.docs.xml index 9c57c81f..7dc4c543 100644 --- a/Source/Core/Output.docs.xml +++ b/Source/Core/Output.docs.xml @@ -42,13 +42,21 @@ is empty, white space or a bare @. - + - names the parameter exactly, with or without its @ and in any case. + is matched to a parameter the way the name of AddParam is, with or without its @: exactly, else ignoring case, else ignoring case and underscores, else after one common prefix such as p_ is removed from the declared name; a lower rule applies only when no higher one matches. + A name that matches two parameters by the same rule throws: pass the exact name. A value added under the same name makes it . + + + The name of the output parameter, with or without its @, matched the way the name of AddParam is. + Two captures that match one parameter only through a looser rule fail the run; the same name, ignoring case, fails at the call. + + + A parameter added with a null value is sent as too, @@ -148,15 +156,13 @@ At the call: cannot be read from output parameters (a single value, or a type with no member to set); - or a ReturnValue member reads the return code of a command 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). + or the return code (remove one) (for a capture added to the command after the query was made, when the terminal or stream is called). The type the value converts to, as Map<T>() converts a single column. - The name of the output parameter, with or without its @ and in any case. The capture: await it after the terminal. is . is empty, white space or a bare @. @@ -169,7 +175,6 @@ , which throws on NULL, or a of it, which reads NULL as . - The name of the output parameter, with or without its @ and in any case. 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. @@ -185,7 +190,6 @@ - The name of the output parameter, with or without its @ and in any case. 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 . @@ -201,7 +205,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; or the command is not a stored procedure, which has no return code; + At the call: is a model; or another capture reads the return code. @@ -209,6 +213,9 @@ The command, which carries the capture; its next async terminal fills it. + + A capture of the return code (CaptureReturn, or a model with a ReturnValue member) is refused when the run starts if the command is not a stored procedure, which has no return code: the type can be set after the capture, so the run, not the call, decides. + The capture adds its output parameters when the terminal runs the command, and is complete when the terminal's task is. A query that Map made from this command uses the command's captures too; the first run, by either route, fills them. @@ -217,6 +224,10 @@ A command that carries a capture runs once, with an async terminal only: a synchronous terminal, ExecuteAsync(command => …) and ExecuteOutputAsync throw, and so does a second run, which needs a new command with a new capture. + A command whose type re-implements IExecuteReader cannot carry a capture, which reads through the library's reader. + A capture on the command is refused when a mapped query over it runs: that run throws (and completes the capture with it) before anything is executed. + The command's own terminals do not use the re-implemented reader. + Read the outputs with ExecuteOutputAsync instead. @@ -225,11 +236,16 @@ A copy of the query that carries the capture; its async terminal fills it. - The capture belongs to the copy, which also shares any capture on its command, and is complete when the terminal's task is. + A capture of the return code is refused when the run starts if the command is not a stored procedure. + 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 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. A loop that stops early (a ) still fills it, since the read is closed, not canceled. That stop waits for the server to finish sending the response, which closing the reader reads through; - the stall timeout does not bound that wait. + the stall timeout does not bound that wait, so a response that is slow or large keeps the loop's exit waiting. + A token the caller passed (to the call, the enumerator or the command) still cancels the read, and the capture is then canceled. + To stop without waiting, do not capture on a stream that may stop early; read the outputs with ExecuteOutputAsync instead. A query that carries a capture runs once, with an async terminal only: @@ -238,7 +254,7 @@ one from a DbQuery definition throws. - The query is not built from an expressive command. + The query is not built from an expressive command, or its command re-implements IExecuteReader (thrown at the call). diff --git a/Source/Core/OutputLayout.cs b/Source/Core/OutputLayout.cs index b5dfb68b..f657ffd6 100644 --- a/Source/Core/OutputLayout.cs +++ b/Source/Core/OutputLayout.cs @@ -12,7 +12,7 @@ sealed class OutputMember { /// Initializes a member that is sent as an output parameter. /// The member's name, its [Column] name, or the name the caller gave. - /// when names the parameter exactly ([Column], the named form). + /// when names the parameter exactly ([Column]); matches it through the tiers (the named form, and a member without [Column]). /// What the model's map reads the value as: the member's [Column] name, else its name. /// How the parameter is sent. /// The member for the messages: Model.Member, or The output parameter 'name'. @@ -84,7 +84,7 @@ 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; - /// Whether names the parameter exactly, with or without its @ and in any case, never through the tiers. + /// 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; /// What the model's map reads the value as. @@ -539,7 +539,7 @@ public static OutputLayout Get( return new( new OutputMember( name, - exact: true, + exact: false, name, wire, display, @@ -610,7 +610,7 @@ public static OutputLayout Shaped( return new( new OutputMember( name, - exact: true, + exact: false, name, new OutputWire(DbType.Decimal, 0, precision, scale), display, diff --git a/Source/Core/ParameterNames.cs b/Source/Core/ParameterNames.cs index 8fab9fad..f4299332 100644 --- a/Source/Core/ParameterNames.cs +++ b/Source/Core/ParameterNames.cs @@ -303,11 +303,19 @@ static bool ClosesAt(string s, int open, int close) /// The text of the argument, for the message of an ambiguity. /// The procedure's name, for the message of an ambiguity. /// What matches, for the message of an ambiguity; names the argument. - internal static string? MatchBareAs(ImmutableArray candidates, ImmutableArray parameterNames, ImmutableArray bareNames, string expression, string procedure, string? subject) + /// What to do about an ambiguity, ending its message; advises [Column] on the subject, or an explicit AddParam name. + internal static string? MatchBareAs( + ImmutableArray candidates, + ImmutableArray parameterNames, + ImmutableArray bareNames, + string expression, + string procedure, + string? subject, + string? fix = null) { foreach (string candidate in candidates) { - if (Find(expression, procedure, candidate, parameterNames, bareNames, subject) is { } found) return found; + if (Find(expression, procedure, candidate, parameterNames, bareNames, subject, fix) is { } found) return found; } return null; @@ -327,7 +335,7 @@ static bool ClosesAt(string s, int open, int close) _ => "ignoring case and underscores once one parameter prefix (p_, in_, i_, prm_, par_, v_ or a lone p) is removed from the real name", }; - static string? Find(string expression, string procedure, string candidate, ImmutableArray parameterNames, ImmutableArray bareNames, string? subject) + static string? Find(string expression, string procedure, string candidate, ImmutableArray parameterNames, ImmutableArray bareNames, string? subject, string? fix = null) { // Tier 1: exact. Tier 2: ignoring case. Tier 3: ignoring case and underscores. Tier 4: the same without one common parameter prefix. for (int tier = 1; tier <= 4; tier++) @@ -342,7 +350,7 @@ static bool ClosesAt(string s, int open, int close) throw new InvalidOperationException( $"{subject ?? $"The argument '{expression}'"} matches both '{found}' and '{real}' of '{procedure}'. " + $"Its candidate name '{candidate}' fits each of them {TierText(tier)}. " - + $"The procedure declares: {string.Join(", ", parameterNames)}. {(subject is null ? "Name the parameter explicitly: AddParam(\"name\", value)." : $"Name its parameter exactly with [Column(\"name\")] on {subject}.")}"); + + $"The procedure declares: {string.Join(", ", parameterNames)}. {fix ?? (subject is null ? "Name the parameter explicitly: AddParam(\"name\", value)." : $"Name its parameter exactly with [Column(\"name\")] on {subject}.")}"); } found = real; diff --git a/Source/Core/ReaderReplacement.cs b/Source/Core/ReaderReplacement.cs new file mode 100644 index 00000000..d2c189d0 --- /dev/null +++ b/Source/Core/ReaderReplacement.cs @@ -0,0 +1,81 @@ +namespace Open.Database.Extensions; + +// Whether a command type re-implements IExecuteReader, which a capture cannot +// allow: a captured run reads through the library's own reader, so a type that +// replaces that reader would be skipped silently. The answer is a property of +// the type, found once with reflection and kept in a table that does not hold +// the type alive. Only a captured run asks; an uncaptured call never does. +static class ReaderReplacement +{ + // The two answers, as reference values, which the table needs. + static readonly object Replaced = new(); + static readonly object Kept = new(); + + static readonly ConditionalWeakTable Answers = new(); + static readonly ConditionalWeakTable> Lookups = new(); + + /// Gets how many times the type was looked up with + /// reflection. + /// The command type. + /// The count: one per successful lookup, so one after the first + /// captured run of a type that is not a library command; a failed + /// lookup is retried and counted again. + public static int LookupCount(Type type) + => Lookups.TryGetValue(type, out StrongBox? count) + ? Volatile.Read(ref count.Value) + : 0; + + /// Gets whether the type re-implements + /// . + /// The command type. + /// if any method that implements the + /// interface, or an interface that extends it, is declared by a type other + /// than the library's command bases. + /// The lookup failed; the + /// failure is not cached, so the next call looks again. + public static bool Of(Type type) + => ReferenceEquals(Answers.GetValue(type, Detect), Replaced); + + static object Detect(Type type) + { + StrongBox count = Lookups.GetOrCreateValue(type); + Interlocked.Increment(ref count.Value); + + try + { + foreach (Type face in type.GetInterfaces()) + { + if (!typeof(IExecuteReader).IsAssignableFrom(face)) + { + continue; + } + + InterfaceMapping map = type.GetInterfaceMap(face); + foreach (MethodInfo target in map.TargetMethods) + { + if (!IsLibraryBase(target.DeclaringType)) + { + return Replaced; + } + } + } + + return Kept; + } + catch (Exception ex) + { + throw new InvalidOperationException( + CaptureMessages.ReplacementUnknown(type, ex.Message), + ex); + } + } + + // A plain command maps to the constructed base, never the open + // definition; a database command re-lists IExecuteReaderAsync, so it may + // map to either base. + static bool IsLibraryBase(Type? declaring) + => declaring is { IsGenericType: true } + && declaring.GetGenericTypeDefinition() is { } definition + && (definition == typeof(ExpressiveCommandBase<,,,,>) + || definition == typeof(ExpressiveDbCommandBase<,,,,>)); +} diff --git a/Source/MSSqlClient/ExpressiveSqlCommand.cs b/Source/MSSqlClient/ExpressiveSqlCommand.cs index fec8ee3e..d358747c 100644 --- a/Source/MSSqlClient/ExpressiveSqlCommand.cs +++ b/Source/MSSqlClient/ExpressiveSqlCommand.cs @@ -208,4 +208,11 @@ static async Task> ReadNamesAsync(SqlDataReader reader, C while (await reader.ReadAsync(cancellationToken).ConfigureAwait(false)) names.Add(reader.GetString(0)); return names.ToImmutable(); } + + /// + /// Gets whether this is exactly , which a capture + /// needs no lookup for. + /// + internal override bool IsLibraryCommand + => GetType() == typeof(ExpressiveSqlCommand); } diff --git a/Source/SqlClient/ExpressiveSqlCommand.cs b/Source/SqlClient/ExpressiveSqlCommand.cs index 8a755967..b591bd89 100644 --- a/Source/SqlClient/ExpressiveSqlCommand.cs +++ b/Source/SqlClient/ExpressiveSqlCommand.cs @@ -196,4 +196,11 @@ static async Task> ReadNamesAsync(SqlDataReader reader, C while (await reader.ReadAsync(cancellationToken).ConfigureAwait(false)) names.Add(reader.GetString(0)); return names.ToImmutable(); } + + /// + /// Gets whether this is exactly , which a capture + /// needs no lookup for. + /// + internal override bool IsLibraryCommand + => GetType() == typeof(ExpressiveSqlCommand); } diff --git a/Tests/Open.Database.Extensions.Core.Tests/AllocationQuickWinTests.cs b/Tests/Open.Database.Extensions.Core.Tests/AllocationQuickWinTests.cs index 52065eff..7061c394 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/AllocationQuickWinTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/AllocationQuickWinTests.cs @@ -256,12 +256,12 @@ public static void ToDictionary_ANullMapping_ThrowsArgumentNull() .GetMethod("BareNames", BindingFlags.Static | BindingFlags.NonPublic)! .CreateDelegate, ImmutableArray>>(); - static readonly Func, ImmutableArray, ImmutableArray, string, string, string?, string?> MatchBare = ParameterNamesType + static readonly Func, ImmutableArray, ImmutableArray, string, string, string?, string?, string?> MatchBare = ParameterNamesType .GetMethod("MatchBareAs", BindingFlags.Static | BindingFlags.NonPublic)! - .CreateDelegate, ImmutableArray, ImmutableArray, string, string, string?, string?>>(); + .CreateDelegate, ImmutableArray, ImmutableArray, string, string, string?, string?, string?>>(); // The expression and the procedure only feed the message of an ambiguity; they cost nothing when there is none. - static string? Match(ImmutableArray candidates, ImmutableArray parameterNames) => MatchBare(candidates, parameterNames, BareNames(parameterNames), "argument", "dbo.procedure", null); + static string? Match(ImmutableArray candidates, ImmutableArray parameterNames) => MatchBare(candidates, parameterNames, BareNames(parameterNames), "argument", "dbo.procedure", null, null); static readonly ImmutableArray RealNames = [ diff --git a/Tests/Open.Database.Extensions.Core.Tests/CaptureLibraryCommandTests.cs b/Tests/Open.Database.Extensions.Core.Tests/CaptureLibraryCommandTests.cs new file mode 100644 index 00000000..df73a8e3 --- /dev/null +++ b/Tests/Open.Database.Extensions.Core.Tests/CaptureLibraryCommandTests.cs @@ -0,0 +1,41 @@ +extern alias mssql; + +#nullable enable + +namespace Open.Database.Extensions.Tests; + +// The library's own SQL Server commands are decided without a lookup, as the +// base commands are: the exact type test is in each assembly. +[ExcludeFromCodeCoverage] +public static class CaptureLibraryCommandTests +{ + public sealed record Row(int Id); + + // A query capture checks the command's type at the call, so nothing is + // opened or run. + [Fact] + public static void TheSqlCommands_NeedNoLookup_ForACapture() + { +#pragma warning disable CS0618 // System.Data.SqlClient is obsolete; it is one of the two packages under test + using var legacy = new System.Data.SqlClient.SqlConnection(); + _ = new ExpressiveSqlCommand(legacy, CommandType.StoredProcedure, "p") + .Map() + .CaptureOutput("total", out _); + using var connection = new Microsoft.Data.SqlClient.SqlConnection(); + _ = new mssql::Open.Database.Extensions.ExpressiveSqlCommand( + connection, + CommandType.StoredProcedure, + "p") + .Map() + .CaptureOutput("total", out _); + + Assert.Equal( + 0, + ReaderReplacement.LookupCount(typeof(ExpressiveSqlCommand))); +#pragma warning restore CS0618 + Assert.Equal( + 0, + ReaderReplacement.LookupCount( + typeof(mssql::Open.Database.Extensions.ExpressiveSqlCommand))); + } +} diff --git a/Tests/Open.Database.Extensions.Core.Tests/CaptureLocalDbTests.cs b/Tests/Open.Database.Extensions.Core.Tests/CaptureLocalDbTests.cs index a8fed985..da5fb494 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/CaptureLocalDbTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/CaptureLocalDbTests.cs @@ -135,6 +135,31 @@ static async Task TakeOne(IAsyncEnumerable items) } } + // The loop's exit waits for the rest of the response: the output is set + // after 50000 rows, so it arrives only because closing the reader read + // them all. (The fake provider cannot tell: it does not read.) + [Fact] + public static async Task ABreak_AfterOneRow_StillFillsIt_BecauseTheRestIsRead() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = Procedure( + "@total int output", + ManyRows + " set @total = 42;"); + await using SqlConnection connection = await OpenAsync(); + MappedQuery query = connection + .StoredProcedure("dbo." + procedure.Name) + .Map() + .CaptureOutput("total", out DbCapture total); + + await foreach (Row row in query.ToPooledStream(Token)) + { + Assert.Equal(1, row.Id); + break; + } + + Assert.Equal(42, await total); + } + [Fact] public static async Task ALaterError_FaultsIt_WithTheProvidersError() { @@ -214,6 +239,71 @@ public static async Task AModel_WithADecimal_AndTheNamedDecimal() Assert.Equal(2, await count); } + [Fact] + public static async Task ANamedCapture_FindsItsParameter_ThroughTheTiers() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = Procedure( + "@total_count int output", + "select n as Id from (values (1), (2)) v(n); set @total_count = 2;"); + await using SqlConnection connection = await OpenAsync(); + + List rows = await connection.StoredProcedure("dbo." + procedure.Name) + .CaptureOutput("totalCount", out DbCapture total) + .Map() + .ToListAsync(Token); + + Assert.Equal(2, rows.Count); + Assert.Equal(2, await total); + } + + [Fact] + public static async Task TwoNamedCaptures_OnOneParameter_FailTheRun() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = Procedure( + "@total_count int output", + "select n as Id from (values (1), (2)) v(n); set @total_count = 2;"); + await using SqlConnection connection = await OpenAsync(); + + // 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) + .Map(); + + var ex = await Assert.ThrowsAsync(async () => await query.ToListAsync(Token)); + Assert.Contains("both resolve to the output parameter", ex.Message); + Assert.Contains("Name one of them exactly", ex.Message); + await Assert.ThrowsAsync(async () => await first); + await Assert.ThrowsAsync(async () => await second); + } + + // The named form finds @p_total by the common-prefix rule (the fourth + // tier), on a capture and on ExecuteOutputAsync. + [Fact] + public static async Task ANamedCapture_FindsAPrefixedParameter() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = Procedure( + "@p_total int output", + "select n as Id from (values (1), (2)) v(n); set @p_total = 2;"); + await using SqlConnection connection = await OpenAsync(); + string name = "dbo." + procedure.Name; + + List rows = await connection.StoredProcedure(name) + .CaptureOutput("total", out DbCapture total) + .Map() + .ToListAsync(Token); + + Assert.Equal(2, rows.Count); + Assert.Equal(2, await total); + Assert.Equal( + 2, + await connection.StoredProcedure(name) + .ExecuteOutputAsync("total", Token)); + } + // A text command's @name OUTPUT marker. [Fact] public static async Task ATextCommand_FillsItThroughItsMarker() diff --git a/Tests/Open.Database.Extensions.Core.Tests/CaptureStreamTests.cs b/Tests/Open.Database.Extensions.Core.Tests/CaptureStreamTests.cs index 1724fbad..b434ed45 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/CaptureStreamTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/CaptureStreamTests.cs @@ -76,14 +76,19 @@ public static async Task AStall_FaultsIt_WithTheTimeout(int bufferSize) IAsyncEnumerable rows = Query(c, out DbCapture total) .StreamBuffered(TimeSpan.FromMilliseconds(50), bufferSize, Token); - await Assert.ThrowsAsync(async () => + var thrown = await Assert.ThrowsAsync(async () => { await foreach (Row _ in rows) { await Task.Delay(400, Token); } }); - await Assert.ThrowsAsync(async () => await total); + + // The capture faults with the loop's own exception: same type and + // message. + var captured = await Assert.ThrowsAsync( + async () => await total); + Assert.Equal(thrown.Message, captured.Message); } [Theory] @@ -566,8 +571,8 @@ public static async Task ACanceledToken_ThrowsAtTheCall_AndArmsNothing() // ---- a command that re-implements its reader ------------------------- - // Its own reader function never adds the outputs: a captured run takes - // the command's own reader path, so the capture is claimed and filled. + // A captured run reads through the library's reader, so a command type + // that replaces it is refused, never bypassed. sealed class OwnReaderCommand(CaptureConnection connection) : ExpressiveCommand( () => connection, @@ -593,52 +598,186 @@ async ValueTask } } + sealed class PlainCommand(CaptureConnection connection) + : ExpressiveCommand( + () => connection, + CommandType.StoredProcedure, + "p"); + + sealed class PlainDbCommand(CaptureConnection connection) + : ExpressiveDbCommand( + () => connection, + CommandType.StoredProcedure, + "p"); + + const string Replaced = "re-implementing IExecuteReader"; + + static MappedQuery OnCommand( + OwnReaderCommand command, + out DbCapture total) + => command.CaptureOutput("total", out total) + .Map(); + [Fact] - public static async Task ACommandThatReimplementsItsReader_StillFillsIt() + public static void AQueryCapture_OnAReimplementingCommand_IsRefusedAtTheCall() { var c = new CaptureConnection(("total", 9)); var command = new OwnReaderCommand(c); + MappedQuery query = command.Map(); - List rows = await command.CaptureOutput( - "total", - out DbCapture total) - .Map() - .ToListAsync(Token); - - Assert.Equal(3, rows.Count); - Assert.Equal(9, await total); + var ex = Assert.Throws( + () => query.CaptureOutput("total", out _)); + Contains( + ex, + nameof(OwnReaderCommand), + Replaced, + "read the outputs with ExecuteOutputAsync"); + Assert.Throws( + () => query.CaptureReturn(out _)); + Assert.Throws( + () => query.Skip(1).CaptureOutput("total", out _)); Assert.Equal(0, command.OwnReads); + Assert.Equal(0, c.Executed); + } - // Without a capture, its own reader runs as before. - var plain = new OwnReaderCommand(c); - Assert.Single(await plain.Map() - .ToListAsync(Token)); - Assert.Equal(1, plain.OwnReads); + public static TheoryData RefusedTerminals + => new( + "ToListAsync", "AnyAsync", "SingleResult", "AsObjectArrays", + "Stream", "ToPooledBuffer", + "ToChannelReader", "AsSourceBlock", "ToTargetBlock"); + + // The command's capture reaches the one choke of the mapped query, at the + // first read of each terminal, and refuses there. + [Theory] + [MemberData(nameof(RefusedTerminals))] + public static async Task ACommandCapture_OnAReimplementingCommand_IsRefusedAtTheRun( + string terminal) + { + var c = new CaptureConnection(("total", 9)); + var command = new OwnReaderCommand(c); + DbCapture total; + var forever = Timeout.InfiniteTimeSpan; + + Func run; + switch (terminal) + { + case "ToListAsync": + { + MappedQuery query = OnCommand(command, out total); + run = async () => await query.ToListAsync(Token); + break; + } + case "Stream": + { + MappedQuery query = OnCommand(command, out total); + run = async () => + { + await foreach (Row _ in query.Stream(forever, Token)) { } + }; + break; + } + case "ToPooledBuffer": + { + MappedQuery query = OnCommand(command, out total); + run = async () => + { + using PooledBuffer buffer = query.ToPooledBuffer(Token); + await foreach (Row _ in buffer.AsAsyncEnumerable(Token)) { } + }; + break; + } + case "ToChannelReader": + { + MappedQuery query = OnCommand(command, out total); + ChannelReader reader = query.ToChannelReader(Token); + run = async () => + { + await foreach (Row _ in reader.ReadAllAsync(Token)) { } + }; + break; + } + case "AsSourceBlock": + { + MappedQuery query = OnCommand(command, out total); + IReceivableSourceBlock block = query.AsSourceBlock(Token); + run = async () => await block.Completion; + break; + } + case "ToTargetBlock": + { + MappedQuery query = OnCommand(command, out total); + var block = new BufferBlock(); + run = async () => await query.ToTargetBlock(block, Token); + break; + } + case "AnyAsync": + { + MappedQuery query = OnCommand(command, out total); + run = async () => await query.AnyAsync(Token); + break; + } + case "AsObjectArrays": + { + command.CaptureOutput("total", out total); + run = async () => + await command.AsObjectArrays().ToListAsync(Token); + break; + } + default: + { + command.CaptureOutput("total", out total); + run = async () => await command.SingleResult() + .Map() + .ToListAsync(Token); + break; + } + } + + var ex = await Assert.ThrowsAsync(run); + Contains( + ex, + nameof(OwnReaderCommand), + Replaced, + "read the outputs with ExecuteOutputAsync"); + + // Never pending: the capture completed with the same refusal. + Assert.True(total.AsTask().IsFaulted); + Assert.Same( + ex, + await Assert.ThrowsAsync( + async () => await total)); + Assert.Equal(0, command.OwnReads); + Assert.Equal(0, c.Executed); } + // CancelOnEarlyStop is refused before the reader is asked, so its own + // message holds; the run is still refused. [Fact] - public static async Task ACommandThatReimplementsItsReader_OnAQueryCapture() + public static async Task ACommandCapture_WithCancelOnEarlyStop_KeepsItsOwnMessage() { var c = new CaptureConnection(("total", 9)); var command = new OwnReaderCommand(c); + MappedQuery query = OnCommand(command, out DbCapture total) + .CancelOnEarlyStop(); - List rows = await command.Map() - .CaptureOutput("total", out DbCapture total) - .ToListAsync(Token); - - Assert.Equal(3, rows.Count); - Assert.Equal(9, await total); + var ex = await Assert.ThrowsAsync( + async () => await query.ToListAsync(Token)); + Contains(ex, "cannot be used with CancelOnEarlyStop()"); + Assert.Same( + ex, + await Assert.ThrowsAsync( + async () => await total)); Assert.Equal(0, command.OwnReads); + Assert.Equal(0, c.Executed); } - // The synchronous path is refused before its own reader is asked. + // The synchronous refusal comes first, so it keeps its message. [Fact] - public static void ACommandThatReimplementsItsReader_RefusesSync() + public static void ACommandCapture_OnAReimplementingCommand_RefusesSync() { var c = new CaptureConnection(("total", 9)); var command = new OwnReaderCommand(c); - MappedQuery query = command.Map() - .CaptureOutput("total", out DbCapture total); + MappedQuery query = OnCommand(command, out DbCapture total); Contains( Assert.Throws(() => query.ToList()), @@ -651,6 +790,97 @@ public static void ACommandThatReimplementsItsReader_RefusesSync() "has not started"); } + // Without a capture, its own reader runs as before. + [Fact] + public static async Task AReimplementingCommand_WithoutACapture_RunsItsOwnReader() + { + var c = new CaptureConnection(("total", 9)); + var plain = new OwnReaderCommand(c); + + Assert.Single(await plain.Map() + .ToListAsync(Token)); + Assert.Equal(1, plain.OwnReads); + } + + // The way out the docs give a re-implementing command: it reads the + // outputs through the library, not through its own reader. + [Fact] + public static async Task AReimplementingCommand_ReadsItsOutputs_WithExecuteOutputAsync() + { + var c = new CaptureConnection(("total", 9)); + var command = new OwnReaderCommand(c); + + Assert.Equal( + 9, + await command.ExecuteOutputAsync("total", Token)); + Assert.Equal(0, command.OwnReads); + Assert.Equal(1, c.Executed); + } + + [Fact] + public static async Task APlainSubclass_FillsItsCapture_OnBothForms() + { + var c = new CaptureConnection(("total", 9)); + + List onCommand = await new PlainCommand(c) + .CaptureOutput("total", out DbCapture first) + .Map() + .ToListAsync(Token); + Assert.Equal(3, onCommand.Count); + Assert.Equal(9, await first); + + List onQuery = await new PlainCommand(c) + .Map() + .CaptureOutput("total", out DbCapture second) + .ToListAsync(Token); + Assert.Equal(3, onQuery.Count); + Assert.Equal(9, await second); + + List onDbCommand = await new PlainDbCommand(c) + .CaptureOutput("total", out DbCapture third) + .Map() + .ToListAsync(Token); + Assert.Equal(3, onDbCommand.Count); + Assert.Equal(9, await third); + + List onDbQuery = await new PlainDbCommand(c) + .Map() + .CaptureOutput("total", out DbCapture fourth) + .ToListAsync(Token); + Assert.Equal(3, onDbQuery.Count); + Assert.Equal(9, await fourth); + + // One lookup per type, however many captured runs. + Assert.Equal(1, ReaderReplacement.LookupCount(typeof(PlainCommand))); + Assert.Equal(1, ReaderReplacement.LookupCount(typeof(PlainDbCommand))); + } + + // The library's own command types are decided without a lookup. + [Fact] + 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) + .Map() + .ToListAsync(Token); + Assert.Equal(9, await first); + + await new ExpressiveDbCommand(() => c, CommandType.StoredProcedure, "p") + .Map() + .CaptureOutput("total", out DbCapture second) + .ToListAsync(Token); + Assert.Equal(9, await second); + + Assert.Equal( + 0, + ReaderReplacement.LookupCount(typeof(ExpressiveCommand))); + Assert.Equal( + 0, + ReaderReplacement.LookupCount(typeof(ExpressiveDbCommand))); + } + // ---- an argument guard ----------------------------------------------- // The guard throws before anything is armed (decision 9): the capture diff --git a/Tests/Open.Database.Extensions.Core.Tests/CaptureTests.cs b/Tests/Open.Database.Extensions.Core.Tests/CaptureTests.cs index 9a5477ad..6007687f 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/CaptureTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/CaptureTests.cs @@ -366,26 +366,16 @@ public static void EachOutput_HasOneOwner_CheckedAtTheCall() } [Fact] - public static void TheReturnCode_NeedsAStoredProcedure_AndAnInteger() + public static void TheReturnCode_NeedsAnInteger() { var c = new CaptureConnection(); - Contains( - Assert.Throws(() => c - .Command("select 1") - .CaptureReturn(out DbCapture _)), - "CaptureReturn needs a stored procedure", - "StoredProcedure(…)"); - Contains( - Assert.Throws(() => c - .Command("select 1") - .CaptureOutput(out DbCapture _)), - "the ReturnValue member of Touched, which needs a stored procedure"); Contains( Assert.Throws(() => c .StoredProcedure("p") .CaptureReturn(out DbCapture _)), - "CaptureReturn cannot hold it"); + "CaptureReturn cannot hold it", + "Use CaptureReturn"); } [Fact] @@ -991,4 +981,224 @@ await Assert.ThrowsAsync( "the query never ran"); Assert.Equal(0, c.Executed); } + + // ---- a capture added to the command after the query was made ---------- + + [Theory] + [InlineData(false, false)] + [InlineData(false, true)] + [InlineData(true, false)] + [InlineData(true, true)] + public static async Task ACommandCapture_AddedAfterMap_IsFilledToo( + bool commandFirst, + bool stream) + { + var c = new CaptureConnection(("total", 9), ("count", 4)); + var command = c.StoredProcedure("p"); + DbCapture total; + DbCapture count; + MappedQuery query; + if (commandFirst) + { + command.CaptureOutput("count", out count); + query = command.Map() + .CaptureOutput("total", out total); + } + else + { + query = command.Map() + .CaptureOutput("total", out total); + command.CaptureOutput("count", out count); + } + + if (stream) + { + await foreach (Row _ in query.ToPooledStream(Token)) { } + } + else + { + await query.ToListAsync(Token); + } + + Assert.Equal(9, await total); + Assert.Equal(4, await count); + Assert.Equal(1, c.Executed); + + // One run: a second is refused. + await Assert.ThrowsAsync( + async () => await query.ToListAsync(Token)); + } + + [Fact] + 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); + + Contains( + await Assert.ThrowsAsync( + async () => await query.ToListAsync(Token)), + "reads output parameter @total twice", + "Capture each parameter once"); + Assert.Equal(0, c.Executed); + + // Nothing was armed: each capture says it has not started. + foreach (DbCapture capture in (DbCapture[])[own, late]) + { + Contains( + Assert.Throws( + () => { _ = capture.AsTask(); }), + "has not started"); + } + } + + [Fact] + 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 _); + + Contains( + Assert.Throws(() => query.ToList()), + "reads output parameter @total twice"); + Assert.Equal(0, c.Executed); + } + + [Fact] + 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 _); + + Contains( + Assert.Throws( + () => query.ToPooledStream(Token)), + "reads output parameter @total twice", + "Capture each parameter once"); + Assert.Equal(0, c.Executed); + } + + // A stream or a buffer takes the command's captures when it is made: one + // added to the command after that is not part of its run. + [Theory] + [InlineData(false)] + [InlineData(true)] + public static async Task ACommandCapture_AddedAfterTheStreamIsMade_IsNotFilled( + bool buffer) + { + var c = new CaptureConnection(("total", 9), ("count", 4)); + var command = c.StoredProcedure("p"); + MappedQuery query = command.Map() + .CaptureOutput("total", out DbCapture total); + + if (buffer) + { + using PooledBuffer made = query.ToPooledBuffer(Token); + command.CaptureOutput("count", out DbCapture late); + _ = await made.Items; + AssertNotFilled(c, late); + } + else + { + IAsyncEnumerable rows = query.ToPooledStream(Token); + command.CaptureOutput("count", out DbCapture late); + await foreach (Row _ in rows) { } + AssertNotFilled(c, late); + } + + Assert.Equal(9, await total); + } + + static void AssertNotFilled(CaptureConnection c, DbCapture late) + { + Assert.DoesNotContain( + c.Last!.All, + static p => p.ParameterName == "count"); + Contains( + Assert.Throws( + () => { _ = late.AsTask(); }), + "has not started"); + } + + // ---- the return code: the run decides, the command's type can change ---- + + [Fact] + public static async Task ACommandTypeSetAfterCaptureReturn_IsHonored() + { + var c = new CaptureConnection(("", 7)); + var command = c.Command("p") + .CaptureReturn(out DbCapture code); + + command.Type = CommandType.StoredProcedure; + await command.ExecuteNonQueryAsync(Token); + + Assert.Equal(7, await code); + } + + [Fact] + public static async Task AReturnCode_OnATextCommand_IsRefusedAtTheRun() + { + var c = new CaptureConnection(("", 7)); + var command = c.Command("select 1") + .CaptureReturn(out DbCapture code); + + Contains( + await Assert.ThrowsAsync( + async () => await command.ExecuteNonQueryAsync(Token)), + "CaptureReturn needs a stored procedure", + "StoredProcedure(…)"); + Contains( + await Assert.ThrowsAsync( + async () => await code), + "needs a stored procedure"); + Assert.Equal(0, c.Executed); + } + + [Fact] + public static async Task AModelWithAReturnValue_OnATextCommand_IsRefusedAtTheRun() + { + var c = new CaptureConnection(("Count", 1), ("", 7)); + MappedQuery query = c.Command("select 1") + .Map() + .CaptureOutput(out DbCapture touched); + + Contains( + await Assert.ThrowsAsync( + async () => await query.ToListAsync(Token)), + "the ReturnValue member of Touched, which needs a stored procedure"); + Contains( + await Assert.ThrowsAsync( + async () => await touched), + "which needs a stored procedure"); + Assert.Equal(0, c.Executed); + } + + // ---- ExecuteReturnAsync with a model --------------------------------- + + // Takes the value task as an argument: the call under test must throw + // before one exists, so nothing is awaited. + static void Discard(ValueTask _) { } + + [Fact] + public static void ExecuteReturnAsync_OfAModel_ThrowsAtTheCall() + { + var c = new CaptureConnection(("", 1)); + var command = c.StoredProcedure("p"); + + // Not in a task: it throws before one exists. + Contains( + Assert.Throws( + () => Discard(command.ExecuteReturnAsync(Token))), + "cannot hold it"); + Assert.Equal(0, c.Executed); + } } diff --git a/Tests/Open.Database.Extensions.Core.Tests/OutputParameterLocalDbTests.cs b/Tests/Open.Database.Extensions.Core.Tests/OutputParameterLocalDbTests.cs index 93304e9b..904bab5d 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/OutputParameterLocalDbTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/OutputParameterLocalDbTests.cs @@ -263,9 +263,9 @@ public static async Task WhenTheNamesAreKnown_NoMatchAndTwoMembersOnOneParameter Assert.Contains("Name its parameter exactly with [Column(\"name\")] on Counted.PostCount", ambiguous.Message); } - // The named form: the name exactly (with or without @, any case), never through the tiers; "ReturnValue" names a declared parameter. + // The named form finds its parameter the way AddParam does (the four tiers, exact first); "ReturnValue" names a declared parameter. [Fact] - public static async Task TheNamedForm_MatchesTheNameExactly() + public static async Task TheNamedForm_MatchesThroughTheTiers() { LocalDbFixture.SkipUnlessAvailable(); using LocalDbFixture.Scratch procedure = Procedure( @@ -277,11 +277,50 @@ public static async Task TheNamedForm_MatchesTheNameExactly() Assert.Equal(7, await connection.StoredProcedure(name).ExecuteOutputAsync("@post_id", Token)); Assert.Equal(7, await connection.StoredProcedure(name).ExecuteOutputAsync("POST_ID", Token)); Assert.Equal(9, await connection.StoredProcedure(name).ExecuteOutputAsync("ReturnValue", Token)); - var ex = await Assert.ThrowsAsync(async () => await connection.StoredProcedure(name).ExecuteOutputAsync("PostId", Token)); - Assert.Contains("The output parameter 'PostId' is not a parameter of dbo.", ex.Message); + Assert.Equal(7, await connection.StoredProcedure(name).ExecuteOutputAsync("PostId", Token)); + var ex = await Assert.ThrowsAsync(async () => await connection.StoredProcedure(name).ExecuteOutputAsync("Posts", Token)); + Assert.Contains("The output parameter 'Posts' is not a parameter of dbo.", ex.Message); Assert.Contains("Pass one of those names to ExecuteOutputAsync(name)", ex.Message); } + [Fact] + public static async Task TheNamedForm_FindsACamelCaseName_ByTheUnderscoreTier() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = Procedure("@total_count int output", "set @total_count = 12;"); + await using SqlConnection connection = await OpenAsync(); + + Assert.Equal(12, await connection.StoredProcedure("dbo." + procedure.Name).ExecuteOutputAsync("totalCount", Token)); + } + + [Fact] + public static async Task TheNamedForm_PrefersTheExactName_OverALowerTier() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = Procedure("@post_id int = null output, @postid int = null output", "set @post_id = 7; set @postid = 8;"); + await using SqlConnection connection = await OpenAsync(); + string name = "dbo." + procedure.Name; + + Assert.Equal(8, await connection.StoredProcedure(name).ExecuteOutputAsync("postid", Token)); + Assert.Equal(8, await connection.StoredProcedure(name).ExecuteOutputAsync("POSTID", Token)); + Assert.Equal(7, await connection.StoredProcedure(name).ExecuteOutputAsync("post_id", Token)); + } + + [Fact] + public static async Task TheNamedForm_ThrowsWhenTwoParametersFitEqually_AndSaysTheFix() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = Procedure("@post_id int output, @postid_ int output", "set @post_id = 7; set @postid_ = 8;"); + await using SqlConnection connection = await OpenAsync(); + + var ex = await Assert.ThrowsAsync(async () => await connection.StoredProcedure("dbo." + procedure.Name).ExecuteOutputAsync("PostId", Token)); + Assert.Contains("matches both", ex.Message); + Assert.Contains("post_id", ex.Message); + Assert.Contains("postid_", ex.Message); + Assert.Contains("Pass the exact parameter name", ex.Message); + Assert.DoesNotContain("[Column", ex.Message); + } + // ---- the owner's matrix: each type as a model member and as a named value; return only; failures ---------------- public enum PostStatus diff --git a/Tests/Open.Database.Extensions.Core.Tests/OutputParameterTests.cs b/Tests/Open.Database.Extensions.Core.Tests/OutputParameterTests.cs index 3d98e5f2..6292066a 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/OutputParameterTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/OutputParameterTests.cs @@ -46,6 +46,10 @@ public sealed record Cursor(long Position); public sealed record Ordered([property: Column(Order = 2)] int Total, int Count); + public sealed record Gapped( + [property: Column(Order = 0)] int First, + [property: Column(Order = 2)] int Third); + public sealed record Renamed([property: Column("@post_count")] int Count); public sealed record Twice(int Total, [property: Column("total")] int Sum); @@ -294,6 +298,28 @@ public static async Task AMemberWithAnOrdinal_IsRead() Assert.Equal(new Ordered(9, 2), await c.StoredProcedure("dbo.Count").ExecuteOutputAsync(Token)); } + // A pin, not a fix: orders 0 and 2 leave ordinal 1 with no member. The + // output model reads as a row model does: the gap is not read, and the + // map accepts the null label of the gap. + [Fact] + public static async Task AGapInTheOrdinals_BehavesAsInARowModel() + { + var c = new OutputConnection(Fill(("First", 1), ("Third", 3))); + + Assert.Equal( + new Gapped(1, 3), + await c.StoredProcedure("dbo.Count").ExecuteOutputAsync(Token)); + + var row = new FakeExecuteReader(() => TypedReader.Create( + [("First", typeof(int)), ("Between", typeof(int)), ("Third", typeof(int))], + [1, 2, 3])); + Assert.Equal(new Gapped(1, 3), Assert.Single(row.Map().ToList())); + + Func fromCells = RowMap.Default + .ArrayMapper(["First", null!, "Third"]); + Assert.Equal(new Gapped(1, 3), fromCells([1, null, 3])); + } + [Fact] public static async Task AReturnValueMember_ReadsTheReturnCode() { diff --git a/Tests/Open.Database.Extensions.Core.Tests/ParameterByteZeroCompileTests.cs b/Tests/Open.Database.Extensions.Core.Tests/ParameterByteZeroCompileTests.cs new file mode 100644 index 00000000..f7741c58 --- /dev/null +++ b/Tests/Open.Database.Extensions.Core.Tests/ParameterByteZeroCompileTests.cs @@ -0,0 +1,75 @@ +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; + +#nullable enable + +namespace Open.Database.Extensions.Tests; + +// A constant zero of type byte on the SQL Server command used to bind to the +// direction overload. The release notes say it is now an ambiguous call +// (CS0121), and what to pass instead; this compiles the three shapes. +[ExcludeFromCodeCoverage] +public static class ParameterByteZeroCompileTests +{ + 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)) + { + // The legacy adapter defines types of the same name as the SQL + // Server package (CS0433): only the package is referenced. + string file = Path.GetFileName(path); + if (file.Equals( + "Open.Database.Extensions.SqlClient.dll", + StringComparison.OrdinalIgnoreCase)) + { + continue; + } + + paths.Add(path); + } + } + + return [.. paths.Select(static p => + (MetadataReference)MetadataReference.CreateFromFile(p))]; + }); + + static string[] ErrorIds(string body) + { + string source = "using System.Data;\n" + + "using Open.Database.Extensions;\n" + + "static class Probe\n{\n" + + "\tstatic void M(ExpressiveSqlCommand c) { " + body + " }\n}\n"; + var compilation = CSharpCompilation.Create( + "ByteZeroProbe", + [CSharpSyntaxTree.ParseText( + source, + new CSharpParseOptions(LanguageVersion.Preview))], + References.Value, + new CSharpCompilationOptions( + OutputKind.DynamicallyLinkedLibrary, + specificDiagnosticOptions: new Dictionary + { + ["CS1701"] = ReportDiagnostic.Suppress, + ["CS1702"] = ReportDiagnostic.Suppress, + })); + return [.. compilation + .GetDiagnostics(TestContext.Current.CancellationToken) + .Where(static d => d.Severity == DiagnosticSeverity.Error) + .Select(static d => d.Id)]; + } + + [Fact] + public static void ConstantByteZero_WithoutAType_IsAnAmbiguousCall() + => Assert.Equal(["CS0121"], ErrorIds("c.AddParam(\"x\", (byte)0);")); + + [Fact] + public static void AByteVariable_OrAGivenType_Compiles() + { + Assert.Empty(ErrorIds("byte b = 0; c.AddParam(\"x\", b);")); + Assert.Empty(ErrorIds( + "c.AddParam(\"x\", (byte)0, SqlDbType.TinyInt);")); + } +} diff --git a/Tests/Open.Database.Extensions.Core.Tests/ParameterNameAddParamsTests.cs b/Tests/Open.Database.Extensions.Core.Tests/ParameterNameAddParamsTests.cs index 84615553..ebfcf7f8 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/ParameterNameAddParamsTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/ParameterNameAddParamsTests.cs @@ -321,16 +321,16 @@ public static void AMemberOfARefStructType_MakesAddParamsThrowForThatType_UntilS .GetMethod("Candidates", BindingFlags.Static | BindingFlags.NonPublic)! .CreateDelegate>>(); - static readonly Func, ImmutableArray, ImmutableArray, string, string, string?, string?> MatchBare = Names + static readonly Func, ImmutableArray, ImmutableArray, string, string, string?, string?, string?> MatchBare = Names .GetMethod("MatchBareAs", BindingFlags.Static | BindingFlags.NonPublic)! - .CreateDelegate, ImmutableArray, ImmutableArray, string, string, string?, string?>>(); + .CreateDelegate, ImmutableArray, ImmutableArray, string, string, string?, string?, string?>>(); static readonly Func, ImmutableArray> BareNames = Names .GetMethod("BareNames", BindingFlags.Static | BindingFlags.NonPublic)! .CreateDelegate, ImmutableArray>>(); static string? Match(ImmutableArray candidates, ImmutableArray parameterNames, string expression, string procedure) - => MatchBare(candidates, parameterNames, BareNames(parameterNames), expression, procedure, null); + => MatchBare(candidates, parameterNames, BareNames(parameterNames), expression, procedure, null, null); [Theory] [InlineData("x", "x")] diff --git a/docsite/articles/expressive-commands.md b/docsite/articles/expressive-commands.md index 57659880..76e023c7 100644 --- a/docsite/articles/expressive-commands.md +++ b/docsite/articles/expressive-commands.md @@ -209,7 +209,7 @@ 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, named exactly (with or without `@`, any case); `"ReturnValue"` there names a declared parameter, not the return code. A `decimal` needs its precision and scale: `ExecuteOutputAsync("total", 19, 4)` for a `decimal(19,4)` (`decimal?` for NULL), or `ExecuteOutputDecimalAsync("total", 19, 4)`, which returns a `decimal?`. Without them `ExecuteOutputAsync(name)` throws before it runs, and only a `decimal` takes them. +- **One value.** `ExecuteOutputAsync("name")` reads one parameter, found the way `AddParam` finds its name (with or without `@`: exactly, else ignoring case, else ignoring case and underscores, else without a common prefix such as `p_`; the exact name wins, and a name that fits two parameters equally well throws, so pass the exact one); `"ReturnValue"` there names a declared parameter, not the return code. A `decimal` needs its precision and scale: `ExecuteOutputAsync("total", 19, 4)` for a `decimal(19,4)` (`decimal?` for NULL), or `ExecuteOutputDecimalAsync("total", 19, 4)`, which returns a `decimal?`. Without them `ExecuteOutputAsync(name)` throws before it runs, and only a `decimal` takes them. - **Not delivered.** An Output parameter still empty after the call means the response never completed: the call throws `InvalidOperationException`, never a NULL. One value, and a decimal with its precision and scale: @@ -224,7 +224,7 @@ There is no blocking form. Known limits: - The declared scale of a `decimal` also rounds a value sent in (`1.239` sent as `decimal(10,2)` arrives as `1.24`). - An InputOutput parameter whose outputs never arrive keeps the value sent: that case cannot be told from a real answer. - A parameter added with a null value (`AddParam(name, (int?)null, type)`) that is also an output member is sent as InputOutput too, so a lost output cannot be told from a NULL. For a pure output, add no value; add one only when the procedure reads it. -- A member on a parameter the procedure does not declare `OUTPUT` is the provider's error (SQL Server: 8162), and SQLite refuses every output direction with its own `ArgumentException`. +- A member on a parameter the procedure does not declare `OUTPUT` is the provider's error (SQL Server: 8162). - SqlClient reports an error after the outputs are set, and a cancel while the command runs, with its own `SqlException`. - **A legacy `datetime` output can differ from a row in the last digits.** Outputs are sent as `datetime2`, so a `datetime` that stores `.997` (ticks of 1/300 second) reads back into a `DateTime` as `.9966667`, where a row read of the same value gives `.997`. `smalldatetime` and `datetime2` arrive exactly. To get what a row read gives, pass the value through `new SqlDateTime(value).Value` (from `System.Data.SqlTypes`), or have the procedure declare the output as `datetime2(3)`. Feeding such a value back in as an input lands on the same stored tick. - Output models use the runtime map, not a generated reader. @@ -235,11 +235,11 @@ There is no blocking form. Known limits: [!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: +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: [!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. 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): +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)] @@ -247,7 +247,8 @@ The recommended form for a query is the definition: `static readonly MappedDbQue - **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. - **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, a return code on a text command, and two captures of one output (the same name twice, or a model beside another capture) throw at the capture call, before anything runs. +- **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. - **How it completes.** With the value; with the run's error, or the conversion's (the terminal's own result is not affected); canceled with the caller's token; or with `InvalidOperationException` when the outputs never arrived. Awaiting it before the terminal was called throws, and its `GetResult` never blocks. ## Terminals diff --git a/docsite/articles/release-notes.md b/docsite/articles/release-notes.md index 22560526..67faabe4 100644 --- a/docsite/articles/release-notes.md +++ b/docsite/articles/release-notes.md @@ -10,8 +10,8 @@ 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. 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. Misuse throws at the call: `NotSupportedException` on a query made from a definition or one that does not read from an expressive command, `InvalidOperationException` otherwise. 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(name, ...)` captures one; a name finds its parameter the way `AddParam`'s name does (exactly, else ignoring case, else ignoring case and underscores, else without a common prefix such as `p_`), so `"totalCount"` finds `@total_count`. A `decimal` declares its SQL type: `[Column(TypeName = "decimal(p,s)")]` on a member, or `ExecuteOutputAsync(name, precision, scale)` (`ExecuteOutputDecimalAsync`) for one value. See [Output parameters](expressive-commands.md#output-parameters). +- **New: captures, output parameters beside rows.** `CaptureOutput` (a model, one value, or a `decimal` with its precision and scale), `CaptureOutputDecimal` and `CaptureReturn` on an expressive command, a mapped query and its `Skip` and `Take` views give a `DbCapture` as an `out` argument; the async terminal fills it, and a stream fills it when its loop ends, a `break` included. A capture runs once and needs an async terminal; a query's run fills the captures its command has when the run starts, including one added after `Map`. Misuse throws at the call, except that the return code of a command that is not a stored procedure is refused when the run starts: `NotSupportedException` on a query made from a definition or one that does not read from an expressive command, `InvalidOperationException` otherwise. A command whose type re-implements `IExecuteReader` is refused too, as `NotSupportedException` on a query capture and `InvalidOperationException` when a command capture runs. See [Output parameters beside rows](expressive-commands.md#output-parameters-beside-rows). - **New: `ToArrayAsync` and `ToImmutableArrayAsync` on a `DbDataReader`.** Like `ToListAsync(transform)`, they read the remaining rows of the current result set through an asynchronous transform into pooled chunks and copy them once, into an array of exactly their number; on .NET 8 and later the immutable array wraps that array and does not copy it again (on .NET Standard it is a copy). - **Changed: the collecting terminals clear their value rows when no pool is offered.** `ToList`, `ToArray`, `ToImmutableArray`, `ToHashSet` and the dictionaries, asynchronous and synchronous, on a view or on a `DbDataReader`, copy their rows out and never show their pooled arrays, so they hide their pooling: a query that does not call `UsePool` now always clears the used rows of those arrays before they go back, plain value rows included, whatever the `Open.Database.Extensions.ClearPooledArrays` switch says. `UsePool(pool, clearOnReturn)` is followed as before, so `clearOnReturn: false` still keeps the rows. Rows that hold references were always cleared. The buffers and streams are unchanged: their default is still not to clear value rows. A chunk of 128 KB or more is cleared in the background, as before, and the allocation of a call is the same. - **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/samples/OutputParameters.cs b/docsite/samples/OutputParameters.cs index 938bf79b..2ee83068 100644 --- a/docsite/samples/OutputParameters.cs +++ b/docsite/samples/OutputParameters.cs @@ -161,7 +161,8 @@ await Blog await command.ExecuteNonQueryAsync(cancellationToken); - // Read the values after the command has run. + // Read the values after the command has run. A NULL output is DBNull, + // which the cast throws on: cast only what the procedure always sets. id = (int)output.Value!; returned = (int)returnCode.Value!; });