From 90ead95f7852d43f69a322a2bb454a0ae5cda610 Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Wed, 2 Dec 2026 08:47:07 -0800 Subject: [PATCH 1/6] Captures: refuse a command that re-implements its reader A capture reads the outputs through the library's own reader path. A command type that re-implements IExecuteReader replaces that path, so a capture on it used to be bypassed: the library took its own reader and ignored the override. It is now refused. A capture made on a mapped query throws NotSupportedException at the capture call. A capture made on the command throws InvalidOperationException when the query runs, at the one place every captured run passes, and completes every capture with the same exception, so none is left pending. Both messages name the command type and say to capture on a command that does not re-implement the interface, or to read the outputs with ExecuteOutputAsync. The library's own command types are decided by an exact type test, with no lookup. Any other type is examined once with reflection (every interface that extends IExecuteReader, and the declaring type of each method that implements it) and the answer is kept in a table that does not hold the type alive. A type that cannot be examined is refused with a message that says so; that failure is not cached. A call without a capture is not affected. Co-Authored-By: Claude Sonnet 5.5 --- Source/Core/Capture.cs | 14 + Source/Core/ExpressiveCommand.cs | 7 + Source/Core/ExpressiveCommandBase.Capture.cs | 21 ++ Source/Core/ExpressiveDbCommand.cs | 7 + Source/Core/MappedQuery.Capture.cs | 11 +- Source/Core/MappedQuery.cs | 52 +++- Source/Core/Output.docs.xml | 5 +- Source/Core/ReaderReplacement.cs | 80 ++++++ Source/MSSqlClient/ExpressiveSqlCommand.cs | 7 + Source/SqlClient/ExpressiveSqlCommand.cs | 7 + .../CaptureLibraryCommandTests.cs | 41 +++ .../CaptureStreamTests.cs | 270 ++++++++++++++++-- docsite/articles/expressive-commands.md | 1 + docsite/articles/release-notes.md | 2 +- 14 files changed, 489 insertions(+), 36 deletions(-) create mode 100644 Source/Core/ReaderReplacement.cs create mode 100644 Tests/Open.Database.Extensions.Core.Tests/CaptureLibraryCommandTests.cs diff --git a/Source/Core/Capture.cs b/Source/Core/Capture.cs index 98e8d8fe..c5294323 100644 --- a/Source/Core/Capture.cs +++ b/Source/Core/Capture.cs @@ -983,4 +983,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..01e86b42 100644 --- a/Source/Core/ExpressiveCommandBase.Capture.cs +++ b/Source/Core/ExpressiveCommandBase.Capture.cs @@ -21,6 +21,13 @@ interface ICaptureRunner /// 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. /// The type of the state. @@ -182,6 +189,20 @@ void Attach(ICaptureSource source) 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, TState state, 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..6e100ac5 100644 --- a/Source/Core/MappedQuery.Capture.cs +++ b/Source/Core/MappedQuery.Capture.cs @@ -33,7 +33,9 @@ public CaptureRun? CapturedRun /// of the return code of a command that is not a stored procedure, or a /// capture that reads what another one reads. /// 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,6 +49,13 @@ 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())); + } // Appended to the command's, so the query and the command share the // first capture, and one run claims them. diff --git a/Source/Core/MappedQuery.cs b/Source/Core/MappedQuery.cs index 05865a93..0e4a295d 100644 --- a/Source/Core/MappedQuery.cs +++ b/Source/Core/MappedQuery.cs @@ -495,15 +495,55 @@ 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, the one + // place every captured run passes (a capture made on the command, not the + // query, is not checked at a capture call): 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/Output.docs.xml b/Source/Core/Output.docs.xml index 9c57c81f..cbe2df19 100644 --- a/Source/Core/Output.docs.xml +++ b/Source/Core/Output.docs.xml @@ -217,6 +217,9 @@ 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: the capture reads through the library's reader, + so the run throws (and completes the capture with it) before anything is executed. + Capture on a command that does not re-implement it, or read the outputs with ExecuteOutputAsync. @@ -238,7 +241,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/ReaderReplacement.cs b/Source/Core/ReaderReplacement.cs new file mode 100644 index 00000000..47c56a72 --- /dev/null +++ b/Source/Core/ReaderReplacement.cs @@ -0,0 +1,80 @@ +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 after the first captured run of a type that + /// is not a library command, never more. + internal 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. + internal 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/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/CaptureStreamTests.cs b/Tests/Open.Database.Extensions.Core.Tests/CaptureStreamTests.cs index 1724fbad..d3b755f0 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/CaptureStreamTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/CaptureStreamTests.cs @@ -566,8 +566,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 +593,192 @@ 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", + "Stream", + "ToPooledBuffer", + "ToChannelReader", + "AsSourceBlock", + "ToTargetBlock", + "AnyAsync", + "AsObjectArrays", + "SingleResult"); + + // 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 +791,82 @@ 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); + } + + [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/docsite/articles/expressive-commands.md b/docsite/articles/expressive-commands.md index 57659880..d0472a74 100644 --- a/docsite/articles/expressive-commands.md +++ b/docsite/articles/expressive-commands.md @@ -248,6 +248,7 @@ 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. +- **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 throws `InvalidOperationException` when it runs, before anything executes. Capture on a command that does not re-implement `IExecuteReader`, or read the outputs with `ExecuteOutputAsync`. - **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..531b4b01 100644 --- a/docsite/articles/release-notes.md +++ b/docsite/articles/release-notes.md @@ -11,7 +11,7 @@ Version 11 is `11.0.0-rc.16`. For moving a 10.x codebase, read [Coming from earl - **Fixed: `CreateCommand` on a `SqlTransaction` that has no connection throws `InvalidOperationException`.** The SQL Server package threw `ArgumentNullException` named `connection`; it now reports "Transaction has no connection.", as the core package does. `CreateTextCommand` and `CreateStoredProcedureCommand` follow. - **Removed: parameter directions on the fluent chain.** `AddParam` and `AddParamIf` no longer take a `ParameterDirection`; `AddReturnParam` is gone, and `AddParam(name, direction)`, `AddParamIf(condition, name, direction)`, `AddParam(name, type)` and `AddParamIf(condition, name, type)` are now compile errors that say what to do instead. The forms that took a direction after the value, `AddParam(name, value, ParameterDirection)` and `AddParam(name, value, type, direction)` (the SQL Server forms with a database type and a direction too), fail to compile with the compiler's own argument error, without a message of their own: use the raw `AddParameter` inside `ExecuteAsync(command => ...)`, or read the output with `ExecuteOutputAsync`. A parameter on the chain is an input. To set a direction, use `ExecuteAsync(command => ...)` with the raw `AddParameter`, `AddParameterType` and `AddReturnParameter` extensions. Calls that never passed a direction compile unchanged, with one exception: a constant zero of type `byte` on the SQL Server command, `AddParam(name, (byte)0)`, used to bind silently to the direction overload and is now an ambiguous-call error (CS0121); pass a variable, or give the database type, `AddParam(name, value, SqlDbType.TinyInt)`. `Param` has no `direction` constructor parameter and no `Direction` property. - **Read output parameters: `ExecuteOutputAsync()`.** It maps a command's output parameters and return code into a model by name, with the `Map()` rules; `ExecuteOutputAsync(name)` reads one value. 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). +- **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. 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. From 0619e9e19ce2c82e098dfb9a301e8515a89233c8 Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Wed, 2 Dec 2026 09:01:39 -0800 Subject: [PATCH 2/6] Output parameters: one name rule for every named output A named output (ExecuteOutputAsync(name), its decimal forms, and CaptureOutput(name, ...) / CaptureOutputDecimal(name, ...) on a command and on a mapped query) now finds its parameter the way the name of AddParam does: exactly, else ignoring case, else ignoring case and underscores, else without a common prefix such as p_; a lower rule applies only when no higher one matches. "totalCount" finds @total_count. [Column("name")] members keep exact matching. A name that fits two parameters at the same level throws a message that says to pass the exact parameter name, not to use [Column]. Two named captures that resolve to one parameter fail the run and say how to fix it; the call cannot see that, because it compares the names as written. Docs and release notes state the one rule. Co-Authored-By: Claude Sonnet 5.5 --- Source/Core/ExpressiveCommandBase.Capture.cs | 6 +++ Source/Core/ExpressiveCommandBase.Output.cs | 18 +++++-- Source/Core/MappedQuery.Capture.cs | 6 +++ Source/Core/NameSet.cs | 30 ++++++++++++ Source/Core/Output.docs.xml | 15 ++++-- Source/Core/OutputLayout.cs | 8 ++-- Source/Core/ParameterNames.cs | 16 +++++-- .../AllocationQuickWinTests.cs | 6 +-- .../CaptureLocalDbTests.cs | 40 ++++++++++++++++ .../OutputParameterLocalDbTests.cs | 47 +++++++++++++++++-- .../ParameterNameAddParamsTests.cs | 6 +-- docsite/articles/expressive-commands.md | 2 +- docsite/articles/release-notes.md | 2 +- 13 files changed, 173 insertions(+), 29 deletions(-) diff --git a/Source/Core/ExpressiveCommandBase.Capture.cs b/Source/Core/ExpressiveCommandBase.Capture.cs index 01e86b42..c9d5ff52 100644 --- a/Source/Core/ExpressiveCommandBase.Capture.cs +++ b/Source/Core/ExpressiveCommandBase.Capture.cs @@ -104,6 +104,8 @@ public TThis CaptureOutput(out DbCapture output) /// /// + /// public TThis CaptureOutput(string name, out DbCapture value) { @@ -121,6 +123,8 @@ public TThis CaptureOutput(string name, out DbCapture value) /// /// + /// public TThis CaptureOutput( string name, @@ -144,6 +148,8 @@ public TThis CaptureOutput( /// /// + /// public TThis CaptureOutputDecimal( string name, 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/MappedQuery.Capture.cs b/Source/Core/MappedQuery.Capture.cs index 6e100ac5..16f8df49 100644 --- a/Source/Core/MappedQuery.Capture.cs +++ b/Source/Core/MappedQuery.Capture.cs @@ -146,6 +146,8 @@ public MappedQuery CaptureOutput(out DbCapture output) /// /// + /// public MappedQuery CaptureOutput( string name, @@ -165,6 +167,8 @@ public MappedQuery CaptureOutput( /// /// + /// public MappedQuery CaptureOutput( string name, @@ -188,6 +192,8 @@ public MappedQuery CaptureOutput( /// /// + /// public MappedQuery CaptureOutputDecimal( string name, diff --git a/Source/Core/NameSet.cs b/Source/Core/NameSet.cs index 26795a07..948a9d3a 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. + internal 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 cbe2df19..6469b327 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: exactly, else ignoring case, else ignoring case and underscores, else after one common prefix such as p_ is removed from the declared name. + Two captures that match one parameter fail the run, not this call. + + + A parameter added with a null value is sent as too, @@ -156,7 +164,6 @@ 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 +176,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 +191,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 . 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/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/CaptureLocalDbTests.cs b/Tests/Open.Database.Extensions.Core.Tests/CaptureLocalDbTests.cs index a8fed985..bf0519a9 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/CaptureLocalDbTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/CaptureLocalDbTests.cs @@ -214,6 +214,46 @@ 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); + } + // A text command's @name OUTPUT marker. [Fact] public static async Task ATextCommand_FillsItThroughItsMarker() 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/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 d0472a74..f098f4a1 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: diff --git a/docsite/articles/release-notes.md b/docsite/articles/release-notes.md index 531b4b01..1cd2d849 100644 --- a/docsite/articles/release-notes.md +++ b/docsite/articles/release-notes.md @@ -10,7 +10,7 @@ Version 11 is `11.0.0-rc.16`. For moving a 10.x codebase, read [Coming from earl - **Fixed: a cancel during `AsAsyncEnumerable(pool)`.** On a `DbDataReader`, `AsAsyncEnumerable(arrayPool)` with a pool (the form that reads every column) did not pass its token to `ReadAsync`, so a read the provider cancelled threw out of the enumeration. It now ends the enumeration quietly with the rows already yielded, as the other forms do. - **Fixed: `CreateCommand` on a `SqlTransaction` that has no connection throws `InvalidOperationException`.** The SQL Server package threw `ArgumentNullException` named `connection`; it now reports "Transaction has no connection.", as the core package does. `CreateTextCommand` and `CreateStoredProcedureCommand` follow. - **Removed: parameter directions on the fluent chain.** `AddParam` and `AddParamIf` no longer take a `ParameterDirection`; `AddReturnParam` is gone, and `AddParam(name, direction)`, `AddParamIf(condition, name, direction)`, `AddParam(name, type)` and `AddParamIf(condition, name, type)` are now compile errors that say what to do instead. The forms that took a direction after the value, `AddParam(name, value, ParameterDirection)` and `AddParam(name, value, type, direction)` (the SQL Server forms with a database type and a direction too), fail to compile with the compiler's own argument error, without a message of their own: use the raw `AddParameter` inside `ExecuteAsync(command => ...)`, or read the output with `ExecuteOutputAsync`. A parameter on the chain is an input. To set a direction, use `ExecuteAsync(command => ...)` with the raw `AddParameter`, `AddParameterType` and `AddReturnParameter` extensions. Calls that never passed a direction compile unchanged, with one exception: a constant zero of type `byte` on the SQL Server command, `AddParam(name, (byte)0)`, used to bind silently to the direction overload and is now an ambiguous-call error (CS0121); pass a variable, or give the database type, `AddParam(name, value, SqlDbType.TinyInt)`. `Param` has no `direction` constructor parameter and no `Direction` property. -- **Read output parameters: `ExecuteOutputAsync()`.** It maps a command's output parameters and return code into a model by name, with the `Map()` rules; `ExecuteOutputAsync(name)` reads one value. A `decimal` declares its SQL type: `[Column(TypeName = "decimal(p,s)")]` on a member, or `ExecuteOutputAsync(name, precision, scale)` (`ExecuteOutputDecimalAsync`) for one value. See [Output parameters](expressive-commands.md#output-parameters). +- **Read output parameters: `ExecuteOutputAsync()`.** It maps a command's output parameters and return code into a model by name, with the `Map()` rules; `ExecuteOutputAsync(name)` reads one value, and `CaptureOutput(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. 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. A command whose type re-implements `IExecuteReader` is refused too, as `NotSupportedException` on a query capture and `InvalidOperationException` when a command capture runs. See [Output parameters beside rows](expressive-commands.md#output-parameters-beside-rows). - **New: `ToArrayAsync` and `ToImmutableArrayAsync` on a `DbDataReader`.** Like `ToListAsync(transform)`, they read the remaining rows of the current result set through an asynchronous transform into pooled chunks and copy them once, into an array of exactly their number; on .NET 8 and later the immutable array wraps that array and does not copy it again (on .NET Standard it is a copy). - **Changed: the collecting terminals clear their value rows when no pool is offered.** `ToList`, `ToArray`, `ToImmutableArray`, `ToHashSet` and the dictionaries, asynchronous and synchronous, on a view or on a `DbDataReader`, copy their rows out and never show their pooled arrays, so they hide their pooling: a query that does not call `UsePool` now always clears the used rows of those arrays before they go back, plain value rows included, whatever the `Open.Database.Extensions.ClearPooledArrays` switch says. `UsePool(pool, clearOnReturn)` is followed as before, so `clearOnReturn: false` still keeps the rows. Rows that hold references were always cleared. The buffers and streams are unchanged: their default is still not to clear value rows. A chunk of 128 KB or more is cleared in the background, as before, and the allocation of a call is the same. From 92513f496384a5f4392981fa4e91f2092ae6ca7a Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Wed, 2 Dec 2026 09:06:37 -0800 Subject: [PATCH 3/6] Captures: a run fills every capture its command has when it starts A mapped query that had a capture of its own took a snapshot of its command's captures when the capture was added, so a capture added to the command afterwards was never armed. The query now keeps only its own captures, and a run combines the command's captures as they are then (first, so the order is stable) with the query's own. The combined set is kept per command set, so the calls of one run get the same set and layout, and a query or command with nothing to combine allocates nothing new. A capture added to the query is still checked against the command's current captures at the call. A command capture added later that reads what a query capture reads is found when the terminal, the stream or the buffer is called, and throws before anything is armed or run. A stream or buffer takes the command's captures when it is made. The stall timeout test now also checks that the capture faults with the same type and message as the loop; it passes without a code change. Co-Authored-By: Claude Sonnet 5.5 --- Source/Core/Capture.cs | 60 +++++++++++++- Source/Core/MappedQuery.Capture.cs | 27 ++++++- Source/Core/Output.docs.xml | 14 ++-- .../CaptureStreamTests.cs | 9 ++- .../CaptureTests.cs | 79 +++++++++++++++++++ docsite/articles/expressive-commands.md | 2 +- docsite/articles/release-notes.md | 2 +- 7 files changed, 178 insertions(+), 15 deletions(-) diff --git a/Source/Core/Capture.cs b/Source/Core/Capture.cs index c5294323..80443df6 100644 --- a/Source/Core/Capture.cs +++ b/Source/Core/Capture.cs @@ -435,9 +435,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, then + /// these, the query's own. + /// + /// + /// 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) diff --git a/Source/Core/MappedQuery.Capture.cs b/Source/Core/MappedQuery.Capture.cs index 16f8df49..fb57c527 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 . @@ -57,10 +68,18 @@ public MappedQueryCore WithCapture(ICaptureSource source) _command!.GetType())); } - // Appended to the command's, so the query and the command share the - // first capture, and one run claims them. + // 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"); + } + CaptureSet captures = CaptureSet.With( - _captures as CaptureSet ?? runner.Captures, + _captures as CaptureSet, source, onQuery: true, runner.IsProcedure); return new( _command, _call, _source, diff --git a/Source/Core/Output.docs.xml b/Source/Core/Output.docs.xml index 6469b327..02d6d5dc 100644 --- a/Source/Core/Output.docs.xml +++ b/Source/Core/Output.docs.xml @@ -158,7 +158,7 @@ (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). @@ -170,7 +170,7 @@ 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. + or another capture reads the same parameter (for a capture added to the command after the query was made, when the terminal or stream is called). @@ -186,7 +186,7 @@ At the call: is not or a of it; - or another capture reads the same parameter. + or another capture reads the same parameter (for a capture added to the command after the query was made, when the terminal or stream is called). @@ -199,7 +199,7 @@ is 0 or more than 38, or is more than . - At the call: another capture reads the same parameter. + At the call: another capture reads the same parameter (for a capture added to the command after the query was made, when the terminal or stream is called). @@ -207,7 +207,7 @@ 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; - or another capture reads the return code. + or another capture reads the return code (for a capture added to the command after the query was made, when the terminal or stream is called). @@ -233,7 +233,9 @@ 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. + 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; diff --git a/Tests/Open.Database.Extensions.Core.Tests/CaptureStreamTests.cs b/Tests/Open.Database.Extensions.Core.Tests/CaptureStreamTests.cs index d3b755f0..42a321c6 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] diff --git a/Tests/Open.Database.Extensions.Core.Tests/CaptureTests.cs b/Tests/Open.Database.Extensions.Core.Tests/CaptureTests.cs index 9a5477ad..6aa818dd 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/CaptureTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/CaptureTests.cs @@ -991,4 +991,83 @@ 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 _); + command.CaptureOutput("total", out DbCapture _); + + Contains( + await Assert.ThrowsAsync( + async () => await query.ToListAsync(Token)), + "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"); + Assert.Equal(0, c.Executed); + } } diff --git a/docsite/articles/expressive-commands.md b/docsite/articles/expressive-commands.md index f098f4a1..98f4952e 100644 --- a/docsite/articles/expressive-commands.md +++ b/docsite/articles/expressive-commands.md @@ -247,7 +247,7 @@ 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, 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; 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 throws `InvalidOperationException` when it runs, before anything executes. Capture on a command that does not re-implement `IExecuteReader`, or read the outputs with `ExecuteOutputAsync`. - **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. diff --git a/docsite/articles/release-notes.md b/docsite/articles/release-notes.md index 1cd2d849..6389a4cf 100644 --- a/docsite/articles/release-notes.md +++ b/docsite/articles/release-notes.md @@ -11,7 +11,7 @@ Version 11 is `11.0.0-rc.16`. For moving a 10.x codebase, read [Coming from earl - **Fixed: `CreateCommand` on a `SqlTransaction` that has no connection throws `InvalidOperationException`.** The SQL Server package threw `ArgumentNullException` named `connection`; it now reports "Transaction has no connection.", as the core package does. `CreateTextCommand` and `CreateStoredProcedureCommand` follow. - **Removed: parameter directions on the fluent chain.** `AddParam` and `AddParamIf` no longer take a `ParameterDirection`; `AddReturnParam` is gone, and `AddParam(name, direction)`, `AddParamIf(condition, name, direction)`, `AddParam(name, type)` and `AddParamIf(condition, name, type)` are now compile errors that say what to do instead. The forms that took a direction after the value, `AddParam(name, value, ParameterDirection)` and `AddParam(name, value, type, direction)` (the SQL Server forms with a database type and a direction too), fail to compile with the compiler's own argument error, without a message of their own: use the raw `AddParameter` inside `ExecuteAsync(command => ...)`, or read the output with `ExecuteOutputAsync`. A parameter on the chain is an input. To set a direction, use `ExecuteAsync(command => ...)` with the raw `AddParameter`, `AddParameterType` and `AddReturnParameter` extensions. Calls that never passed a direction compile unchanged, with one exception: a constant zero of type `byte` on the SQL Server command, `AddParam(name, (byte)0)`, used to bind silently to the direction overload and is now an ambiguous-call error (CS0121); pass a variable, or give the database type, `AddParam(name, value, SqlDbType.TinyInt)`. `Param` has no `direction` constructor parameter and no `Direction` property. - **Read output parameters: `ExecuteOutputAsync()`.** It maps a command's output parameters and return code into a model by name, with the `Map()` rules; `ExecuteOutputAsync(name)` reads one value, and `CaptureOutput(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. 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. A command whose type re-implements `IExecuteReader` is refused too, as `NotSupportedException` on a query capture and `InvalidOperationException` when a command capture runs. See [Output parameters beside rows](expressive-commands.md#output-parameters-beside-rows). +- **New: captures, output parameters beside rows.** `CaptureOutput` (a model, one value, or a `decimal` with its precision and scale), `CaptureOutputDecimal` and `CaptureReturn` on an expressive command, a mapped query and its `Skip` and `Take` views give a `DbCapture` as an `out` argument; the async terminal fills it, and a stream fills it when its loop ends, a `break` included. A capture runs once and needs an async terminal; a query's run fills the captures its command has when the run starts, including one added after `Map`. Misuse throws at the call: `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. From 81bf8049ae780d13a35664ef5d7079370e5b3114 Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Wed, 2 Dec 2026 09:15:54 -0800 Subject: [PATCH 4/6] Captures: the return-code check moves to the run, and the early-stop cost and the claims in the docs are made explicit A capture of the return code was refused at the capture call when the command was not a stored procedure. The command's type is a public setter, so a valid chain written in the other order (the capture first, the type set after) was refused. The check now happens only when the run starts, where it already was, and fails the terminal and the capture with the same message. The unused procedure flag of the capture runner and of the capture set is removed. Leaving a captured stream early still reads the rest of the response so every output arrives; the docs now say that the loop's exit waits for it, that the stall timeout does not bound the wait, that a token the caller passed still cancels the read, and what to do instead. A test pins that a break after one row of many still fills the capture. ExecuteReturnAsync with a model documents and tests that it throws at the call. Documentation claims without a test are now either proven (a compile test for the ambiguous byte zero call on the SQL Server command) or softened (SQLite's exception type; the sample's cast of a NULL output). Co-Authored-By: Claude Sonnet 5.5 --- Source/Core/Capture.cs | 16 +--- Source/Core/ExpressiveCommandBase.Capture.cs | 14 +-- Source/Core/ExpressiveCommandBase.cs | 7 ++ Source/Core/MappedQuery.Capture.cs | 5 +- Source/Core/Output.docs.xml | 11 ++- .../CaptureLocalDbTests.cs | 25 ++++++ .../CaptureTests.cs | 86 ++++++++++++++++--- .../ParameterByteZeroCompileTests.cs | 75 ++++++++++++++++ docsite/articles/expressive-commands.md | 8 +- docsite/articles/release-notes.md | 2 +- docsite/samples/OutputParameters.cs | 3 +- 11 files changed, 204 insertions(+), 48 deletions(-) create mode 100644 Tests/Open.Database.Extensions.Core.Tests/ParameterByteZeroCompileTests.cs diff --git a/Source/Core/Capture.cs b/Source/Core/Capture.cs index 80443df6..9c22f820 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"; diff --git a/Source/Core/ExpressiveCommandBase.Capture.cs b/Source/Core/ExpressiveCommandBase.Capture.cs index c9d5ff52..4d9fb0f7 100644 --- a/Source/Core/ExpressiveCommandBase.Capture.cs +++ b/Source/Core/ExpressiveCommandBase.Capture.cs @@ -17,10 +17,6 @@ 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. @@ -186,15 +182,11 @@ 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. @@ -261,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.cs b/Source/Core/ExpressiveCommandBase.cs index f8386fa0..5dd48d12 100644 --- a/Source/Core/ExpressiveCommandBase.cs +++ b/Source/Core/ExpressiveCommandBase.cs @@ -1947,6 +1947,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/MappedQuery.Capture.cs b/Source/Core/MappedQuery.Capture.cs index fb57c527..ba4e1ca6 100644 --- a/Source/Core/MappedQuery.Capture.cs +++ b/Source/Core/MappedQuery.Capture.cs @@ -40,8 +40,7 @@ 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 query does not read from an /// expressive command, or the command's type re-implements @@ -80,7 +79,7 @@ public MappedQueryCore WithCapture(ICaptureSource source) CaptureSet captures = CaptureSet.With( _captures as CaptureSet, - source, onQuery: true, runner.IsProcedure); + source, onQuery: true); return new( _command, _call, _source, _skip, _take, Options, Config, captures); diff --git a/Source/Core/Output.docs.xml b/Source/Core/Output.docs.xml index 02d6d5dc..71c3f7c9 100644 --- a/Source/Core/Output.docs.xml +++ b/Source/Core/Output.docs.xml @@ -156,7 +156,6 @@ 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) (for a capture added to the command after the query was made, when the terminal or stream is called). @@ -206,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 (for a capture added to the command after the query was made, when the terminal or stream is called). @@ -214,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. @@ -233,13 +235,16 @@ 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. 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: diff --git a/Tests/Open.Database.Extensions.Core.Tests/CaptureLocalDbTests.cs b/Tests/Open.Database.Extensions.Core.Tests/CaptureLocalDbTests.cs index bf0519a9..fd529069 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() { diff --git a/Tests/Open.Database.Extensions.Core.Tests/CaptureTests.cs b/Tests/Open.Database.Extensions.Core.Tests/CaptureTests.cs index 6aa818dd..e9bc0112 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/CaptureTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/CaptureTests.cs @@ -366,21 +366,10 @@ 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") @@ -1070,4 +1059,77 @@ public static void ALateCommandCapture_ThatConflicts_ThrowsAtAStreamCall() "reads output parameter @total twice"); Assert.Equal(0, c.Executed); } + + // ---- 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/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/docsite/articles/expressive-commands.md b/docsite/articles/expressive-commands.md index 98f4952e..b189f05a 100644 --- a/docsite/articles/expressive-commands.md +++ b/docsite/articles/expressive-commands.md @@ -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,7 @@ 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; 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. +- **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 throws `InvalidOperationException` when it runs, before anything executes. Capture on a command that does not re-implement `IExecuteReader`, or read the outputs with `ExecuteOutputAsync`. - **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. diff --git a/docsite/articles/release-notes.md b/docsite/articles/release-notes.md index 6389a4cf..67faabe4 100644 --- a/docsite/articles/release-notes.md +++ b/docsite/articles/release-notes.md @@ -11,7 +11,7 @@ Version 11 is `11.0.0-rc.16`. For moving a 10.x codebase, read [Coming from earl - **Fixed: `CreateCommand` on a `SqlTransaction` that has no connection throws `InvalidOperationException`.** The SQL Server package threw `ArgumentNullException` named `connection`; it now reports "Transaction has no connection.", as the core package does. `CreateTextCommand` and `CreateStoredProcedureCommand` follow. - **Removed: parameter directions on the fluent chain.** `AddParam` and `AddParamIf` no longer take a `ParameterDirection`; `AddReturnParam` is gone, and `AddParam(name, direction)`, `AddParamIf(condition, name, direction)`, `AddParam(name, type)` and `AddParamIf(condition, name, type)` are now compile errors that say what to do instead. The forms that took a direction after the value, `AddParam(name, value, ParameterDirection)` and `AddParam(name, value, type, direction)` (the SQL Server forms with a database type and a direction too), fail to compile with the compiler's own argument error, without a message of their own: use the raw `AddParameter` inside `ExecuteAsync(command => ...)`, or read the output with `ExecuteOutputAsync`. A parameter on the chain is an input. To set a direction, use `ExecuteAsync(command => ...)` with the raw `AddParameter`, `AddParameterType` and `AddReturnParameter` extensions. Calls that never passed a direction compile unchanged, with one exception: a constant zero of type `byte` on the SQL Server command, `AddParam(name, (byte)0)`, used to bind silently to the direction overload and is now an ambiguous-call error (CS0121); pass a variable, or give the database type, `AddParam(name, value, SqlDbType.TinyInt)`. `Param` has no `direction` constructor parameter and no `Direction` property. - **Read output parameters: `ExecuteOutputAsync()`.** It maps a command's output parameters and return code into a model by name, with the `Map()` rules; `ExecuteOutputAsync(name)` reads one value, and `CaptureOutput(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: `NotSupportedException` on a query made from a definition or one that does not read from an expressive command, `InvalidOperationException` otherwise. A command whose type re-implements `IExecuteReader` is refused too, as `NotSupportedException` on a query capture and `InvalidOperationException` when a command capture runs. See [Output parameters beside rows](expressive-commands.md#output-parameters-beside-rows). +- **New: captures, output parameters beside rows.** `CaptureOutput` (a model, one value, or a `decimal` with its precision and scale), `CaptureOutputDecimal` and `CaptureReturn` on an expressive command, a mapped query and its `Skip` and `Take` views give a `DbCapture` as an `out` argument; the async terminal fills it, and a stream fills it when its loop ends, a `break` included. A capture runs once and needs an async terminal; a query's run fills the captures its command has when the run starts, including one added after `Map`. Misuse throws at the call, except that the return code of a command that is not a stored procedure is refused when the run starts: `NotSupportedException` on a query 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..4f3085e6 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!; }); From dbaf9a2d53eb23e0c1e7e7271cb6e74fe4f1115b Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Wed, 2 Dec 2026 09:27:12 -0800 Subject: [PATCH 5/6] Docs for the AddParam database-type trap, a pin for ordinal gaps, and style fixes AddParam("@id", DbType.Int32) on a SQL Server command binds to the value overload and sends the enum as the value. No code guard works (a derived overload would capture AddParam("x", 0), and on the generic base the existing trap collides), so the shared AddParam remarks now say that a DbType passed there is a value, and that the database type goes in the third argument. An output model with Order values 0 and 2 is pinned to behave as a row model does: the gap is not read, and the map accepts the null label of the gap. Members of internal types that were marked internal are public, and the list of refused terminals in a capture test is grouped. Co-Authored-By: Claude Sonnet 5.5 --- Source/Core/ExpressiveCommandBase.cs | 4 +++ Source/Core/NameSet.cs | 2 +- Source/Core/ReaderReplacement.cs | 4 +-- .../CaptureStreamTests.cs | 12 +++------ .../OutputParameterTests.cs | 26 +++++++++++++++++++ 5 files changed, 36 insertions(+), 12 deletions(-) diff --git a/Source/Core/ExpressiveCommandBase.cs b/Source/Core/ExpressiveCommandBase.cs index 5dd48d12..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. diff --git a/Source/Core/NameSet.cs b/Source/Core/NameSet.cs index 948a9d3a..fe5005c0 100644 --- a/Source/Core/NameSet.cs +++ b/Source/Core/NameSet.cs @@ -121,7 +121,7 @@ public int GetHashCode(string obj) /// What to do about an ambiguity. /// The real name, or when the name matches none. /// The name fits more than one parameter equally well. - internal string? MatchName(string name, string procedure, string subject, string fix) + public string? MatchName(string name, string procedure, string subject, string fix) { if (_nameMatches.TryGetValue(name, out string? remembered)) return remembered; diff --git a/Source/Core/ReaderReplacement.cs b/Source/Core/ReaderReplacement.cs index 47c56a72..d668b9c6 100644 --- a/Source/Core/ReaderReplacement.cs +++ b/Source/Core/ReaderReplacement.cs @@ -19,7 +19,7 @@ static class ReaderReplacement /// The command type. /// The count: one after the first captured run of a type that /// is not a library command, never more. - internal static int LookupCount(Type type) + public static int LookupCount(Type type) => Lookups.TryGetValue(type, out StrongBox? count) ? Volatile.Read(ref count.Value) : 0; @@ -32,7 +32,7 @@ internal static int LookupCount(Type type) /// than the library's command bases. /// The lookup failed; the /// failure is not cached, so the next call looks again. - internal static bool Of(Type type) + public static bool Of(Type type) => ReferenceEquals(Answers.GetValue(type, Detect), Replaced); static object Detect(Type type) diff --git a/Tests/Open.Database.Extensions.Core.Tests/CaptureStreamTests.cs b/Tests/Open.Database.Extensions.Core.Tests/CaptureStreamTests.cs index 42a321c6..75358962 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/CaptureStreamTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/CaptureStreamTests.cs @@ -642,15 +642,9 @@ public static void AQueryCapture_OnAReimplementingCommand_IsRefusedAtTheCall() public static TheoryData RefusedTerminals => new( - "ToListAsync", - "Stream", - "ToPooledBuffer", - "ToChannelReader", - "AsSourceBlock", - "ToTargetBlock", - "AnyAsync", - "AsObjectArrays", - "SingleResult"); + "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. 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() { From ffaa237d1a667e792c6fff92395d6f91b80c4125 Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Wed, 2 Dec 2026 09:46:02 -0800 Subject: [PATCH 6/6] Captures: review fixes to the docs and tests Docs and comments: - A capture on a command that re-implements IExecuteReader is refused when a mapped query over the command runs; the command's own terminals do not use the re-implemented reader. Reworded in the MappedQuery comment, the shared output docs and the expressive commands article. - The capture name docs say that the same name, ignoring case, fails at the call, and that only a looser match fails the run. - ReaderReplacement.LookupCount counts one per successful lookup; a failed lookup is retried and counted again. - WithCapture lists the lookup failure it can throw. - Cut the repeated name-rule, late-capture, and ordering wording. - Re-indented one comment in the output parameters sample. Tests: - A late conflicting command capture keeps its captures and asserts that they stay unarmed, with the fix text, and a synchronous terminal case. - A capture added after a stream or buffer is made is not filled. - A named capture and ExecuteOutputAsync find a p_ prefixed parameter. - ExecuteOutputAsync works on a command that re-implements its reader. Co-Authored-By: Claude Sonnet 5.5 --- Source/Core/Capture.cs | 4 +- Source/Core/MappedQuery.Capture.cs | 3 + Source/Core/MappedQuery.cs | 11 +-- Source/Core/Output.docs.xml | 19 ++--- Source/Core/ReaderReplacement.cs | 5 +- .../CaptureLocalDbTests.cs | 25 ++++++ .../CaptureStreamTests.cs | 15 ++++ .../CaptureTests.cs | 77 ++++++++++++++++++- docsite/articles/expressive-commands.md | 2 +- docsite/samples/OutputParameters.cs | 2 +- 10 files changed, 139 insertions(+), 24 deletions(-) diff --git a/Source/Core/Capture.cs b/Source/Core/Capture.cs index 9c22f820..17c77705 100644 --- a/Source/Core/Capture.cs +++ b/Source/Core/Capture.cs @@ -460,8 +460,8 @@ sealed class Combination(CaptureSet command, CaptureSet result) Combination? _combined; /// - /// Gets what a run fills: the command's captures as they are now, then - /// these, the query's own. + /// 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 diff --git a/Source/Core/MappedQuery.Capture.cs b/Source/Core/MappedQuery.Capture.cs index ba4e1ca6..b4fd321c 100644 --- a/Source/Core/MappedQuery.Capture.cs +++ b/Source/Core/MappedQuery.Capture.cs @@ -42,6 +42,9 @@ public CaptureRun? CapturedRun /// A copy of the query that carries the capture. /// 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, or the command's type re-implements /// , which a capture cannot read diff --git a/Source/Core/MappedQuery.cs b/Source/Core/MappedQuery.cs index 0e4a295d..67c034cc 100644 --- a/Source/Core/MappedQuery.cs +++ b/Source/Core/MappedQuery.cs @@ -495,11 +495,12 @@ 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). - // A command that re-implements IExecuteReader is refused here, the one - // place every captured run passes (a capture made on the command, not the - // query, is not checked at a capture call): its own reader would skip the - // output parameters. The refusal is the task's exception, and completes - // every capture. + // 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) { if (Captured() is not { } captures) diff --git a/Source/Core/Output.docs.xml b/Source/Core/Output.docs.xml index 71c3f7c9..7dc4c543 100644 --- a/Source/Core/Output.docs.xml +++ b/Source/Core/Output.docs.xml @@ -52,8 +52,8 @@ - The name of the output parameter, with or without its @, matched 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. - Two captures that match one parameter fail the run, not this call. + 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. @@ -169,7 +169,7 @@ 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 (for a capture added to the command after the query was made, when the terminal or stream is called). + or another capture reads the same parameter. @@ -185,7 +185,7 @@ At the call: is not or a of it; - or another capture reads the same parameter (for a capture added to the command after the query was made, when the terminal or stream is called). + or another capture reads the same parameter. @@ -198,7 +198,7 @@ is 0 or more than 38, or is more than . - At the call: another capture reads the same parameter (for a capture added to the command after the query was made, when the terminal or stream is called). + At the call: another capture reads the same parameter. @@ -206,7 +206,7 @@ The capture: await it after the terminal. At the call: is a model; - or another capture reads the return code (for a capture added to the command after the query was made, when the terminal or stream is called). + or another capture reads the return code. @@ -224,9 +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: the capture reads through the library's reader, - so the run throws (and completes the capture with it) before anything is executed. - Capture on a command that does not re-implement it, or read the outputs with ExecuteOutputAsync. + 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. diff --git a/Source/Core/ReaderReplacement.cs b/Source/Core/ReaderReplacement.cs index d668b9c6..d2c189d0 100644 --- a/Source/Core/ReaderReplacement.cs +++ b/Source/Core/ReaderReplacement.cs @@ -17,8 +17,9 @@ static class ReaderReplacement /// Gets how many times the type was looked up with /// reflection. /// The command type. - /// The count: one after the first captured run of a type that - /// is not a library command, never more. + /// 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) diff --git a/Tests/Open.Database.Extensions.Core.Tests/CaptureLocalDbTests.cs b/Tests/Open.Database.Extensions.Core.Tests/CaptureLocalDbTests.cs index fd529069..da5fb494 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/CaptureLocalDbTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/CaptureLocalDbTests.cs @@ -279,6 +279,31 @@ public static async Task TwoNamedCaptures_OnOneParameter_FailTheRun() 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 75358962..b434ed45 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/CaptureStreamTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/CaptureStreamTests.cs @@ -802,6 +802,21 @@ public static async Task AReimplementingCommand_WithoutACapture_RunsItsOwnReader 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() { diff --git a/Tests/Open.Database.Extensions.Core.Tests/CaptureTests.cs b/Tests/Open.Database.Extensions.Core.Tests/CaptureTests.cs index e9bc0112..6007687f 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/CaptureTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/CaptureTests.cs @@ -374,7 +374,8 @@ public static void TheReturnCode_NeedsAnInteger() Assert.Throws(() => c .StoredProcedure("p") .CaptureReturn(out DbCapture _)), - "CaptureReturn cannot hold it"); + "CaptureReturn cannot hold it", + "Use CaptureReturn"); } [Fact] @@ -1034,12 +1035,37 @@ 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 _); - command.CaptureOutput("total", out DbCapture _); + .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); } @@ -1056,10 +1082,53 @@ public static void ALateCommandCapture_ThatConflicts_ThrowsAtAStreamCall() Contains( Assert.Throws( () => query.ToPooledStream(Token)), - "reads output parameter @total twice"); + "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] diff --git a/docsite/articles/expressive-commands.md b/docsite/articles/expressive-commands.md index b189f05a..76e023c7 100644 --- a/docsite/articles/expressive-commands.md +++ b/docsite/articles/expressive-commands.md @@ -248,7 +248,7 @@ 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 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 throws `InvalidOperationException` when it runs, before anything executes. Capture on a command that does not re-implement `IExecuteReader`, or read the outputs with `ExecuteOutputAsync`. +- **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/samples/OutputParameters.cs b/docsite/samples/OutputParameters.cs index 4f3085e6..2ee83068 100644 --- a/docsite/samples/OutputParameters.cs +++ b/docsite/samples/OutputParameters.cs @@ -162,7 +162,7 @@ await Blog await command.ExecuteNonQueryAsync(cancellationToken); // 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. + // which the cast throws on: cast only what the procedure always sets. id = (int)output.Value!; returned = (int)returnCode.Value!; });