From d784109e791a96c57d036f88e66444f6ab6a77fb Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Tue, 1 Dec 2026 18:16:32 -0800 Subject: [PATCH 01/20] Remove the parameter direction from the fluent expressive-command chain. AddParam and AddParamIf no longer take a ParameterDirection, the overloads that took only a type or only a direction are gone, and so are AddReturnParam and the SQL Server DbType-and-direction overloads. A parameter on the chain is an input; a direction is set with the raw AddParameter, AddParameterType and AddReturnParameter extensions inside ExecuteAsync(command => ...), which are unchanged. Calls that never passed a direction compile unchanged. Tests of the removed API are deleted, the PublicAPI files and docs are updated. Co-Authored-By: Claude Sonnet 5.5 --- Source/Core/ExpressiveCommand.cs | 1 - Source/Core/ExpressiveCommandBase.Param.cs | 2 +- Source/Core/ExpressiveCommandBase.cs | 202 +++++++----------- Source/Core/ExpressiveDbCommand.cs | 1 - Source/Core/PublicAPI.Unshipped.txt | 54 +++++ Source/MSSqlClient/ExpressiveSqlCommand.cs | 33 +-- Source/MSSqlClient/PublicAPI.Unshipped.txt | 2 + Source/SqlClient/ExpressiveSqlCommand.cs | 30 --- .../CancelOnEarlyStopTests.cs | 22 +- .../ClassicParamPathsAllocationTests.cs | 49 ----- .../DerivedParameterNameTests.cs | 4 +- .../ExpressiveCommandParamTests.cs | 9 - .../ParameterBindingMatrixTests.cs | 36 ++-- .../ParameterDirectionTests.cs | 113 ---------- .../ParameterNameExplicitTests.cs | 1 - .../ParameterTypeOverloadTests.cs | 8 - .../SqlServerPackageTests.cs | 24 +-- .../SqlServerParameterTypeTests.cs | 55 +---- .../TypedNullParameterTests.cs | 42 ---- .../ParameterTypeTests.cs | 8 - docsite/articles/coming-from-dapper.md | 2 +- docsite/articles/expressive-commands.md | 6 +- docsite/articles/release-notes.md | 1 + docsite/articles/whats-new-11.md | 4 +- 24 files changed, 184 insertions(+), 525 deletions(-) delete mode 100644 Tests/Open.Database.Extensions.Core.Tests/ParameterDirectionTests.cs diff --git a/Source/Core/ExpressiveCommand.cs b/Source/Core/ExpressiveCommand.cs index e804fb5a..b898fb01 100644 --- a/Source/Core/ExpressiveCommand.cs +++ b/Source/Core/ExpressiveCommand.cs @@ -131,7 +131,6 @@ protected override void AddParams(IDbCommand command) foreach (Param p in Params) { IDbDataParameter np = command.AddParameter(p.Name, p.Value); - np.Direction = p.Direction; if (p.Type.HasValue) np.DbType = p.Type.Value; else if (p.NullDbType is { } nullType) np.DbType = nullType; // a NULL carries no type, so give it the argument's } diff --git a/Source/Core/ExpressiveCommandBase.Param.cs b/Source/Core/ExpressiveCommandBase.Param.cs index 5bfcb090..dec5433e 100644 --- a/Source/Core/ExpressiveCommandBase.Param.cs +++ b/Source/Core/ExpressiveCommandBase.Param.cs @@ -98,7 +98,7 @@ internal static Param Derived(string name, string expression, object? value, Typ /// The database type, or to let the provider infer it. /// The direction of the parameter. /// The parameter. - internal static Param Typed(string name, object? value, Type clrType, TDbType? type, ParameterDirection direction) + internal static Param Typed(string name, object? value, Type clrType, TDbType? type, ParameterDirection direction = ParameterDirection.Input) => new(name, value, expression: null, fromObject: false, clrType, type, direction); /// diff --git a/Source/Core/ExpressiveCommandBase.cs b/Source/Core/ExpressiveCommandBase.cs index 70d88d61..4b8fa5b4 100644 --- a/Source/Core/ExpressiveCommandBase.cs +++ b/Source/Core/ExpressiveCommandBase.cs @@ -373,7 +373,6 @@ protected TThis AddParam(Param param) /// The name of the parameter. /// The value of the parameter. /// The database type of the parameter. - /// The direction of the parameter. /// This instance for use in method chaining. /// /// A passed to an overload @@ -382,91 +381,88 @@ protected TThis AddParam(Param param) /// is sent with the database type of that type, /// the same choice AddParams makes for a NULL member. /// A you pass always wins. - /// The overloads have no type to use, - /// and neither does a call that gives the direction by position - /// (AddParam(name, value, ParameterDirection.Input)): - /// pass a database type, or name the direction - /// (direction: ...). + /// The overloads have no type to use: + /// pass a database type. /// /// is . /// is empty or white space. - public TThis AddParam(string name, object? value, TDbType type, ParameterDirection direction = ParameterDirection.Input) - => AddParam(new(name, value, type, direction)); + public TThis AddParam(string name, object? value, TDbType type) + => AddParam(new(name, value, type)); - /// - public TThis AddParam(string name, object? value, ParameterDirection direction = ParameterDirection.Input) - => AddParam(new(name, value, null, direction)); + /// + public TThis AddParam(string name, object? value) + => AddParam(new(name, value, null)); /// The type of the value. - /// - public TThis AddParam(string name, T? value, TDbType? type = null, ParameterDirection direction = ParameterDirection.Input) + /// + public TThis AddParam(string name, T? value, TDbType? type = null) where T : struct - => AddParam(Param.Typed(name, value, typeof(T), type, direction)); + => AddParam(Param.Typed(name, value, typeof(T), type)); - // Without this overload, a literal 0 converts to an enum and binds to a type-only or direction-only overload, adding a parameter with no value. + // A literal 0 converts to any enum; this overload is the better match, so the 0 stays a value. /// /// Adds a parameter with an value. /// - /// - public TThis AddParam(string name, int value, TDbType? type = null, ParameterDirection direction = ParameterDirection.Input) - => AddParam(new(name, value, type, direction)); + /// + public TThis AddParam(string name, int value, TDbType? type = null) + => AddParam(new(name, value, type)); - // Without this overload, a literal 0L converts to an enum and binds to a type-only or direction-only overload, adding a parameter with no value. + // A literal 0L converts to any enum; this overload is the better match, so the 0L stays a value. /// /// Adds a parameter with a value. /// - /// - public TThis AddParam(string name, long value, TDbType? type = null, ParameterDirection direction = ParameterDirection.Input) - => AddParam(new(name, value, type, direction)); + /// + public TThis AddParam(string name, long value, TDbType? type = null) + => AddParam(new(name, value, type)); // A char converts implicitly to int; without this overload 'c' would be sent as its code. /// /// Adds a parameter with a value, sent as a character. /// - /// - public TThis AddParam(string name, char value, TDbType? type = null, ParameterDirection direction = ParameterDirection.Input) - => AddParam(new(name, value, type, direction)); + /// + public TThis AddParam(string name, char value, TDbType? type = null) + => AddParam(new(name, value, type)); - /// - public TThis AddParam(string name, string? value, TDbType? type = null, ParameterDirection direction = ParameterDirection.Input) - => AddParam(Param.Typed(name, value, typeof(string), type, direction)); + /// + public TThis AddParam(string name, string? value, TDbType? type = null) + => AddParam(Param.Typed(name, value, typeof(string), type)); // A required TDbType makes this the best match; with the optional-type overloads alone, AddParam("id", id, SqlDbType.Int) is ambiguous (CS0121). /// /// Adds a parameter with an value and a required /// database type. /// - /// - public TThis AddParam(string name, int value, TDbType type, ParameterDirection direction = ParameterDirection.Input) - => AddParam(new(name, value, type, direction)); + /// + public TThis AddParam(string name, int value, TDbType type) + => AddParam(new(name, value, type)); // Required type: see the int overload with a required TDbType. /// /// Adds a parameter with a value and a required /// database type. /// - /// - public TThis AddParam(string name, long value, TDbType type, ParameterDirection direction = ParameterDirection.Input) - => AddParam(new(name, value, type, direction)); + /// + public TThis AddParam(string name, long value, TDbType type) + => AddParam(new(name, value, type)); // A char has its own overload so it is not widened to int and sent as its code; the type is required for the reason given on the int overload. /// /// Adds a parameter with a value, sent as a character, and a required /// database type. /// - /// - public TThis AddParam(string name, char value, TDbType type, ParameterDirection direction = ParameterDirection.Input) - => AddParam(new(name, value, type, direction)); + /// + public TThis AddParam(string name, char value, TDbType type) + => AddParam(new(name, value, type)); - /// - public TThis AddParam(string name, string? value, TDbType type, ParameterDirection direction = ParameterDirection.Input) - => AddParam(Param.Typed(name, value, typeof(string), type, direction)); + /// + public TThis AddParam(string name, string? value, TDbType type) + => AddParam(Param.Typed(name, value, typeof(string), type)); /// The type of the value. - /// - public TThis AddParam(string name, T? value, TDbType type, ParameterDirection direction = ParameterDirection.Input) + /// + public TThis AddParam(string name, T? value, TDbType type) where T : struct - => AddParam(Param.Typed(name, value, typeof(T), type, direction)); + => AddParam(Param.Typed(name, value, typeof(T), type)); // Needed for compilers before C# 13, which ignore OverloadResolutionPriority: without it AddParam("name", someString) binds to AddParam(T, string?), reading the name as the value. /// @@ -474,28 +470,16 @@ public TThis AddParam(string name, T? value, TDbType type, ParameterDirection /// /// The name of the parameter. /// The value of the parameter. - /// + /// public TThis AddParam(string name, string? value) - => AddParam(name, value, null, ParameterDirection.Input); - - /// - public TThis AddParam(string name, TDbType type, ParameterDirection direction = ParameterDirection.Input) - => AddParam(new(name, null, type, direction)); - - // Requiring the direction keeps AddParam(filter.Name) on the derived-name overload AddParam(T, string?). - /// - /// Adds a parameter with no value and the direction given. - /// - /// - public TThis AddParam(string name, ParameterDirection direction) - => AddParam(new(name, null, null, direction)); + => AddParam(name, value, null); /// /// Adds an input parameter whose name is taken from the argument expression: AddParam(filter.AuthorId) adds a parameter named for AuthorId. /// /// /// The argument must be a variable or a chain of member accesses (properties and fields alike): startDate, filter.AuthorId, post.Author.Id. - /// Anything else (a call, an index, an operator, a literal) throws : use and name the parameter. + /// Anything else (a call, an index, an operator, a literal) throws : use and name the parameter. /// The name is settled when the command executes. The real parameter names are: /// /// for a stored procedure, the names the provider reports for the procedure; @@ -632,17 +616,6 @@ static ArgumentException NotDerivable(string? expression) ? new("The compiler did not supply the argument's text (deriving a name needs C# 10 or newer). Pass the name explicitly: AddParam(\"name\", value).", "value") : new($"Cannot derive a parameter name from the argument '{expression}'. Pass a variable or a chain of members such as filter.CompanySerialNum, or name the parameter: AddParam(\"name\", value).", "value"); - /// - /// Adds a return parameter to the params list. - /// - /// - public TThis AddReturnParam(string name, TDbType type) - => AddParam(new(name, null, type, ParameterDirection.ReturnValue)); - - /// - public TThis AddReturnParam(string name) - => AddParam(new(name, null, null, ParameterDirection.ReturnValue)); - /// /// Conditionally adds a parameter to the params list. /// @@ -650,20 +623,19 @@ public TThis AddReturnParam(string name) /// The name of the parameter. /// The value of the parameter. /// The database type of the parameter. - /// The direction of the parameter. - /// - public TThis AddParamIf(bool condition, string name, object? value, TDbType type, ParameterDirection direction = ParameterDirection.Input) - => condition ? AddParam(name, value, type, direction) : (TThis)this; + /// + public TThis AddParamIf(bool condition, string name, object? value, TDbType type) + => condition ? AddParam(name, value, type) : (TThis)this; /// The type of the value. - /// - public TThis AddParamIf(bool condition, string name, T? value, ParameterDirection direction = ParameterDirection.Input) + /// + public TThis AddParamIf(bool condition, string name, T? value) where T : struct - => condition ? AddParam(name, value, null, direction) : (TThis)this; + => condition ? AddParam(name, value, null) : (TThis)this; - /// - public TThis AddParamIf(bool condition, string name, object? value, ParameterDirection direction = ParameterDirection.Input) - => condition ? AddParam(name, value, direction) : (TThis)this; + /// + public TThis AddParamIf(bool condition, string name, object? value) + => condition ? AddParam(name, value) : (TThis)this; // Needed for compilers before C# 13, which ignore OverloadResolutionPriority: without it AddParamIf(condition, "name", someString) binds to AddParamIf(bool, T, string?), reading the name as the value. /// @@ -672,57 +644,49 @@ public TThis AddParamIf(bool condition, string name, object? value, ParameterDir /// /// The name of the parameter. /// The value of the parameter. - /// + /// public TThis AddParamIf(bool condition, string name, string? value) - => condition ? AddParam(name, value, null, ParameterDirection.Input) : (TThis)this; + => condition ? AddParam(name, value, null) : (TThis)this; /// The type of the value. - /// - public TThis AddParamIf(bool condition, string name, T? value, TDbType? type, ParameterDirection direction = ParameterDirection.Input) + /// + public TThis AddParamIf(bool condition, string name, T? value, TDbType? type) where T : struct - => condition ? AddParam(name, value, type, direction) : (TThis)this; + => condition ? AddParam(name, value, type) : (TThis)this; - /// - public TThis AddParamIf(bool condition, string name, int value, TDbType? type = null, ParameterDirection direction = ParameterDirection.Input) - => condition ? AddParam(name, value, type, direction) : (TThis)this; + /// + public TThis AddParamIf(bool condition, string name, int value, TDbType? type = null) + => condition ? AddParam(name, value, type) : (TThis)this; - /// - public TThis AddParamIf(bool condition, string name, long value, TDbType? type = null, ParameterDirection direction = ParameterDirection.Input) - => condition ? AddParam(name, value, type, direction) : (TThis)this; + /// + public TThis AddParamIf(bool condition, string name, long value, TDbType? type = null) + => condition ? AddParam(name, value, type) : (TThis)this; - /// - public TThis AddParamIf(bool condition, string name, char value, TDbType? type = null, ParameterDirection direction = ParameterDirection.Input) - => condition ? AddParam(name, value, type, direction) : (TThis)this; + /// + public TThis AddParamIf(bool condition, string name, char value, TDbType? type = null) + => condition ? AddParam(name, value, type) : (TThis)this; - /// - public TThis AddParamIf(bool condition, string name, int value, TDbType type, ParameterDirection direction = ParameterDirection.Input) - => condition ? AddParam(name, value, type, direction) : (TThis)this; + /// + public TThis AddParamIf(bool condition, string name, int value, TDbType type) + => condition ? AddParam(name, value, type) : (TThis)this; - /// - public TThis AddParamIf(bool condition, string name, long value, TDbType type, ParameterDirection direction = ParameterDirection.Input) - => condition ? AddParam(name, value, type, direction) : (TThis)this; + /// + public TThis AddParamIf(bool condition, string name, long value, TDbType type) + => condition ? AddParam(name, value, type) : (TThis)this; - /// - public TThis AddParamIf(bool condition, string name, char value, TDbType type, ParameterDirection direction = ParameterDirection.Input) - => condition ? AddParam(name, value, type, direction) : (TThis)this; + /// + public TThis AddParamIf(bool condition, string name, char value, TDbType type) + => condition ? AddParam(name, value, type) : (TThis)this; - /// - public TThis AddParamIf(bool condition, string name, string? value, TDbType type, ParameterDirection direction = ParameterDirection.Input) - => condition ? AddParam(name, value, type, direction) : (TThis)this; + /// + public TThis AddParamIf(bool condition, string name, string? value, TDbType type) + => condition ? AddParam(name, value, type) : (TThis)this; /// The type of the value. - /// - public TThis AddParamIf(bool condition, string name, T? value, TDbType type, ParameterDirection direction = ParameterDirection.Input) + /// + public TThis AddParamIf(bool condition, string name, T? value, TDbType type) where T : struct - => condition ? AddParam(name, value, type, direction) : (TThis)this; - - /// - public TThis AddParamIf(bool condition, string name, TDbType type, ParameterDirection direction = ParameterDirection.Input) - => condition ? AddParam(name, type, direction) : (TThis)this; - - /// - public TThis AddParamIf(bool condition, string name, ParameterDirection direction) - => condition ? AddParam(name, direction) : (TThis)this; + => condition ? AddParam(name, value, type) : (TThis)this; /// /// Handles adding the list of parameters to a new command. @@ -976,7 +940,7 @@ void ResolveWritten(List send, NameSet text) continue; } - // Two spellings of one name that the text declares, of any direction, are both sent as written, as they always were. + // Two spellings of one name that the text declares are both sent as written, as they always were. bool collides = false; for (int j = 0; j < i; j++) { @@ -987,7 +951,7 @@ void ResolveWritten(List send, NameSet text) } } - send.Add(collides || p.Direction != ParameterDirection.Input || string.Equals(entry.Real, p.Name, StringComparison.Ordinal) ? p : p.Resolved(entry.Real)); + send.Add(collides || string.Equals(entry.Real, p.Name, StringComparison.Ordinal) ? p : p.Resolved(entry.Real)); } } @@ -1034,7 +998,7 @@ void Apply( if (p.Expression is not { } expression) { // A name written without its @ goes under the spelling a text command declares. - names[i] = p.Direction == ParameterDirection.Input && Type == CommandType.Text && real is { Names.Length: > 0 } && real.Find(p.Name) is { } declared + names[i] = Type == CommandType.Text && real is { Names.Length: > 0 } && real.Find(p.Name) is { } declared ? declared.Real : p.Name; continue; diff --git a/Source/Core/ExpressiveDbCommand.cs b/Source/Core/ExpressiveDbCommand.cs index 6527cfe0..f216c92d 100644 --- a/Source/Core/ExpressiveDbCommand.cs +++ b/Source/Core/ExpressiveDbCommand.cs @@ -144,7 +144,6 @@ protected override void AddParams(DbCommand command) foreach (Param p in Params) { IDbDataParameter np = command.AddParameter(p.Name, p.Value); - np.Direction = p.Direction; if (p.Type.HasValue) np.DbType = p.Type.Value; else if (p.NullDbType is { } nullType) np.DbType = nullType; // a NULL carries no type, so give it the argument's } diff --git a/Source/Core/PublicAPI.Unshipped.txt b/Source/Core/PublicAPI.Unshipped.txt index ca9ac00a..b554d224 100644 --- a/Source/Core/PublicAPI.Unshipped.txt +++ b/Source/Core/PublicAPI.Unshipped.txt @@ -13,3 +13,57 @@ Open.Database.Extensions.MappedQueryWithTake.SequentialAccess() -> Open.Datab static Open.Database.Extensions.Synchronous.SyncCommandExtensions.ToDataTable(this System.Data.IDbCommand! command, System.Data.CommandBehavior behavior = System.Data.CommandBehavior.Default) -> System.Data.DataTable! *REMOVED*static Open.Database.Extensions.Synchronous.SyncCommandExtensions.ToDataTables(this System.Data.IDbCommand! command, System.Data.CommandBehavior behavior = System.Data.CommandBehavior.SequentialAccess) -> System.Collections.Generic.List! static Open.Database.Extensions.Synchronous.SyncCommandExtensions.ToDataTables(this System.Data.IDbCommand! command, System.Data.CommandBehavior behavior = System.Data.CommandBehavior.Default) -> System.Collections.Generic.List! +*REMOVED*Open.Database.Extensions.ExpressiveCommandBase.AddParam(string! name, System.Data.ParameterDirection direction) -> TThis! +*REMOVED*Open.Database.Extensions.ExpressiveCommandBase.AddParam(string! name, TDbType type, System.Data.ParameterDirection direction = System.Data.ParameterDirection.Input) -> TThis! +*REMOVED*Open.Database.Extensions.ExpressiveCommandBase.AddParam(string! name, char value, TDbType type, System.Data.ParameterDirection direction = System.Data.ParameterDirection.Input) -> TThis! +Open.Database.Extensions.ExpressiveCommandBase.AddParam(string! name, char value, TDbType type) -> TThis! +*REMOVED*Open.Database.Extensions.ExpressiveCommandBase.AddParam(string! name, char value, TDbType? type = null, System.Data.ParameterDirection direction = System.Data.ParameterDirection.Input) -> TThis! +Open.Database.Extensions.ExpressiveCommandBase.AddParam(string! name, char value, TDbType? type = null) -> TThis! +*REMOVED*Open.Database.Extensions.ExpressiveCommandBase.AddParam(string! name, int value, TDbType type, System.Data.ParameterDirection direction = System.Data.ParameterDirection.Input) -> TThis! +Open.Database.Extensions.ExpressiveCommandBase.AddParam(string! name, int value, TDbType type) -> TThis! +*REMOVED*Open.Database.Extensions.ExpressiveCommandBase.AddParam(string! name, int value, TDbType? type = null, System.Data.ParameterDirection direction = System.Data.ParameterDirection.Input) -> TThis! +Open.Database.Extensions.ExpressiveCommandBase.AddParam(string! name, int value, TDbType? type = null) -> TThis! +*REMOVED*Open.Database.Extensions.ExpressiveCommandBase.AddParam(string! name, long value, TDbType type, System.Data.ParameterDirection direction = System.Data.ParameterDirection.Input) -> TThis! +Open.Database.Extensions.ExpressiveCommandBase.AddParam(string! name, long value, TDbType type) -> TThis! +*REMOVED*Open.Database.Extensions.ExpressiveCommandBase.AddParam(string! name, long value, TDbType? type = null, System.Data.ParameterDirection direction = System.Data.ParameterDirection.Input) -> TThis! +Open.Database.Extensions.ExpressiveCommandBase.AddParam(string! name, long value, TDbType? type = null) -> TThis! +*REMOVED*Open.Database.Extensions.ExpressiveCommandBase.AddParam(string! name, object? value, System.Data.ParameterDirection direction = System.Data.ParameterDirection.Input) -> TThis! +Open.Database.Extensions.ExpressiveCommandBase.AddParam(string! name, object? value) -> TThis! +*REMOVED*Open.Database.Extensions.ExpressiveCommandBase.AddParam(string! name, string? value, TDbType type, System.Data.ParameterDirection direction = System.Data.ParameterDirection.Input) -> TThis! +Open.Database.Extensions.ExpressiveCommandBase.AddParam(string! name, string? value, TDbType type) -> TThis! +*REMOVED*Open.Database.Extensions.ExpressiveCommandBase.AddParam(string! name, string? value, TDbType? type = null, System.Data.ParameterDirection direction = System.Data.ParameterDirection.Input) -> TThis! +Open.Database.Extensions.ExpressiveCommandBase.AddParam(string! name, string? value, TDbType? type = null) -> TThis! +*REMOVED*Open.Database.Extensions.ExpressiveCommandBase.AddParam(string! name, T? value, TDbType type, System.Data.ParameterDirection direction = System.Data.ParameterDirection.Input) -> TThis! +Open.Database.Extensions.ExpressiveCommandBase.AddParam(string! name, T? value, TDbType type) -> TThis! +*REMOVED*Open.Database.Extensions.ExpressiveCommandBase.AddParam(string! name, T? value, TDbType? type = null, System.Data.ParameterDirection direction = System.Data.ParameterDirection.Input) -> TThis! +Open.Database.Extensions.ExpressiveCommandBase.AddParam(string! name, T? value, TDbType? type = null) -> TThis! +*REMOVED*Open.Database.Extensions.ExpressiveCommandBase.AddParamIf(bool condition, string! name, System.Data.ParameterDirection direction) -> TThis! +*REMOVED*Open.Database.Extensions.ExpressiveCommandBase.AddParamIf(bool condition, string! name, TDbType type, System.Data.ParameterDirection direction = System.Data.ParameterDirection.Input) -> TThis! +*REMOVED*Open.Database.Extensions.ExpressiveCommandBase.AddParamIf(bool condition, string! name, char value, TDbType type, System.Data.ParameterDirection direction = System.Data.ParameterDirection.Input) -> TThis! +Open.Database.Extensions.ExpressiveCommandBase.AddParamIf(bool condition, string! name, char value, TDbType type) -> TThis! +*REMOVED*Open.Database.Extensions.ExpressiveCommandBase.AddParamIf(bool condition, string! name, char value, TDbType? type = null, System.Data.ParameterDirection direction = System.Data.ParameterDirection.Input) -> TThis! +Open.Database.Extensions.ExpressiveCommandBase.AddParamIf(bool condition, string! name, char value, TDbType? type = null) -> TThis! +*REMOVED*Open.Database.Extensions.ExpressiveCommandBase.AddParamIf(bool condition, string! name, int value, TDbType type, System.Data.ParameterDirection direction = System.Data.ParameterDirection.Input) -> TThis! +Open.Database.Extensions.ExpressiveCommandBase.AddParamIf(bool condition, string! name, int value, TDbType type) -> TThis! +*REMOVED*Open.Database.Extensions.ExpressiveCommandBase.AddParamIf(bool condition, string! name, int value, TDbType? type = null, System.Data.ParameterDirection direction = System.Data.ParameterDirection.Input) -> TThis! +Open.Database.Extensions.ExpressiveCommandBase.AddParamIf(bool condition, string! name, int value, TDbType? type = null) -> TThis! +*REMOVED*Open.Database.Extensions.ExpressiveCommandBase.AddParamIf(bool condition, string! name, long value, TDbType type, System.Data.ParameterDirection direction = System.Data.ParameterDirection.Input) -> TThis! +Open.Database.Extensions.ExpressiveCommandBase.AddParamIf(bool condition, string! name, long value, TDbType type) -> TThis! +*REMOVED*Open.Database.Extensions.ExpressiveCommandBase.AddParamIf(bool condition, string! name, long value, TDbType? type = null, System.Data.ParameterDirection direction = System.Data.ParameterDirection.Input) -> TThis! +Open.Database.Extensions.ExpressiveCommandBase.AddParamIf(bool condition, string! name, long value, TDbType? type = null) -> TThis! +*REMOVED*Open.Database.Extensions.ExpressiveCommandBase.AddParamIf(bool condition, string! name, object? value, System.Data.ParameterDirection direction = System.Data.ParameterDirection.Input) -> TThis! +Open.Database.Extensions.ExpressiveCommandBase.AddParamIf(bool condition, string! name, object? value) -> TThis! +*REMOVED*Open.Database.Extensions.ExpressiveCommandBase.AddParamIf(bool condition, string! name, string? value, TDbType type, System.Data.ParameterDirection direction = System.Data.ParameterDirection.Input) -> TThis! +Open.Database.Extensions.ExpressiveCommandBase.AddParamIf(bool condition, string! name, string? value, TDbType type) -> TThis! +*REMOVED*Open.Database.Extensions.ExpressiveCommandBase.AddParamIf(bool condition, string! name, T? value, System.Data.ParameterDirection direction = System.Data.ParameterDirection.Input) -> TThis! +Open.Database.Extensions.ExpressiveCommandBase.AddParamIf(bool condition, string! name, T? value) -> TThis! +*REMOVED*Open.Database.Extensions.ExpressiveCommandBase.AddParamIf(bool condition, string! name, T? value, TDbType type, System.Data.ParameterDirection direction = System.Data.ParameterDirection.Input) -> TThis! +Open.Database.Extensions.ExpressiveCommandBase.AddParamIf(bool condition, string! name, T? value, TDbType type) -> TThis! +*REMOVED*Open.Database.Extensions.ExpressiveCommandBase.AddParamIf(bool condition, string! name, T? value, TDbType? type, System.Data.ParameterDirection direction = System.Data.ParameterDirection.Input) -> TThis! +Open.Database.Extensions.ExpressiveCommandBase.AddParamIf(bool condition, string! name, T? value, TDbType? type) -> TThis! +*REMOVED*Open.Database.Extensions.ExpressiveCommandBase.AddReturnParam(string! name) -> TThis! +*REMOVED*Open.Database.Extensions.ExpressiveCommandBase.AddReturnParam(string! name, TDbType type) -> TThis! +*REMOVED*Open.Database.Extensions.ExpressiveCommandBase.AddParam(string! name, object? value, TDbType type, System.Data.ParameterDirection direction = System.Data.ParameterDirection.Input) -> TThis! +Open.Database.Extensions.ExpressiveCommandBase.AddParam(string! name, object? value, TDbType type) -> TThis! +*REMOVED*Open.Database.Extensions.ExpressiveCommandBase.AddParamIf(bool condition, string! name, object? value, TDbType type, System.Data.ParameterDirection direction = System.Data.ParameterDirection.Input) -> TThis! +Open.Database.Extensions.ExpressiveCommandBase.AddParamIf(bool condition, string! name, object? value, TDbType type) -> TThis! diff --git a/Source/MSSqlClient/ExpressiveSqlCommand.cs b/Source/MSSqlClient/ExpressiveSqlCommand.cs index 3accac44..a24209b9 100644 --- a/Source/MSSqlClient/ExpressiveSqlCommand.cs +++ b/Source/MSSqlClient/ExpressiveSqlCommand.cs @@ -97,43 +97,13 @@ public ExpressiveSqlCommand( { } - // The database type of this command is SqlDbType, so without this overload a DbType argument would be taken as the value of the parameter. - // The direction has no default on purpose: this overload hides the inherited AddParam overloads wherever it applies, and a literal 0 converts to any enum, which would turn AddParam("@count", 0) into a parameter with no value. - /// - /// Adds a parameter of a with no value, for example an output parameter: AddParam("@id", DbType.Int32, ParameterDirection.Output). - /// - /// - /// A constant 0 with a direction (AddParam("@n", 0, ParameterDirection.InputOutput)) binds to this overload as a : write (object)0 or use a variable. - /// - /// The name of the parameter. - /// The database type of the parameter. - /// The direction of the parameter. An input or input-output parameter with no value is sent as a NULL of that type. - /// This instance for use in method chaining. - /// is . - /// is empty or white space, or SQL Server has no type for . - public ExpressiveSqlCommand AddParam(string name, DbType type, ParameterDirection direction) - => AddParam(name, new SqlParameter { DbType = type }.SqlDbType, direction); - - /// - /// Conditionally adds a parameter of a with no value. - /// - /// - /// The parameter is added and is . - /// The parameter is added and is empty or white space, or SQL Server has no type for . - /// The name of the parameter. - /// The database type of the parameter. - /// The direction of the parameter. An input or input-output parameter with no value is sent as a NULL of that type. - /// - public ExpressiveSqlCommand AddParamIf(bool condition, string name, DbType type, ParameterDirection direction) - => condition ? AddParam(name, type, direction) : this; - /// /// Adds the command's parameters to a new . /// /// /// A parameter that has a value is added with it, so the provider infers the type from the value. /// A parameter that has no value (an output or return-value parameter) is still added, so that it reaches the command. - /// The direction is applied, and the database type when one was given; otherwise a database null that came from an argument of a static type is sent with the of that argument, as a null carries no type of its own. + /// The database type is applied when one was given; otherwise a database null that came from an argument of a static type is sent with the of that argument, as a null carries no type of its own. /// /// The command to add the parameters to. /// is . @@ -156,7 +126,6 @@ protected override void AddParams(SqlCommand command) np = command.Parameters.AddWithValue(p.Name, p.Value); } - np.Direction = p.Direction; if (p.Type.HasValue) np.SqlDbType = p.Type.Value; else if (p.NullDbType is { } nullType) diff --git a/Source/MSSqlClient/PublicAPI.Unshipped.txt b/Source/MSSqlClient/PublicAPI.Unshipped.txt index 7dc5c581..2d00ef13 100644 --- a/Source/MSSqlClient/PublicAPI.Unshipped.txt +++ b/Source/MSSqlClient/PublicAPI.Unshipped.txt @@ -1 +1,3 @@ #nullable enable +*REMOVED*Open.Database.Extensions.ExpressiveSqlCommand.AddParam(string! name, System.Data.DbType type, System.Data.ParameterDirection direction) -> Open.Database.Extensions.ExpressiveSqlCommand! +*REMOVED*Open.Database.Extensions.ExpressiveSqlCommand.AddParamIf(bool condition, string! name, System.Data.DbType type, System.Data.ParameterDirection direction) -> Open.Database.Extensions.ExpressiveSqlCommand! diff --git a/Source/SqlClient/ExpressiveSqlCommand.cs b/Source/SqlClient/ExpressiveSqlCommand.cs index 77954550..bbec2cc3 100644 --- a/Source/SqlClient/ExpressiveSqlCommand.cs +++ b/Source/SqlClient/ExpressiveSqlCommand.cs @@ -110,35 +110,6 @@ public ExpressiveSqlCommand( { } - // The database type of this command is SqlDbType, so without this overload a DbType argument would be taken as the value of the parameter. - // The direction has no default on purpose: this overload hides the inherited AddParam overloads wherever it applies, and a literal 0 converts to any enum, which would turn AddParam("@count", 0) into a parameter with no value. - /// - /// Adds a parameter of a with no value, for example an output parameter: AddParam("@id", DbType.Int32, ParameterDirection.Output). - /// - /// - /// A constant 0 with a direction (AddParam("@n", 0, ParameterDirection.InputOutput)) binds to this overload as a : write (object)0 or use a variable. - /// - /// The name of the parameter. - /// The database type of the parameter. - /// The direction of the parameter. An input or input-output parameter with no value is sent as a NULL of that type. - /// This instance for use in method chaining. - /// is null. - /// is blank, or SQL Server has no type for . - public ExpressiveSqlCommand AddParam(string name, DbType type, ParameterDirection direction) - => AddParam(name, new SqlParameter { DbType = type }.SqlDbType, direction); - - /// - /// Conditionally adds a parameter of a with no value. See . - /// - /// The condition to add the param by. Only adds if true. - /// The name of the parameter. - /// The database type of the parameter. - /// The direction of the parameter. - /// This instance for use in method chaining. - /// The parameter is added and is blank, or SQL Server has no type for . - public ExpressiveSqlCommand AddParamIf(bool condition, string name, DbType type, ParameterDirection direction) - => condition ? AddParam(name, type, direction) : this; - /// /// Handles adding the list of parameters to a new command. /// @@ -161,7 +132,6 @@ protected override void AddParams(SqlCommand command) np = command.Parameters.AddWithValue(p.Name, p.Value); } - np.Direction = p.Direction; if (p.Type.HasValue) np.SqlDbType = p.Type.Value; else if (p.NullDbType is { } nullType) diff --git a/Tests/Open.Database.Extensions.Core.Tests/CancelOnEarlyStopTests.cs b/Tests/Open.Database.Extensions.Core.Tests/CancelOnEarlyStopTests.cs index c5f4d921..c7a2e1c7 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/CancelOnEarlyStopTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/CancelOnEarlyStopTests.cs @@ -158,13 +158,10 @@ public static TheoryData Blocked foreach (string path in new[] { "Expressive", "DbQuery", "Command" }) data.Add(path, "Transaction"); - // A DbQuery has no way to declare a parameter that is not an input. - foreach (string path in new[] { "Expressive", "Command" }) - { - data.Add(path, nameof(ParameterDirection.Output)); - data.Add(path, nameof(ParameterDirection.InputOutput)); - data.Add(path, nameof(ParameterDirection.ReturnValue)); - } + // Only a raw command can declare a parameter that is not an input. + data.Add("Command", nameof(ParameterDirection.Output)); + data.Add("Command", nameof(ParameterDirection.InputOutput)); + data.Add("Command", nameof(ParameterDirection.ReturnValue)); foreach (string path in new[] { "Expressive", "DbQuery", "Command" }) data.Add(path, "Ambient"); @@ -219,7 +216,6 @@ public static async Task EachGuard_ThrowsBeforeTheCommandRuns_AndLeavesTheConnec else { var command = transaction is null ? connection.Command("select") : ((TrackedTransaction)transaction).Command("select"); - if (direction is { } dir) command = command.AddParam("o", null, dir); query = command.Map(); } @@ -336,10 +332,18 @@ public static async Task WithoutTheOptIn_NothingIsRefused() await using var transaction = (TrackedTransaction)tally.NewOpenConnection().BeginTransaction(); Assert.Equal(1, (await transaction.Command("select") - .AddParam("o", null, ParameterDirection.Output) .Map() .FirstAsync(Ct)).Id); + await using DbCommand raw = transaction.Connection!.CreateCommand(); + raw.CommandText = "select"; + raw.Transaction = transaction; + DbParameter output = raw.CreateParameter(); + output.ParameterName = "o"; + output.Direction = ParameterDirection.Output; + raw.Parameters.Add(output); + Assert.Equal(1, (await raw.Map().FirstAsync(Ct)).Id); + FakeExecuteReader source = new(["id", "name"], [1, "a"]); Assert.Equal(1, (await source.Map().FirstAsync(Ct)).Id); } diff --git a/Tests/Open.Database.Extensions.Core.Tests/ClassicParamPathsAllocationTests.cs b/Tests/Open.Database.Extensions.Core.Tests/ClassicParamPathsAllocationTests.cs index f12d072a..d32952c2 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/ClassicParamPathsAllocationTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/ClassicParamPathsAllocationTests.cs @@ -201,55 +201,6 @@ public static void AWrittenName_TheTextDoesNotDeclare_IsSentAsWritten() Assert.Equal(["@a", "other"], sent); } - [Fact] - public static void AnOutputParameter_IsSentUnderTheNameItWasAddedWith() - { - // SQLite takes input parameters only; the tracking provider takes any direction. - var tally = new DbTally(); - TrackedConnection c = tally.NewOpenConnection(); - - ExpressiveDbCommand command = c.Command("select @Id, @Name") - .AddParam("id", null, ParameterDirection.Output) - .AddParam("name", "x"); - - string[] sent = command.Execute(static cmd => cmd.Parameters.Cast().Select(static p => p.ParameterName).ToArray()); - - Assert.Equal(["id", "@Name"], sent); - } - - [Fact] - public static void AnOutputParameter_NextToADerivedOne_IsSentUnderTheNameItWasAddedWith() - { - var tally = new DbTally(); - TrackedConnection c = tally.NewOpenConnection(); - const int id = 1; - - ExpressiveDbCommand command = c.Command("select @Id, @Name") - .AddParam(id) - .AddParam("name", null, ParameterDirection.Output); - - string[] sent = command.Execute(static cmd => cmd.Parameters.Cast().Select(static p => p.ParameterName).ToArray()); - - Assert.Equal(["@Id", "name"], sent); - } - - [Theory] - [InlineData(ParameterDirection.Input, ParameterDirection.Output)] - [InlineData(ParameterDirection.Output, ParameterDirection.Input)] - public static void TwoSpellingsOfOneName_OfAnyDirection_AreSentAsWritten(ParameterDirection first, ParameterDirection second) - { - var tally = new DbTally(); - TrackedConnection c = tally.NewOpenConnection(); - - ExpressiveDbCommand command = c.Command("select @Id") - .AddParam("id", null, first) - .AddParam("@Id", null, second); - - string[] sent = command.Execute(static cmd => cmd.Parameters.Cast().Select(static p => p.ParameterName).ToArray()); - - Assert.Equal(["id", "@Id"], sent); - } - [Fact] public static void TwoWrittenSpellingsOfOneName_AreSentAsWritten() { diff --git a/Tests/Open.Database.Extensions.Core.Tests/DerivedParameterNameTests.cs b/Tests/Open.Database.Extensions.Core.Tests/DerivedParameterNameTests.cs index d9161f9d..701eacb6 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/DerivedParameterNameTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/DerivedParameterNameTests.cs @@ -694,14 +694,14 @@ public static void ExplicitNames_StillBindToTheNamedOverloads_NeverToTheDeriving .AddParam("b", 0) .AddParam("c", 5L) .AddParam("d", (object?)null) - .AddParam("e", ParameterDirection.Output) + .AddParam("e", 'x') .AddParamIf(true, "f", "text") .AddParamIf(true, "g", 0) .AddParam("h", 3, null) .ExecuteNonQuery(); Assert.Equal(["a", "b", "c", "d", "e", "f", "g", "h"], SentNames(probe)); - Assert.Equal(["text", 0, 5L, DBNull.Value, null, "text", 0, 3], probe.Parameters.Select(p => p.Value is DBNull ? DBNull.Value : p.Value)); + Assert.Equal(["text", 0, 5L, DBNull.Value, 'x', "text", 0, 3], probe.Parameters.Select(p => p.Value is DBNull ? DBNull.Value : p.Value)); Assert.Equal(0, proc.Lookups); // nothing was derived, so the provider was never asked } diff --git a/Tests/Open.Database.Extensions.Core.Tests/ExpressiveCommandParamTests.cs b/Tests/Open.Database.Extensions.Core.Tests/ExpressiveCommandParamTests.cs index 3c74ba42..e1a64a07 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/ExpressiveCommandParamTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/ExpressiveCommandParamTests.cs @@ -63,15 +63,6 @@ public static void AddParam_NullInputValue_BecomesDBNull() Assert.Equal(DBNull.Value, cmd.Params[0].Value); } - [Fact] - public static void AddReturnParam_SetsReturnDirection() - { - ExpressiveCommand cmd = NewCommand().AddReturnParam("ret"); - - Assert.Single(cmd.Params); - Assert.Equal(ParameterDirection.ReturnValue, cmd.Params[0].Direction); - } - [Fact] public static void AddParamIf_OnlyAddsWhenConditionTrue() { diff --git a/Tests/Open.Database.Extensions.Core.Tests/ParameterBindingMatrixTests.cs b/Tests/Open.Database.Extensions.Core.Tests/ParameterBindingMatrixTests.cs index 46adf06b..9087821c 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/ParameterBindingMatrixTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/ParameterBindingMatrixTests.cs @@ -128,27 +128,27 @@ static void Expect(LanguageVersion version, string expected, string statement, b [MemberData(nameof(Versions))] public static void AnIntOrLongValue_BindsToTheIntAndLongForms_AtEveryLanguageVersion(LanguageVersion version) { - Expect(version, "AddParam(string, int, DbType?, ParameterDirection)", "c.AddParam(\"x\", i);"); - Expect(version, "AddParam(string, int, DbType?, ParameterDirection)", "c.AddParam(\"x\", i, null);"); - Expect(version, "AddParam(string, int, DbType?, ParameterDirection)", "c.AddParam(\"x\", i, t);"); - Expect(version, "AddParam(string, int, DbType?, ParameterDirection)", "c.AddParam(\"x\", 0);"); - Expect(version, "AddParam(string, long, DbType?, ParameterDirection)", "c.AddParam(\"x\", 0L);"); - Expect(version, "AddParam(string, long, DbType?, ParameterDirection)", "c.AddParam(\"x\", l);"); - Expect(version, "AddParam(string, int, DbType, ParameterDirection)", "c.AddParam(\"x\", i, DbType.Int32);"); - Expect(version, "AddParamIf(bool, string, int, DbType?, ParameterDirection)", "c.AddParamIf(true, \"x\", i, null);"); - Expect(version, "AddParamIf(bool, string, int, DbType?, ParameterDirection)", "c.AddParamIf(true, \"x\", 0);"); - Expect(version, "AddParamIf(bool, string, long, DbType?, ParameterDirection)", "c.AddParamIf(true, \"x\", 0L);"); + Expect(version, "AddParam(string, int, DbType?)", "c.AddParam(\"x\", i);"); + Expect(version, "AddParam(string, int, DbType?)", "c.AddParam(\"x\", i, null);"); + Expect(version, "AddParam(string, int, DbType?)", "c.AddParam(\"x\", i, t);"); + Expect(version, "AddParam(string, int, DbType?)", "c.AddParam(\"x\", 0);"); + Expect(version, "AddParam(string, long, DbType?)", "c.AddParam(\"x\", 0L);"); + Expect(version, "AddParam(string, long, DbType?)", "c.AddParam(\"x\", l);"); + Expect(version, "AddParam(string, int, DbType)", "c.AddParam(\"x\", i, DbType.Int32);"); + Expect(version, "AddParamIf(bool, string, int, DbType?)", "c.AddParamIf(true, \"x\", i, null);"); + Expect(version, "AddParamIf(bool, string, int, DbType?)", "c.AddParamIf(true, \"x\", 0);"); + Expect(version, "AddParamIf(bool, string, long, DbType?)", "c.AddParamIf(true, \"x\", 0L);"); } [Theory] [MemberData(nameof(Versions))] public static void AnIntOrLongValue_OnTheSqlServerCommand_BindsToTheIntAndLongForms(LanguageVersion version) { - Expect(version, "AddParam(string, int, SqlDbType?, ParameterDirection)", "q.AddParam(\"x\", i);", sql: true); - Expect(version, "AddParam(string, int, SqlDbType?, ParameterDirection)", "q.AddParam(\"x\", i, null);", sql: true); - Expect(version, "AddParam(string, int, SqlDbType?, ParameterDirection)", "q.AddParam(\"x\", i, st);", sql: true); - Expect(version, "AddParam(string, int, SqlDbType?, ParameterDirection)", "q.AddParam(\"x\", 0);", sql: true); - Expect(version, "AddParam(string, long, SqlDbType?, ParameterDirection)", "q.AddParam(\"x\", 0L);", sql: true); + Expect(version, "AddParam(string, int, SqlDbType?)", "q.AddParam(\"x\", i);", sql: true); + Expect(version, "AddParam(string, int, SqlDbType?)", "q.AddParam(\"x\", i, null);", sql: true); + Expect(version, "AddParam(string, int, SqlDbType?)", "q.AddParam(\"x\", i, st);", sql: true); + Expect(version, "AddParam(string, int, SqlDbType?)", "q.AddParam(\"x\", 0);", sql: true); + Expect(version, "AddParam(string, long, SqlDbType?)", "q.AddParam(\"x\", 0L);", sql: true); } // ---- a user enum is a value ---- @@ -159,8 +159,8 @@ public static void AUserEnum_BindsToAValueForm(LanguageVersion version) { string[] valueForms = [ - "AddParam(string, Mode?, DbType?, ParameterDirection)", - "AddParam(string, object, ParameterDirection)", + "AddParam(string, Mode?, DbType?)", + "AddParam(string, object)", ]; Assert.Contains(Bound(version, "c.AddParam(\"x\", Mode.A);"), valueForms); } @@ -175,7 +175,7 @@ public static void ATypedNullByteArray_CompilesWithNoWarning_AndBindsToTheObject var (compilation, _) = Compile(version, statement); var problems = compilation.GetDiagnostics(TestContext.Current.CancellationToken).Where(static d => d.Severity >= DiagnosticSeverity.Warning).Select(static d => d.ToString()).ToArray(); Assert.True(problems.Length == 0, $"{version}: {string.Join(" | ", problems)}"); - Expect(version, "AddParam(string, object, DbType, ParameterDirection)", statement); + Expect(version, "AddParam(string, object, DbType)", statement); } [Fact] diff --git a/Tests/Open.Database.Extensions.Core.Tests/ParameterDirectionTests.cs b/Tests/Open.Database.Extensions.Core.Tests/ParameterDirectionTests.cs deleted file mode 100644 index 43198991..00000000 --- a/Tests/Open.Database.Extensions.Core.Tests/ParameterDirectionTests.cs +++ /dev/null @@ -1,113 +0,0 @@ -namespace Open.Database.Extensions.Tests; - -#nullable enable - -// The direction of a parameter reaches the provider's command on every command type. The SQL Server command always did; the generic commands (ExpressiveCommand over an IDbConnection, -// ExpressiveDbCommand over a DbConnection) sent every parameter as an input, so a stored procedure with an output parameter failed with "expects parameter '@o', which was not supplied". -// ExpressiveCommand is read through the connection probe (a substitute remembers what is set on it), ExpressiveDbCommand through a command that records real DbParameter objects. -[ExcludeFromCodeCoverage] -public static class ParameterDirectionTests -{ - public static TheoryData Directions - => [ - ParameterDirection.Input, - ParameterDirection.Output, - ParameterDirection.InputOutput, - ParameterDirection.ReturnValue, - ]; - - static ExpressiveDbCommand DbCommand(DerivedParameterNameTests.RecordingDbCommand recorder) - => new(new DerivedParameterNameTests.OpenDbConnection(recorder), CommandType.StoredProcedure, "dbo.p"); - - // ---- every direction reaches the provider's parameter ---- - - [Theory] - [MemberData(nameof(Directions))] - public static async Task ExpressiveDbCommand_SendsTheDirectionOfTheParameter_Async(ParameterDirection direction) - { - var recorder = new DerivedParameterNameTests.RecordingDbCommand(); - - await DbCommand(recorder) - .AddParam("@p", 5, DbType.Int32, direction) - .ExecuteNonQueryAsync( - cancellationToken: TestContext.Current.CancellationToken); - - Assert.Equal(direction, Assert.Single(recorder.Sent).Direction); - } - - // ---- the usual procedure call: inputs, an output, an input-output and a return value, together ---- - - [Fact] - public static void AProcedureCallWithEveryKindOfParameter_SendsEachOneWithItsDirection() - { - var probe = new ConnectionProbe(ConnectionState.Open); - var recorder = new DerivedParameterNameTests.RecordingDbCommand(); - - new ExpressiveCommand(probe.Connection, CommandType.StoredProcedure, "dbo.p") - .AddParam("@i", 1) - .AddParam("@o", DbType.Int32, ParameterDirection.Output) - .AddParam("@io", 3, DbType.Int32, ParameterDirection.InputOutput) - .AddReturnParam("@r", DbType.Int32) - .ExecuteNonQuery(); - - DbCommand(recorder) - .AddParam("@i", 1) - .AddParam("@o", DbType.Int32, ParameterDirection.Output) - .AddParam("@io", 3, DbType.Int32, ParameterDirection.InputOutput) - .AddReturnParam("@r", DbType.Int32) - .ExecuteNonQuery(); - - ParameterDirection[] expected = [ParameterDirection.Input, ParameterDirection.Output, ParameterDirection.InputOutput, ParameterDirection.ReturnValue]; - Assert.Equal(["@i", "@o", "@io", "@r"], probe.Parameters.Select(p => p.ParameterName)); - Assert.Equal(expected, probe.Parameters.Select(p => p.Direction)); - Assert.Equal(["@i", "@o", "@io", "@r"], recorder.Sent.Select(p => p.ParameterName)); - Assert.Equal(expected, recorder.Sent.Select(p => p.Direction)); - } - - // ---- a NULL-valued output parameter still reaches the command ---- - - [Fact] - public static void ANullValuedOutputParameter_ReachesTheCommand_WithItsDirection() - { - var probe = new ConnectionProbe(ConnectionState.Open); - var recorder = new DerivedParameterNameTests.RecordingDbCommand(); - - new ExpressiveCommand(probe.Connection, CommandType.StoredProcedure, "dbo.p") - .AddParam("@o", ParameterDirection.Output) - .AddParam("@io", null, ParameterDirection.InputOutput) - .AddReturnParam("@r") - .ExecuteNonQuery(); - - DbCommand(recorder) - .AddParam("@o", ParameterDirection.Output) - .AddParam("@io", null, ParameterDirection.InputOutput) - .AddReturnParam("@r") - .ExecuteNonQuery(); - - Assert.Equal(["@o", "@io", "@r"], probe.Parameters.Select(p => p.ParameterName)); - Assert.Equal([ParameterDirection.Output, ParameterDirection.InputOutput, ParameterDirection.ReturnValue], probe.Parameters.Select(p => p.Direction)); - Assert.Null(probe.Parameters[0].Value); // an output parameter is sent as given; an input-output one with no value is a database null - Assert.Equal(DBNull.Value, probe.Parameters[1].Value); - - Assert.Equal(["@o", "@io", "@r"], recorder.Sent.Select(p => p.ParameterName)); - Assert.Equal([ParameterDirection.Output, ParameterDirection.InputOutput, ParameterDirection.ReturnValue], recorder.Sent.Select(p => p.Direction)); - Assert.Null(recorder.Sent[0].Value); - Assert.Equal(DBNull.Value, recorder.Sent[1].Value); - } - - // A name that is derived from the argument is still an input, and stays one once its real name is known. - [Fact] - public static void AnArgumentNamedByItsExpression_IsSentAsAnInput() - { - var probe = new ConnectionProbe(ConnectionState.Open); - const int orderId = 5; - - new ExpressiveCommand(probe.Connection, CommandType.StoredProcedure, "dbo.p") - .AddParam(orderId) - .AddParams(new { Name = "ann" }) - .ExecuteNonQuery(); - - Assert.Equal(["orderId", "Name"], probe.Parameters.Select(p => p.ParameterName)); - Assert.All(probe.Parameters, p => Assert.Equal(ParameterDirection.Input, p.Direction)); - } -} diff --git a/Tests/Open.Database.Extensions.Core.Tests/ParameterNameExplicitTests.cs b/Tests/Open.Database.Extensions.Core.Tests/ParameterNameExplicitTests.cs index b7717ff4..93094996 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/ParameterNameExplicitTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/ParameterNameExplicitTests.cs @@ -35,7 +35,6 @@ public static class ParameterNameExplicitTests (c, name) => c.AddParam(name, "text"), (c, name) => c.AddParam(name, (object?)null), (c, name) => c.AddParam(name, (object)5, DbType.Int32), - (c, name) => c.AddParam(name, ParameterDirection.Output), (c, name) => c.AddParam(name, 3, null), (c, name) => c.AddParamIf(true, name, 5), (c, name) => c.AddParamIf(true, name, "text"), diff --git a/Tests/Open.Database.Extensions.Core.Tests/ParameterTypeOverloadTests.cs b/Tests/Open.Database.Extensions.Core.Tests/ParameterTypeOverloadTests.cs index b84d69ae..efc40024 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/ParameterTypeOverloadTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/ParameterTypeOverloadTests.cs @@ -45,8 +45,6 @@ public static void AddParam_StringAndType() Assert.Equal("x=DBNull NVarChar Input", Sent(New().AddParam("x", n, SqlDbType.NVarChar))); Assert.Equal("x=a NVarChar Input", Sent(New().AddParam("x", "a", SqlDbType.NVarChar))); Assert.Equal("x=DBNull NVarChar Input", Sent(New().AddParam("x", null, SqlDbType.NVarChar))); - Assert.Equal("x=a NVarChar Output", Sent(New().AddParam("x", s, SqlDbType.NVarChar, ParameterDirection.Output))); - Assert.Equal("x=a NVarChar InputOutput", Sent(New().AddParam(name: "x", value: s, type: SqlDbType.NVarChar, direction: ParameterDirection.InputOutput))); } [Fact] @@ -64,7 +62,6 @@ public static void AddParam_IntegersAndType() Assert.Equal("x=5 Int Input", Sent(New().AddParam("x", 5, SqlDbType.Int))); Assert.Equal("x=0 Int Input", Sent(New().AddParam("x", 0, SqlDbType.Int))); Assert.Equal("x=6 BigInt Input", Sent(New().AddParam("x", 6L, SqlDbType.BigInt))); - Assert.Equal("x=5 Int Output", Sent(New().AddParam("x", i, SqlDbType.Int, ParameterDirection.Output))); Assert.Equal("x=5 Int Input", Sent(New().AddParam(name: "x", value: i, type: SqlDbType.Int))); Assert.Equal("x=5 Int Input", Sent(New().AddParam("x", 5, SqlDbType.Int))); } @@ -91,7 +88,6 @@ public static void AddParam_CharAndType_SendsTheCharacter() Assert.Equal("x=c NChar Input", Sent(New().AddParam("x", c, SqlDbType.NChar))); Assert.Equal("x=c NChar Input", Sent(New().AddParam("x", 'c', SqlDbType.NChar))); - Assert.Equal("x=c NChar Output", Sent(New().AddParam("x", c, SqlDbType.NChar, ParameterDirection.Output))); Assert.Equal("x=c NChar Input", Sent(New().AddParamIf(true, "x", c, SqlDbType.NChar))); Assert.IsType(New().AddParam("x", c, SqlDbType.NChar).Params[0].Value); } @@ -165,7 +161,6 @@ public static void AddParam_NullableValueAndType() Assert.Equal("x=11111111-2222-3333-4444-555555555555 UniqueIdentifier Input", Sent(New().AddParam("x", g, SqlDbType.UniqueIdentifier))); Assert.Equal("x=True Bit Input", Sent(New().AddParam("x", b, SqlDbType.Bit))); Assert.Equal("x=2.5 Float Input", Sent(New().AddParam("x", db, SqlDbType.Float))); - Assert.Equal("x=9 Int Output", Sent(New().AddParam("x", ni, SqlDbType.Int, ParameterDirection.Output))); } // ---- a value and a database type: the forms that already compiled keep their meaning ---- @@ -205,8 +200,6 @@ public static void AddParam_OptionalTypeForms_AreUnchanged() Assert.Equal("x=5 Int Input", Sent(New().AddParam("x", i, type))); Assert.Equal("x=a Int Input", Sent(New().AddParam("x", s, type))); Assert.Equal("x=9 Int Input", Sent(New().AddParam("x", ni, type))); - Assert.Equal("x=DBNull Int Input", Sent(New().AddParam("x", SqlDbType.Int))); - Assert.Equal("x=5 - Output", Sent(New().AddParam("x", i, ParameterDirection.Output))); } // ---- the conditional forms, with the condition true and false ---- @@ -241,7 +234,6 @@ public static void AddParamIf_ValueAndType_AddsOnlyWhenTrue(bool condition) Assert.Equal(Only(condition, "x=2.5 Decimal Input"), Sent(New().AddParamIf(condition, "x", dn, SqlDbType.Decimal))); Assert.Equal(Only(condition, "x=01/02/2020 03:04:05 DateTime2 Input"), Sent(New().AddParamIf(condition, "x", Stamp, SqlDbType.DateTime2))); Assert.Equal(Only(condition, "x=c NChar Input"), Sent(New().AddParamIf(condition, "x", c, SqlDbType.NChar))); - Assert.Equal(Only(condition, "x=5 Int Output"), Sent(New().AddParamIf(condition, "x", i, SqlDbType.Int, ParameterDirection.Output))); Assert.Equal(Only(condition, "x=3 Int Input"), Sent(New().AddParamIf(condition, "x", 3, SqlDbType.Int))); } diff --git a/Tests/Open.Database.Extensions.Core.Tests/SqlServerPackageTests.cs b/Tests/Open.Database.Extensions.Core.Tests/SqlServerPackageTests.cs index 63a77382..835049af 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/SqlServerPackageTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/SqlServerPackageTests.cs @@ -65,28 +65,6 @@ public static void AddParams_AValue_IsAnInputParameterTheProviderTypes() Assert.Equal(SqlDbType.Int, p.SqlDbType); } - [Fact] - public static void AddParams_NoValue_StillReachesTheCommandWithItsTypeAndDirection() - { - SqlParameter[] sent = Sent(c => c - .AddParam("@o", SqlDbType.Int, ParameterDirection.Output) - .AddParam("@r", SqlDbType.BigInt, ParameterDirection.ReturnValue)); - - Assert.Equal(["@o", "@r"], sent.Select(p => p.ParameterName)); - Assert.All(sent, p => Assert.Null(p.Value)); - Assert.Equal([SqlDbType.Int, SqlDbType.BigInt], sent.Select(p => p.SqlDbType)); - Assert.Equal([ParameterDirection.Output, ParameterDirection.ReturnValue], sent.Select(p => p.Direction)); - } - - [Fact] - public static void AddParams_InputOutput_KeepsItsValueAndDirection() - { - SqlParameter p = Assert.Single(Sent(c => c.AddParam("@io", 7, ParameterDirection.InputOutput))); - - Assert.Equal(7, p.Value); - Assert.Equal(ParameterDirection.InputOutput, p.Direction); - } - [Fact] public static void AddParams_ANullFromANullableArgument_IsADatabaseNullOfThatType() { @@ -129,7 +107,7 @@ public static void AddParams_KeepsTheOrderTheParametersWereAdded() .AddParam("@c", 1) .AddParam("@a", 2) .AddParam("@b", "three") - .AddParam("@o", SqlDbType.Int, ParameterDirection.Output)).Select(p => p.ParameterName)); + .AddParam("@o", 4)).Select(p => p.ParameterName)); [Fact] public static void AddParams_ANullCommand_ThrowsArgumentNull() diff --git a/Tests/Open.Database.Extensions.Core.Tests/SqlServerParameterTypeTests.cs b/Tests/Open.Database.Extensions.Core.Tests/SqlServerParameterTypeTests.cs index 89241b4b..303d571c 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/SqlServerParameterTypeTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/SqlServerParameterTypeTests.cs @@ -4,10 +4,7 @@ namespace Open.Database.Extensions.Tests; #nullable enable -// AddParam("@o", DbType.Int32, ParameterDirection.Output) on the two SQL Server commands. Their database type is SqlDbType, so a DbType used to bind to AddParam(string, object?, ParameterDirection) -// and the enum itself became the VALUE of an output parameter. The overloads below take the DbType, as the generic commands do, and build a parameter of that type with no value. -// Each case is written for both packages (System.Data.SqlClient and Microsoft.Data.SqlClient): the second is reached through an extern alias, as both define ExpressiveSqlCommand. -// A command that declares an AddParam of its own hides the inherited ones that apply to the same call, so the last tests pin the calls that must keep their meaning, a literal 0 above all. +// The SQL Server commands add no overloads of their own: a literal 0, a char, a string and a SqlDbType keep their meaning, on both packages (System.Data.SqlClient and Microsoft.Data.SqlClient, the second reached through an extern alias, as both define ExpressiveSqlCommand). [ExcludeFromCodeCoverage] public static class SqlServerParameterTypeTests { @@ -31,51 +28,7 @@ static string Sent(ExpressiveSqlCommand command) static string Sent(mssql::Open.Database.Extensions.ExpressiveSqlCommand command) => string.Join("; ", command.Params.Select(p => $"{p.Name}={Show(p.Value)} {(p.Type.HasValue ? p.Type.Value.ToString() : "-")} {p.Direction}")); - static string Only(bool condition, string expected) => condition ? expected : ""; - - // ---- a DbType and a direction: a parameter of that type with no value ---- - - [Fact] - public static void ADbTypeAndADirection_AreATypedParameterWithNoValue() - { - Assert.Equal("@o=null Int Output", Sent(Legacy().AddParam("@o", DbType.Int32, ParameterDirection.Output))); - Assert.Equal("@o=null Int Output", Sent(Microsoft().AddParam("@o", DbType.Int32, ParameterDirection.Output))); - Assert.Equal("@o=null BigInt Output", Sent(Legacy().AddParam("@o", DbType.Int64, ParameterDirection.Output))); - Assert.Equal("@o=null NVarChar Output", Sent(Microsoft().AddParam("@o", DbType.String, ParameterDirection.Output))); - Assert.Equal("@o=null VarChar Output", Sent(Legacy().AddParam("@o", DbType.AnsiString, ParameterDirection.Output))); - Assert.Equal("@o=null DateTime2 Output", Sent(Microsoft().AddParam("@o", DbType.DateTime2, ParameterDirection.Output))); - Assert.Equal("@o=null Bit Output", Sent(Legacy().AddParam("@o", DbType.Boolean, ParameterDirection.Output))); - } - - [Fact] - public static void TheOtherDirections_KeepTheirMeaning() - { - Assert.Equal("@r=null Int ReturnValue", Sent(Legacy().AddParam("@r", DbType.Int32, ParameterDirection.ReturnValue))); - Assert.Equal("@r=null Int ReturnValue", Sent(Microsoft().AddParam("@r", DbType.Int32, ParameterDirection.ReturnValue))); - - // An input or input-output parameter with no value is a typed NULL, as for a SqlDbType. - Assert.Equal("@i=DBNull Int Input", Sent(Legacy().AddParam("@i", DbType.Int32, ParameterDirection.Input))); - Assert.Equal("@io=DBNull Int InputOutput", Sent(Microsoft().AddParam("@io", DbType.Int32, ParameterDirection.InputOutput))); - } - - [Theory] - [InlineData(true)] - [InlineData(false)] - public static void AddParamIf_AddsOnlyWhenTrue(bool condition) - { - Assert.Equal(Only(condition, "@o=null Int Output"), Sent(Legacy().AddParamIf(condition, "@o", DbType.Int32, ParameterDirection.Output))); - Assert.Equal(Only(condition, "@o=null Int Output"), Sent(Microsoft().AddParamIf(condition, "@o", DbType.Int32, ParameterDirection.Output))); - } - - [Fact] - public static void ADbTypeSqlServerHasNoTypeFor_Throws_AsTheProviderDoes() - { - Assert.Throws(() => Legacy().AddParam("@o", DbType.UInt16, ParameterDirection.Output)); - Assert.Throws(() => Microsoft().AddParam("@o", DbType.UInt16, ParameterDirection.Output)); - } - - // ---- the calls that must keep their meaning: the new overload is declared on the command, so it hides the inherited overloads of any call it applies to ---- - // A literal 0 converts implicitly to any enum, so a DbType parameter with a default direction would take AddParam("@count", 0) and add a typed NULL where an int 0 was meant. + // ---- the calls that must keep their meaning ---- [Fact] [SuppressMessage("Roslynator", "RCS1118:Mark local variable as const", Justification = "The local is a variable on purpose: a literal 0 converts implicitly to any enum, a variable does not, and the test pins both.")] @@ -93,16 +46,12 @@ public static void AValueIsStillAValue_AboveAllALiteralZero() Assert.Equal("@x=0 - Input", Sent(Microsoft().AddParamIf(true, "@x", 0))); Assert.Equal("@x=c - Input", Sent(Legacy().AddParam("@x", 'c'))); Assert.Equal("@x=c - Input", Sent(Microsoft().AddParam("@x", 'c'))); - Assert.Equal("@x=5 - Output", Sent(Legacy().AddParam("@x", 5, ParameterDirection.Output))); Assert.Equal("@x=a - Input", Sent(Microsoft().AddParam("@x", "a"))); } [Fact] public static void ASqlDbTypeIsStillASqlDbType() { - Assert.Equal("@x=DBNull Int Input", Sent(Legacy().AddParam("@x", SqlDbType.Int))); - Assert.Equal("@x=null Int Output", Sent(Microsoft().AddParam("@x", SqlDbType.Int, ParameterDirection.Output))); Assert.Equal("@x=5 Int Input", Sent(Legacy().AddParam("@x", 5, SqlDbType.Int))); - Assert.Equal("@x=null Int ReturnValue", Sent(Microsoft().AddReturnParam("@x", SqlDbType.Int))); } } diff --git a/Tests/Open.Database.Extensions.Core.Tests/TypedNullParameterTests.cs b/Tests/Open.Database.Extensions.Core.Tests/TypedNullParameterTests.cs index 0f4b712c..c9a26057 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/TypedNullParameterTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/TypedNullParameterTests.cs @@ -160,48 +160,6 @@ public static void TheObjectOverload_WithANull_StaysUntyped() AssertAllNull(probe); } - [Fact] - public static void AnOutputParameter_KeepsItsNullAndStaysUntyped() - { - var probe = new ConnectionProbe(ConnectionState.Open); - - Command(probe) - .AddParam("@a", (int?)null, direction: ParameterDirection.Output) - .ExecuteNonQuery(); - - AssertUntyped(probe.Parameters[0]); - Assert.Null(probe.Parameters[0].Value); - } - - [Fact] - public static void AnInputOutputParameter_WithANull_IsTyped() - { - var probe = new ConnectionProbe(ConnectionState.Open); - - Command(probe) - .AddParam("@a", (int?)null, direction: ParameterDirection.InputOutput) - .ExecuteNonQuery(); - - Assert.Equal(DbType.Int32, probe.Parameters[0].DbType); - AssertAllNull(probe); - } - - // Known limit: a positional ParameterDirection is not a database type, so - // the call binds the object overload, which has no type to use. Name the - // direction (direction: ...) or pass a database type. - [Fact] - public static void APositionalDirection_BindsTheObjectOverload_AndStaysUntyped() - { - var probe = new ConnectionProbe(ConnectionState.Open); - - Command(probe) - .AddParam("@a", null, ParameterDirection.Input) - .ExecuteNonQuery(); - - AssertUntyped(probe.Parameters[0]); - AssertAllNull(probe); - } - [Fact] public static void AddParamIf_WithANull_IsTypedTheSameWay() { diff --git a/Tests/Open.Database.Extensions.LegacyCompiler.Tests/ParameterTypeTests.cs b/Tests/Open.Database.Extensions.LegacyCompiler.Tests/ParameterTypeTests.cs index 6c87375c..ca4f3d76 100644 --- a/Tests/Open.Database.Extensions.LegacyCompiler.Tests/ParameterTypeTests.cs +++ b/Tests/Open.Database.Extensions.LegacyCompiler.Tests/ParameterTypeTests.cs @@ -54,7 +54,6 @@ public static void AddParam_StringAndType() Assert.Equal("x=a NVarChar Input", Sent(New().AddParam("x", "a", SqlDbType.NVarChar))); Assert.Equal("x=DBNull NVarChar Input", Sent(New().AddParam("x", null, SqlDbType.NVarChar))); Assert.Equal("x=DBNull NVarChar Input", Sent(New().AddParam("x", null, SqlDbType.NVarChar))); - Assert.Equal("x=a NVarChar Output", Sent(New().AddParam("x", s, SqlDbType.NVarChar, ParameterDirection.Output))); Assert.Equal("x=a NVarChar Input", Sent(New().AddParam(name: "x", value: s, type: SqlDbType.NVarChar))); } @@ -73,7 +72,6 @@ public static void AddParam_IntegersAndType() Assert.Equal("x=5 Int Input", Sent(New().AddParam("x", 5, SqlDbType.Int))); Assert.Equal("x=0 Int Input", Sent(New().AddParam("x", 0, SqlDbType.Int))); Assert.Equal("x=6 BigInt Input", Sent(New().AddParam("x", 6L, SqlDbType.BigInt))); - Assert.Equal("x=5 Int Output", Sent(New().AddParam("x", i, SqlDbType.Int, ParameterDirection.Output))); Assert.Equal("x=5 Int Input", Sent(New().AddParam(name: "x", value: i, type: SqlDbType.Int))); Assert.Equal("x=5 Int Input", Sent(New().AddParam("x", 5, SqlDbType.Int))); } @@ -100,7 +98,6 @@ public static void AddParam_CharAndType_SendsTheCharacter() Assert.Equal("x=c NChar Input", Sent(New().AddParam("x", c, SqlDbType.NChar))); Assert.Equal("x=c NChar Input", Sent(New().AddParam("x", 'c', SqlDbType.NChar))); - Assert.Equal("x=c NChar Output", Sent(New().AddParam("x", c, SqlDbType.NChar, ParameterDirection.Output))); Assert.Equal("x=c NChar Input", Sent(New().AddParamIf(true, "x", c, SqlDbType.NChar))); } @@ -157,7 +154,6 @@ public static void AddParam_NullableValueAndType() Assert.Equal("x=11111111-2222-3333-4444-555555555555 UniqueIdentifier Input", Sent(New().AddParam("x", g, SqlDbType.UniqueIdentifier))); Assert.Equal("x=True Bit Input", Sent(New().AddParam("x", b, SqlDbType.Bit))); Assert.Equal("x=2.5 Float Input", Sent(New().AddParam("x", db, SqlDbType.Float))); - Assert.Equal("x=9 Int Output", Sent(New().AddParam("x", ni, SqlDbType.Int, ParameterDirection.Output))); } // ---- a value and a database type: the forms that already compiled keep their meaning ---- @@ -197,8 +193,6 @@ public static void AddParam_OptionalTypeForms_AreUnchanged() Assert.Equal("x=5 Int Input", Sent(New().AddParam("x", i, type))); Assert.Equal("x=a Int Input", Sent(New().AddParam("x", s, type))); Assert.Equal("x=9 Int Input", Sent(New().AddParam("x", ni, type))); - Assert.Equal("x=DBNull Int Input", Sent(New().AddParam("x", SqlDbType.Int))); - Assert.Equal("x=5 - Output", Sent(New().AddParam("x", i, ParameterDirection.Output))); } // ---- the conditional forms ---- @@ -230,7 +224,6 @@ public static void AddParamIf_ValueAndType_AddsWhenTrue() Assert.Equal("x=1.5 Decimal Input", Sent(New().AddParamIf(true, "x", d, SqlDbType.Decimal))); Assert.Equal("x=2.5 Decimal Input", Sent(New().AddParamIf(true, "x", dn, SqlDbType.Decimal))); Assert.Equal("x=01/02/2020 03:04:05 DateTime2 Input", Sent(New().AddParamIf(true, "x", dt, SqlDbType.DateTime2))); - Assert.Equal("x=5 Int Output", Sent(New().AddParamIf(true, "x", i, SqlDbType.Int, ParameterDirection.Output))); Assert.Equal("x=3 Int Input", Sent(New().AddParamIf(true, "x", 3, SqlDbType.Int))); } @@ -294,7 +287,6 @@ public static void ExpressiveCommand_ValueAndDbType() Assert.Equal("x=1.5 Decimal Input", SentDb(NewDb().AddParam("x", d, DbType.Decimal))); Assert.Equal("x=5 Int32 Input", SentDb(NewDb().AddParam("x", 5, DbType.Int32))); Assert.Equal("x=0 Int32 Input", SentDb(NewDb().AddParam("x", 0, DbType.Int32))); - Assert.Equal("x=5 Int32 Output", SentDb(NewDb().AddParam("x", i, DbType.Int32, ParameterDirection.Output))); Assert.Equal("x=5 Int32 Input", SentDb(NewDb().AddParamIf(true, "x", i, DbType.Int32))); Assert.Equal("x=a String Input", SentDb(NewDb().AddParamIf(true, "x", s, DbType.String))); Assert.Equal("x=6 Int64 Input", SentDb(NewDb().AddParamIf(true, "x", l, DbType.Int64))); diff --git a/docsite/articles/coming-from-dapper.md b/docsite/articles/coming-from-dapper.md index 4beff717..ce39c41e 100644 --- a/docsite/articles/coming-from-dapper.md +++ b/docsite/articles/coming-from-dapper.md @@ -263,7 +263,7 @@ Dapper has features this library does not offer: - **Type handlers and custom type maps.** `SqlMapper.AddTypeHandler` and `SqlMapper.SetTypeMap`. - **Dynamic results.** `Query(sql)` without a type returns dynamic rows. - **Batch execution.** `Execute(sql, IEnumerable)` runs one command once for every item. The extensions have no equivalent: loop over the items and run the command for each, inside one `ExecuteTransactionAsync` (see [A transaction](#a-transaction)). -- **Parameter bags and output parameters.** An anonymous object, `new { id = 1 }`, becomes `AddParams(new { id = 1 })` (see [Name a parameter from its argument](expressive-commands.md#name-a-parameter-from-its-argument)). `DynamicParameters` has no equivalent: add each value with `AddParam`. Output parameters can be sent, but their values cannot be read back, so a procedure that returns values through them needs Dapper or plain ADO.NET. The return value is readable: `ExecuteReturnAsync()` (see [Return values and output parameters](expressive-commands.md#return-values-and-output-parameters)). +- **Parameter bags and output parameters.** An anonymous object, `new { id = 1 }`, becomes `AddParams(new { id = 1 })` (see [Name a parameter from its argument](expressive-commands.md#name-a-parameter-from-its-argument)). `DynamicParameters` has no equivalent: add each value with `AddParam`. Output parameters are not part of the chain: to set a direction, use `ExecuteAsync(command => ...)` with the raw `AddParameter` and `AddReturnParameter` extensions on the command. The return value is readable: `ExecuteReturnAsync()` (see [Return values and output parameters](expressive-commands.md#return-values-and-output-parameters)). With the extensions, use `Map(selector)` or `ExecuteReader(reader => ...)` for those jobs. For dynamic rows, `AsObjectArrays()` gives each row as an `object?[]` (`AsDictionaryRows()` as a dictionary): see [Rows without a model](mapping.md#rows-without-a-model). diff --git a/docsite/articles/expressive-commands.md b/docsite/articles/expressive-commands.md index 753999bf..60da0f84 100644 --- a/docsite/articles/expressive-commands.md +++ b/docsite/articles/expressive-commands.md @@ -163,7 +163,7 @@ A derived name stays as written when no real names were read: a text command, an ### Name a parameter yourself -`AddParam(name, value)` adds an input parameter under the name you give. Overloads accept a database type and a `ParameterDirection`. `AddParamIf(condition, value)` (or `AddParamIf(condition, name, value)`) adds the parameter only when the condition is true, which keeps the SQL text constant. A false condition adds nothing and does not look at the argument, so a name that could not be derived is an error only when the condition holds: +`AddParam(name, value)` adds an input parameter under the name you give. Overloads accept a database type. `AddParamIf(condition, value)` (or `AddParamIf(condition, name, value)`) adds the parameter only when the condition is true, which keeps the SQL text constant. A false condition adds nothing and does not look at the argument, so a name that could not be derived is an error only when the condition holds: [!code-csharp[](../samples/ExpressiveCommands.cs#param_if)] @@ -175,11 +175,11 @@ To get the id an insert generated, select it in the same command and read it wit ### Return values and output parameters -`ExecuteReturnAsync()` runs the command and returns the value of its return-value parameter, which it adds itself (you do not call `AddReturnParam` for it). As with `ExecuteScalarAsync()`, the value is converted to `T` the way `Map()` converts a column: a NULL is `null` for a nullable `T` and throws `ValueMappingException` for a non-nullable value type. A token that is already cancelled fails the call with `OperationCanceledException` before anything runs. A SQL Server stored procedure returns an `int`, its `RETURN` code: +`ExecuteReturnAsync()` runs the command and returns the value of its return-value parameter, which it adds itself. As with `ExecuteScalarAsync()`, the value is converted to `T` the way `Map()` converts a column: a NULL is `null` for a nullable `T` and throws `ValueMappingException` for a non-nullable value type. A token that is already cancelled fails the call with `OperationCanceledException` before anything runs. A SQL Server stored procedure returns an `int`, its `RETURN` code: [!code-csharp[](../samples/SqlServer.cs#sql_server_return)] -Output values cannot be read back. You can send an output parameter (`AddParam(name, ParameterDirection.Output)`, with a type and size on SQL Server) but not read what the procedure put in it. A procedure that hands its results back through output parameters needs plain ADO.NET; a result set and the return value are readable. +Output values cannot be read back, and a direction cannot be set on the chain: `AddParam` adds inputs only. To set a direction, use `ExecuteAsync(command => ...)` with the raw `AddParameter`, `AddParameterType` and `AddReturnParameter` extensions on the command. A result set and the return value are readable on the chain. ## Terminals diff --git a/docsite/articles/release-notes.md b/docsite/articles/release-notes.md index cbd7f19e..974aa5bc 100644 --- a/docsite/articles/release-notes.md +++ b/docsite/articles/release-notes.md @@ -9,6 +9,7 @@ Version 11 is `11.0.0-rc.16`. For moving a 10.x codebase, read [Coming from earl - **Generated row readers for `DbQuery` too.** A plain `Map()` on a `DbQuery`, a `DbQuery` or a query bound with `Using` now gets its row reader written at build time, as on a command or a reader; before, it used the runtime map. The runtime map's conversions are therefore no longer applied there: see [Generated readers](mapping.md#generated-readers) for the differences and the switch. - **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`; `AddParam(name, type)`, `AddParam(name, direction)`, `AddParamIf` with only a type or direction, and `AddReturnParam` are gone. 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. ### Changes since rc.15 diff --git a/docsite/articles/whats-new-11.md b/docsite/articles/whats-new-11.md index 70762c54..4de33afa 100644 --- a/docsite/articles/whats-new-11.md +++ b/docsite/articles/whats-new-11.md @@ -125,11 +125,11 @@ See [Expressive commands](expressive-commands.md). ## Parameters -- **`AddParam(parameterName)` with a string variable** added a parameter with that name and no value in 10.x. In 11 it adds a parameter named `parameterName` whose value is the string. A literal, `AddParam("name")`, throws `ArgumentException`. For a parameter with no value pass its direction, `AddParam("name", ParameterDirection.Output)`. +- **`AddParam(parameterName)` with a string variable** added a parameter with that name and no value in 10.x. In 11 it adds a parameter named `parameterName` whose value is the string. A literal, `AddParam("name")`, throws `ArgumentException`. - **Names from arguments.** `.AddParam(author)` takes the name from the variable and matches it to the stored procedure's real name. `AddParam("name", value)` always wins. - **A typed NULL** such as `AddParam("@id", (long?)null)` is sent with the database type of its overload. - **After a run, `Params` holds what you added,** under the names as added. Read the provider command's `Parameters` in `Execute(command => ...)` to see what was sent. -- **The `direction = Input` default** of `AddParam(string, ParameterDirection)` and `AddParamIf` is gone: pass the direction. +- **No direction on the chain.** `AddParam`, `AddParamIf` and `AddReturnParam` no longer take a `ParameterDirection`, so a parameter added on the chain is an input; the overloads that took only a direction or only a type, and `AddReturnParam`, are gone. To set a direction, use `ExecuteAsync(command => ...)` with the raw `AddParameter`, `AddParameterType` and `AddReturnParameter` extensions. See [Parameters](expressive-commands.md#name-a-parameter-from-its-argument). From 267014dd087d06a56a3479fe828a8963f6ca96aa Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Tue, 1 Dec 2026 18:23:56 -0800 Subject: [PATCH 02/20] Make the public Param input-only. Param loses its direction constructor parameter and its Direction property, and a null value is always stored as a database null. The readers of the direction in the command classes are simplified to treat every parameter as an input, and the SQL Server commands no longer have a branch for a parameter with no value. Co-Authored-By: Claude Sonnet 5.5 --- Source/Core/ExpressiveCommandBase.Param.cs | 35 +-- Source/Core/PublicAPI.Unshipped.txt | 3 + Source/MSSqlClient/ExpressiveSqlCommand.cs | 15 +- Source/SqlClient/ExpressiveSqlCommand.cs | 12 +- .../ParameterBindingMatrixTests.cs | 1 - .../ParameterTypeOverloadTests.cs | 148 ++++++------ .../SqlServerParameterTypeTests.cs | 30 +-- .../ParameterTypeTests.cs | 212 +++++++++--------- docsite/articles/release-notes.md | 2 +- docsite/articles/whats-new-11.md | 2 +- 10 files changed, 214 insertions(+), 246 deletions(-) diff --git a/Source/Core/ExpressiveCommandBase.Param.cs b/Source/Core/ExpressiveCommandBase.Param.cs index dec5433e..7a38205f 100644 --- a/Source/Core/ExpressiveCommandBase.Param.cs +++ b/Source/Core/ExpressiveCommandBase.Param.cs @@ -12,7 +12,7 @@ public abstract partial class ExpressiveCommandBase /// - /// For and parameters, a value is stored as so the parameter is sent as a database null. For output and return-value parameters the value is stored as given. + /// A parameter is an input: a value is stored as so the parameter is sent as a database null. /// public readonly record struct Param @@ -21,16 +21,14 @@ public readonly record struct Param /// Initializes a new instance of the struct. /// /// The name of the parameter. Cannot be , empty, or white space. - /// The value of the parameter. A input value is converted to . + /// The value of the parameter. A value is converted to . /// The optional database type of the parameter. When , the provider infers it from the value. - /// The direction of the parameter. /// is . /// is empty or white space. public Param( string name, object? value, - TDbType? type = null, - ParameterDirection direction = ParameterDirection.Input) + TDbType? type = null) { if (name is null) throw new ArgumentNullException(nameof(name)); if (string.IsNullOrWhiteSpace(name)) @@ -39,10 +37,7 @@ public Param( Name = name; Type = type; - Direction = direction; - - bool isInput = direction is ParameterDirection.Input or ParameterDirection.InputOutput; - Value = isInput ? (value ?? DBNull.Value) : value; + Value = value ?? DBNull.Value; } /// @@ -62,9 +57,8 @@ public Param( /// Whether the parameter is a member of an AddParams object. /// The CLR type of the argument. /// The database type, or to let the provider infer it. - /// The direction of the parameter. - private Param(string name, object? value, string? expression, bool fromObject, Type? clrType, TDbType? type = null, ParameterDirection direction = ParameterDirection.Input) - : this(name, value, type, direction) + private Param(string name, object? value, string? expression, bool fromObject, Type? clrType, TDbType? type = null) + : this(name, value, type) { Expression = expression; FromObject = fromObject; @@ -96,10 +90,9 @@ internal static Param Derived(string name, string expression, object? value, Typ /// The value of the parameter. /// The CLR type of the argument. /// The database type, or to let the provider infer it. - /// The direction of the parameter. /// The parameter. - internal static Param Typed(string name, object? value, Type clrType, TDbType? type, ParameterDirection direction = ParameterDirection.Input) - => new(name, value, expression: null, fromObject: false, clrType, type, direction); + internal static Param Typed(string name, object? value, Type clrType, TDbType? type) + => new(name, value, expression: null, fromObject: false, clrType, type); /// /// Makes a parameter from a member of an object given to @@ -123,7 +116,7 @@ internal static Param OfObject(string member, object? value, Type clrType) /// The real name. /// The parameter under its real name. internal Param Resolved(string name) - => new(name, Value, expression: null, fromObject: false, ClrType, Type, Direction); + => new(name, Value, expression: null, fromObject: false, ClrType, Type); /// Gets the CLR type of the argument a derived parameter came from, so a NULL can be sent with a type. internal Type? ClrType { get; } @@ -144,9 +137,9 @@ internal Param Resolved(string name) public string Name { get; } /// - /// Gets the value of the parameter. Input and input/output parameters hold instead of . + /// Gets the value of the parameter. A value is held as . /// - /// The value of the parameter, or for an output or return-value parameter that was given none. + /// The value of the parameter, never . public object? Value { get; } /// @@ -157,11 +150,5 @@ internal Param Resolved(string name) /// A NULL made by a typed AddParam overload reports here and is still sent with the database type of its argument. /// public TDbType? Type { get; } - - /// - /// Gets the direction of the parameter. - /// - /// One of the values. - public ParameterDirection Direction { get; } } } diff --git a/Source/Core/PublicAPI.Unshipped.txt b/Source/Core/PublicAPI.Unshipped.txt index b554d224..e29ac7e7 100644 --- a/Source/Core/PublicAPI.Unshipped.txt +++ b/Source/Core/PublicAPI.Unshipped.txt @@ -67,3 +67,6 @@ Open.Database.Extensions.ExpressiveCommandBase.AddParam(string! name, object? value, TDbType type) -> TThis! *REMOVED*Open.Database.Extensions.ExpressiveCommandBase.AddParamIf(bool condition, string! name, object? value, TDbType type, System.Data.ParameterDirection direction = System.Data.ParameterDirection.Input) -> TThis! Open.Database.Extensions.ExpressiveCommandBase.AddParamIf(bool condition, string! name, object? value, TDbType type) -> TThis! +*REMOVED*Open.Database.Extensions.ExpressiveCommandBase.Param.Direction.get -> System.Data.ParameterDirection +*REMOVED*Open.Database.Extensions.ExpressiveCommandBase.Param.Param(string! name, object? value, TDbType? type = null, System.Data.ParameterDirection direction = System.Data.ParameterDirection.Input) -> void +Open.Database.Extensions.ExpressiveCommandBase.Param.Param(string! name, object? value, TDbType? type = null) -> void diff --git a/Source/MSSqlClient/ExpressiveSqlCommand.cs b/Source/MSSqlClient/ExpressiveSqlCommand.cs index a24209b9..fec8ee3e 100644 --- a/Source/MSSqlClient/ExpressiveSqlCommand.cs +++ b/Source/MSSqlClient/ExpressiveSqlCommand.cs @@ -101,8 +101,7 @@ public ExpressiveSqlCommand( /// Adds the command's parameters to a new . /// /// - /// A parameter that has a value is added with it, so the provider infers the type from the value. - /// A parameter that has no value (an output or return-value parameter) is still added, so that it reaches the command. + /// Each parameter is added with its value, so the provider infers the type from the value. /// The database type is applied when one was given; otherwise a database null that came from an argument of a static type is sent with the of that argument, as a null carries no type of its own. /// /// The command to add the parameters to. @@ -114,17 +113,7 @@ protected override void AddParams(SqlCommand command) foreach (Param p in Params) { - SqlParameter np; - if (p.Value is null) - { - np = command.CreateParameter(); - np.ParameterName = p.Name; - command.Parameters.Add(np); // a parameter with no value (output, return value) must still reach the command - } - else - { - np = command.Parameters.AddWithValue(p.Name, p.Value); - } + SqlParameter np = command.Parameters.AddWithValue(p.Name, p.Value); if (p.Type.HasValue) np.SqlDbType = p.Type.Value; diff --git a/Source/SqlClient/ExpressiveSqlCommand.cs b/Source/SqlClient/ExpressiveSqlCommand.cs index bbec2cc3..8a755967 100644 --- a/Source/SqlClient/ExpressiveSqlCommand.cs +++ b/Source/SqlClient/ExpressiveSqlCommand.cs @@ -120,17 +120,7 @@ protected override void AddParams(SqlCommand command) foreach (Param p in Params) { - SqlParameter np; - if (p.Value is null) - { - np = command.CreateParameter(); - np.ParameterName = p.Name; - command.Parameters.Add(np); // a parameter with no value (output, return value) must still reach the command - } - else - { - np = command.Parameters.AddWithValue(p.Name, p.Value); - } + SqlParameter np = command.Parameters.AddWithValue(p.Name, p.Value); if (p.Type.HasValue) np.SqlDbType = p.Type.Value; diff --git a/Tests/Open.Database.Extensions.Core.Tests/ParameterBindingMatrixTests.cs b/Tests/Open.Database.Extensions.Core.Tests/ParameterBindingMatrixTests.cs index 9087821c..96f9aefe 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/ParameterBindingMatrixTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/ParameterBindingMatrixTests.cs @@ -187,6 +187,5 @@ public static void ATypedNullByteArray_IsSentAsDBNull_WithItsType() var p = Assert.Single(cmd.Params); Assert.Equal(DBNull.Value, p.Value); Assert.Equal(DbType.Binary, p.Type); - Assert.Equal(ParameterDirection.Input, p.Direction); } } diff --git a/Tests/Open.Database.Extensions.Core.Tests/ParameterTypeOverloadTests.cs b/Tests/Open.Database.Extensions.Core.Tests/ParameterTypeOverloadTests.cs index efc40024..c2860ca3 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/ParameterTypeOverloadTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/ParameterTypeOverloadTests.cs @@ -24,9 +24,9 @@ protected override void AddParams(IDbCommand command) { } static string Show(object? value) => value is null ? "null" : value is DBNull ? "DBNull" : Convert.ToString(value, CultureInfo.InvariantCulture)!; - // What the command holds: name=value databaseType direction, "-" when no database type was given. + // What the command holds: name=value databaseType, "-" when no database type was given. static string Sent(SqlTyped command) - => string.Join("; ", command.Params.Select(p => $"{p.Name}={Show(p.Value)} {(p.Type.HasValue ? p.Type.Value.ToString() : "-")} {p.Direction}")); + => string.Join("; ", command.Params.Select(p => $"{p.Name}={Show(p.Value)} {(p.Type.HasValue ? p.Type.Value.ToString() : "-")}")); static string Only(bool condition, string expected) => condition ? expected : ""; @@ -41,10 +41,10 @@ public static void AddParam_StringAndType() string s = "a"; string? n = null; - Assert.Equal("x=a NVarChar Input", Sent(New().AddParam("x", s, SqlDbType.NVarChar))); - Assert.Equal("x=DBNull NVarChar Input", Sent(New().AddParam("x", n, SqlDbType.NVarChar))); - Assert.Equal("x=a NVarChar Input", Sent(New().AddParam("x", "a", SqlDbType.NVarChar))); - Assert.Equal("x=DBNull NVarChar Input", Sent(New().AddParam("x", null, SqlDbType.NVarChar))); + Assert.Equal("x=a NVarChar", Sent(New().AddParam("x", s, SqlDbType.NVarChar))); + Assert.Equal("x=DBNull NVarChar", Sent(New().AddParam("x", n, SqlDbType.NVarChar))); + Assert.Equal("x=a NVarChar", Sent(New().AddParam("x", "a", SqlDbType.NVarChar))); + Assert.Equal("x=DBNull NVarChar", Sent(New().AddParam("x", null, SqlDbType.NVarChar))); } [Fact] @@ -55,15 +55,15 @@ public static void AddParam_IntegersAndType() short sh = 7; byte b = 8; - Assert.Equal("x=5 Int Input", Sent(New().AddParam("x", i, SqlDbType.Int))); - Assert.Equal("x=6 BigInt Input", Sent(New().AddParam("x", l, SqlDbType.BigInt))); - Assert.Equal("x=7 SmallInt Input", Sent(New().AddParam("x", sh, SqlDbType.SmallInt))); - Assert.Equal("x=8 TinyInt Input", Sent(New().AddParam("x", b, SqlDbType.TinyInt))); - Assert.Equal("x=5 Int Input", Sent(New().AddParam("x", 5, SqlDbType.Int))); - Assert.Equal("x=0 Int Input", Sent(New().AddParam("x", 0, SqlDbType.Int))); - Assert.Equal("x=6 BigInt Input", Sent(New().AddParam("x", 6L, SqlDbType.BigInt))); - Assert.Equal("x=5 Int Input", Sent(New().AddParam(name: "x", value: i, type: SqlDbType.Int))); - Assert.Equal("x=5 Int Input", Sent(New().AddParam("x", 5, SqlDbType.Int))); + Assert.Equal("x=5 Int", Sent(New().AddParam("x", i, SqlDbType.Int))); + Assert.Equal("x=6 BigInt", Sent(New().AddParam("x", l, SqlDbType.BigInt))); + Assert.Equal("x=7 SmallInt", Sent(New().AddParam("x", sh, SqlDbType.SmallInt))); + Assert.Equal("x=8 TinyInt", Sent(New().AddParam("x", b, SqlDbType.TinyInt))); + Assert.Equal("x=5 Int", Sent(New().AddParam("x", 5, SqlDbType.Int))); + Assert.Equal("x=0 Int", Sent(New().AddParam("x", 0, SqlDbType.Int))); + Assert.Equal("x=6 BigInt", Sent(New().AddParam("x", 6L, SqlDbType.BigInt))); + Assert.Equal("x=5 Int", Sent(New().AddParam(name: "x", value: i, type: SqlDbType.Int))); + Assert.Equal("x=5 Int", Sent(New().AddParam("x", 5, SqlDbType.Int))); } [Fact] @@ -74,10 +74,10 @@ public static void AddParam_NarrowAndUnsignedIntegersAndType_SendTheNumber() uint ui = 5; ulong ul = 6; - Assert.Equal("x=3 SmallInt Input", Sent(New().AddParam("x", sb, SqlDbType.SmallInt))); - Assert.Equal("x=4 Int Input", Sent(New().AddParam("x", us, SqlDbType.Int))); - Assert.Equal("x=5 BigInt Input", Sent(New().AddParam("x", ui, SqlDbType.BigInt))); - Assert.Equal("x=6 Decimal Input", Sent(New().AddParam("x", ul, SqlDbType.Decimal))); + Assert.Equal("x=3 SmallInt", Sent(New().AddParam("x", sb, SqlDbType.SmallInt))); + Assert.Equal("x=4 Int", Sent(New().AddParam("x", us, SqlDbType.Int))); + Assert.Equal("x=5 BigInt", Sent(New().AddParam("x", ui, SqlDbType.BigInt))); + Assert.Equal("x=6 Decimal", Sent(New().AddParam("x", ul, SqlDbType.Decimal))); } // A char is sent as the character, not as its code. @@ -86,9 +86,9 @@ public static void AddParam_CharAndType_SendsTheCharacter() { char c = 'c'; - Assert.Equal("x=c NChar Input", Sent(New().AddParam("x", c, SqlDbType.NChar))); - Assert.Equal("x=c NChar Input", Sent(New().AddParam("x", 'c', SqlDbType.NChar))); - Assert.Equal("x=c NChar Input", Sent(New().AddParamIf(true, "x", c, SqlDbType.NChar))); + Assert.Equal("x=c NChar", Sent(New().AddParam("x", c, SqlDbType.NChar))); + Assert.Equal("x=c NChar", Sent(New().AddParam("x", 'c', SqlDbType.NChar))); + Assert.Equal("x=c NChar", Sent(New().AddParamIf(true, "x", c, SqlDbType.NChar))); Assert.IsType(New().AddParam("x", c, SqlDbType.NChar).Params[0].Value); } @@ -108,9 +108,9 @@ public static void AddParam_CharWithoutType_SendsTheCharacter_AndAnIntStaysAnInt Assert.Equal('c', Assert.IsType(New().AddParamIf(true, "x", c).Params[0].Value)); Assert.Equal('c', Assert.IsType(New().AddParamIf(true, "x", 'c').Params[0].Value)); Assert.Equal('c', Assert.IsType(New().AddParamIf(true, "x", c, null).Params[0].Value)); - Assert.Equal("x=c - Input", Sent(New().AddParam("x", c))); - Assert.Equal("x=c NChar Input", Sent(New().AddParam("x", c, type))); - Assert.Equal("x=c NChar Input", Sent(New().AddParam("x", c, SqlDbType.NChar))); + Assert.Equal("x=c -", Sent(New().AddParam("x", c))); + Assert.Equal("x=c NChar", Sent(New().AddParam("x", c, type))); + Assert.Equal("x=c NChar", Sent(New().AddParam("x", c, SqlDbType.NChar))); Assert.Equal("", Sent(New().AddParamIf(false, "x", c))); Assert.Equal(5, Assert.IsType(New().AddParam("x", 5).Params[0].Value)); @@ -150,17 +150,17 @@ public static void AddParam_NullableValueAndType() bool? b = true; double? db = 2.5; - Assert.Equal("x=9 Int Input", Sent(New().AddParam("x", ni, SqlDbType.Int))); - Assert.Equal("x=DBNull Int Input", Sent(New().AddParam("x", nn, SqlDbType.Int))); - Assert.Equal("x=DBNull Int Input", Sent(New().AddParam("x", (int?)null, SqlDbType.Int))); - Assert.Equal("x=10 BigInt Input", Sent(New().AddParam("x", ln, SqlDbType.BigInt))); - Assert.Equal("x=11 SmallInt Input", Sent(New().AddParam("x", sh, SqlDbType.SmallInt))); - Assert.Equal("x=12 TinyInt Input", Sent(New().AddParam("x", by, SqlDbType.TinyInt))); - Assert.Equal("x=1.5 Decimal Input", Sent(New().AddParam("x", d, SqlDbType.Decimal))); - Assert.Equal("x=01/02/2020 03:04:05 DateTime2 Input", Sent(New().AddParam("x", dt, SqlDbType.DateTime2))); - Assert.Equal("x=11111111-2222-3333-4444-555555555555 UniqueIdentifier Input", Sent(New().AddParam("x", g, SqlDbType.UniqueIdentifier))); - Assert.Equal("x=True Bit Input", Sent(New().AddParam("x", b, SqlDbType.Bit))); - Assert.Equal("x=2.5 Float Input", Sent(New().AddParam("x", db, SqlDbType.Float))); + Assert.Equal("x=9 Int", Sent(New().AddParam("x", ni, SqlDbType.Int))); + Assert.Equal("x=DBNull Int", Sent(New().AddParam("x", nn, SqlDbType.Int))); + Assert.Equal("x=DBNull Int", Sent(New().AddParam("x", (int?)null, SqlDbType.Int))); + Assert.Equal("x=10 BigInt", Sent(New().AddParam("x", ln, SqlDbType.BigInt))); + Assert.Equal("x=11 SmallInt", Sent(New().AddParam("x", sh, SqlDbType.SmallInt))); + Assert.Equal("x=12 TinyInt", Sent(New().AddParam("x", by, SqlDbType.TinyInt))); + Assert.Equal("x=1.5 Decimal", Sent(New().AddParam("x", d, SqlDbType.Decimal))); + Assert.Equal("x=01/02/2020 03:04:05 DateTime2", Sent(New().AddParam("x", dt, SqlDbType.DateTime2))); + Assert.Equal("x=11111111-2222-3333-4444-555555555555 UniqueIdentifier", Sent(New().AddParam("x", g, SqlDbType.UniqueIdentifier))); + Assert.Equal("x=True Bit", Sent(New().AddParam("x", b, SqlDbType.Bit))); + Assert.Equal("x=2.5 Float", Sent(New().AddParam("x", db, SqlDbType.Float))); } // ---- a value and a database type: the forms that already compiled keep their meaning ---- @@ -170,17 +170,17 @@ public static void AddParam_OtherValuesAndType_AreUnchanged() { object o = "a"; - Assert.Equal("x=1.5 Decimal Input", Sent(New().AddParam("x", 1.5m, SqlDbType.Decimal))); - Assert.Equal("x=01/02/2020 03:04:05 DateTime2 Input", Sent(New().AddParam("x", Stamp, SqlDbType.DateTime2))); - Assert.Equal("x=11111111-2222-3333-4444-555555555555 UniqueIdentifier Input", Sent(New().AddParam("x", Key, SqlDbType.UniqueIdentifier))); - Assert.Equal("x=True Bit Input", Sent(New().AddParam("x", true, SqlDbType.Bit))); - Assert.Equal("x=System.Byte[] VarBinary Input", Sent(New().AddParam("x", new byte[] { 1 }, SqlDbType.VarBinary))); - Assert.Equal("x=2.5 Float Input", Sent(New().AddParam("x", 2.5, SqlDbType.Float))); - Assert.Equal("x=3.5 Real Input", Sent(New().AddParam("x", 3.5f, SqlDbType.Real))); - Assert.Equal("x=a NVarChar Input", Sent(New().AddParam("x", o, SqlDbType.NVarChar))); - Assert.Equal("x=5 Int Input", Sent(New().AddParam("x", (object)5, SqlDbType.Int))); - Assert.Equal("x=DBNull NVarChar Input", Sent(New().AddParam("x", DBNull.Value, SqlDbType.NVarChar))); - Assert.Equal("x=Monday Int Input", Sent(New().AddParam("x", DayOfWeek.Monday, SqlDbType.Int))); + Assert.Equal("x=1.5 Decimal", Sent(New().AddParam("x", 1.5m, SqlDbType.Decimal))); + Assert.Equal("x=01/02/2020 03:04:05 DateTime2", Sent(New().AddParam("x", Stamp, SqlDbType.DateTime2))); + Assert.Equal("x=11111111-2222-3333-4444-555555555555 UniqueIdentifier", Sent(New().AddParam("x", Key, SqlDbType.UniqueIdentifier))); + Assert.Equal("x=True Bit", Sent(New().AddParam("x", true, SqlDbType.Bit))); + Assert.Equal("x=System.Byte[] VarBinary", Sent(New().AddParam("x", new byte[] { 1 }, SqlDbType.VarBinary))); + Assert.Equal("x=2.5 Float", Sent(New().AddParam("x", 2.5, SqlDbType.Float))); + Assert.Equal("x=3.5 Real", Sent(New().AddParam("x", 3.5f, SqlDbType.Real))); + Assert.Equal("x=a NVarChar", Sent(New().AddParam("x", o, SqlDbType.NVarChar))); + Assert.Equal("x=5 Int", Sent(New().AddParam("x", (object)5, SqlDbType.Int))); + Assert.Equal("x=DBNull NVarChar", Sent(New().AddParam("x", DBNull.Value, SqlDbType.NVarChar))); + Assert.Equal("x=Monday Int", Sent(New().AddParam("x", DayOfWeek.Monday, SqlDbType.Int))); } [Fact] @@ -191,15 +191,15 @@ public static void AddParam_OptionalTypeForms_AreUnchanged() int? ni = 9; SqlDbType? type = SqlDbType.Int; - Assert.Equal("x=5 - Input", Sent(New().AddParam("x", i))); - Assert.Equal("x=a - Input", Sent(New().AddParam("x", s))); - Assert.Equal("x=9 - Input", Sent(New().AddParam("x", ni))); - Assert.Equal("x=5 - Input", Sent(New().AddParam("x", i, null))); - Assert.Equal("x=a - Input", Sent(New().AddParam("x", s, null))); - Assert.Equal("x=5 - Input", Sent(New().AddParam("x", 5, null))); - Assert.Equal("x=5 Int Input", Sent(New().AddParam("x", i, type))); - Assert.Equal("x=a Int Input", Sent(New().AddParam("x", s, type))); - Assert.Equal("x=9 Int Input", Sent(New().AddParam("x", ni, type))); + Assert.Equal("x=5 -", Sent(New().AddParam("x", i))); + Assert.Equal("x=a -", Sent(New().AddParam("x", s))); + Assert.Equal("x=9 -", Sent(New().AddParam("x", ni))); + Assert.Equal("x=5 -", Sent(New().AddParam("x", i, null))); + Assert.Equal("x=a -", Sent(New().AddParam("x", s, null))); + Assert.Equal("x=5 -", Sent(New().AddParam("x", 5, null))); + Assert.Equal("x=5 Int", Sent(New().AddParam("x", i, type))); + Assert.Equal("x=a Int", Sent(New().AddParam("x", s, type))); + Assert.Equal("x=9 Int", Sent(New().AddParam("x", ni, type))); } // ---- the conditional forms, with the condition true and false ---- @@ -221,20 +221,20 @@ public static void AddParamIf_ValueAndType_AddsOnlyWhenTrue(bool condition) decimal? dn = 2.5m; char c = 'c'; - Assert.Equal(Only(condition, "x=a NVarChar Input"), Sent(New().AddParamIf(condition, "x", s, SqlDbType.NVarChar))); - Assert.Equal(Only(condition, "x=DBNull NVarChar Input"), Sent(New().AddParamIf(condition, "x", n, SqlDbType.NVarChar))); - Assert.Equal(Only(condition, "x=DBNull NVarChar Input"), Sent(New().AddParamIf(condition, "x", null, SqlDbType.NVarChar))); - Assert.Equal(Only(condition, "x=5 Int Input"), Sent(New().AddParamIf(condition, "x", i, SqlDbType.Int))); - Assert.Equal(Only(condition, "x=6 BigInt Input"), Sent(New().AddParamIf(condition, "x", l, SqlDbType.BigInt))); - Assert.Equal(Only(condition, "x=7 SmallInt Input"), Sent(New().AddParamIf(condition, "x", sh, SqlDbType.SmallInt))); - Assert.Equal(Only(condition, "x=8 TinyInt Input"), Sent(New().AddParamIf(condition, "x", b, SqlDbType.TinyInt))); - Assert.Equal(Only(condition, "x=9 Int Input"), Sent(New().AddParamIf(condition, "x", ni, SqlDbType.Int))); - Assert.Equal(Only(condition, "x=10 BigInt Input"), Sent(New().AddParamIf(condition, "x", ln, SqlDbType.BigInt))); - Assert.Equal(Only(condition, "x=1.5 Decimal Input"), Sent(New().AddParamIf(condition, "x", d, SqlDbType.Decimal))); - Assert.Equal(Only(condition, "x=2.5 Decimal Input"), Sent(New().AddParamIf(condition, "x", dn, SqlDbType.Decimal))); - Assert.Equal(Only(condition, "x=01/02/2020 03:04:05 DateTime2 Input"), Sent(New().AddParamIf(condition, "x", Stamp, SqlDbType.DateTime2))); - Assert.Equal(Only(condition, "x=c NChar Input"), Sent(New().AddParamIf(condition, "x", c, SqlDbType.NChar))); - Assert.Equal(Only(condition, "x=3 Int Input"), Sent(New().AddParamIf(condition, "x", 3, SqlDbType.Int))); + Assert.Equal(Only(condition, "x=a NVarChar"), Sent(New().AddParamIf(condition, "x", s, SqlDbType.NVarChar))); + Assert.Equal(Only(condition, "x=DBNull NVarChar"), Sent(New().AddParamIf(condition, "x", n, SqlDbType.NVarChar))); + Assert.Equal(Only(condition, "x=DBNull NVarChar"), Sent(New().AddParamIf(condition, "x", null, SqlDbType.NVarChar))); + Assert.Equal(Only(condition, "x=5 Int"), Sent(New().AddParamIf(condition, "x", i, SqlDbType.Int))); + Assert.Equal(Only(condition, "x=6 BigInt"), Sent(New().AddParamIf(condition, "x", l, SqlDbType.BigInt))); + Assert.Equal(Only(condition, "x=7 SmallInt"), Sent(New().AddParamIf(condition, "x", sh, SqlDbType.SmallInt))); + Assert.Equal(Only(condition, "x=8 TinyInt"), Sent(New().AddParamIf(condition, "x", b, SqlDbType.TinyInt))); + Assert.Equal(Only(condition, "x=9 Int"), Sent(New().AddParamIf(condition, "x", ni, SqlDbType.Int))); + Assert.Equal(Only(condition, "x=10 BigInt"), Sent(New().AddParamIf(condition, "x", ln, SqlDbType.BigInt))); + Assert.Equal(Only(condition, "x=1.5 Decimal"), Sent(New().AddParamIf(condition, "x", d, SqlDbType.Decimal))); + Assert.Equal(Only(condition, "x=2.5 Decimal"), Sent(New().AddParamIf(condition, "x", dn, SqlDbType.Decimal))); + Assert.Equal(Only(condition, "x=01/02/2020 03:04:05 DateTime2"), Sent(New().AddParamIf(condition, "x", Stamp, SqlDbType.DateTime2))); + Assert.Equal(Only(condition, "x=c NChar"), Sent(New().AddParamIf(condition, "x", c, SqlDbType.NChar))); + Assert.Equal(Only(condition, "x=3 Int"), Sent(New().AddParamIf(condition, "x", 3, SqlDbType.Int))); } [Theory] @@ -246,10 +246,10 @@ public static void AddParamIf_OptionalTypeForms_AreUnchanged(bool condition) int i = 5; SqlDbType? type = SqlDbType.Int; - Assert.Equal(Only(condition, "x=a - Input"), Sent(New().AddParamIf(condition, "x", s))); - Assert.Equal(Only(condition, "x=5 - Input"), Sent(New().AddParamIf(condition, "x", i))); - Assert.Equal(Only(condition, "x=5 - Input"), Sent(New().AddParamIf(condition, "x", i, null))); - Assert.Equal(Only(condition, "x=5 Int Input"), Sent(New().AddParamIf(condition, "x", i, type))); + Assert.Equal(Only(condition, "x=a -"), Sent(New().AddParamIf(condition, "x", s))); + Assert.Equal(Only(condition, "x=5 -"), Sent(New().AddParamIf(condition, "x", i))); + Assert.Equal(Only(condition, "x=5 -"), Sent(New().AddParamIf(condition, "x", i, null))); + Assert.Equal(Only(condition, "x=5 Int"), Sent(New().AddParamIf(condition, "x", i, type))); } // ---- what reaches the provider's parameter (DbType, as ExpressiveCommand uses) ---- diff --git a/Tests/Open.Database.Extensions.Core.Tests/SqlServerParameterTypeTests.cs b/Tests/Open.Database.Extensions.Core.Tests/SqlServerParameterTypeTests.cs index 303d571c..d5e8442a 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/SqlServerParameterTypeTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/SqlServerParameterTypeTests.cs @@ -19,14 +19,14 @@ static ExpressiveSqlCommand Legacy() static string Show(object? value) => value is null ? "null" : value is DBNull ? "DBNull" : Convert.ToString(value, System.Globalization.CultureInfo.InvariantCulture)!; - // What the command holds: name=value databaseType direction, "-" when no database type was given. + // What the command holds: name=value databaseType, "-" when no database type was given. #pragma warning disable CS0618 // Obsolete in 11.0, removed in 12: kept covered until then. static string Sent(ExpressiveSqlCommand command) - => string.Join("; ", command.Params.Select(p => $"{p.Name}={Show(p.Value)} {(p.Type.HasValue ? p.Type.Value.ToString() : "-")} {p.Direction}")); + => string.Join("; ", command.Params.Select(p => $"{p.Name}={Show(p.Value)} {(p.Type.HasValue ? p.Type.Value.ToString() : "-")}")); #pragma warning restore CS0618 static string Sent(mssql::Open.Database.Extensions.ExpressiveSqlCommand command) - => string.Join("; ", command.Params.Select(p => $"{p.Name}={Show(p.Value)} {(p.Type.HasValue ? p.Type.Value.ToString() : "-")} {p.Direction}")); + => string.Join("; ", command.Params.Select(p => $"{p.Name}={Show(p.Value)} {(p.Type.HasValue ? p.Type.Value.ToString() : "-")}")); // ---- the calls that must keep their meaning ---- @@ -36,22 +36,22 @@ public static void AValueIsStillAValue_AboveAllALiteralZero() { int zero = 0; - Assert.Equal("@x=0 - Input", Sent(Legacy().AddParam("@x", 0))); - Assert.Equal("@x=0 - Input", Sent(Microsoft().AddParam("@x", 0))); - Assert.Equal("@x=0 - Input", Sent(Legacy().AddParam("@x", zero))); - Assert.Equal("@x=0 - Input", Sent(Microsoft().AddParam("@x", zero))); - Assert.Equal("@x=0 - Input", Sent(Legacy().AddParam("@x", 0L))); - Assert.Equal("@x=0 Int Input", Sent(Microsoft().AddParam("@x", 0, SqlDbType.Int))); - Assert.Equal("@x=0 Int Input", Sent(Legacy().AddParamIf(true, "@x", 0, SqlDbType.Int))); - Assert.Equal("@x=0 - Input", Sent(Microsoft().AddParamIf(true, "@x", 0))); - Assert.Equal("@x=c - Input", Sent(Legacy().AddParam("@x", 'c'))); - Assert.Equal("@x=c - Input", Sent(Microsoft().AddParam("@x", 'c'))); - Assert.Equal("@x=a - Input", Sent(Microsoft().AddParam("@x", "a"))); + Assert.Equal("@x=0 -", Sent(Legacy().AddParam("@x", 0))); + Assert.Equal("@x=0 -", Sent(Microsoft().AddParam("@x", 0))); + Assert.Equal("@x=0 -", Sent(Legacy().AddParam("@x", zero))); + Assert.Equal("@x=0 -", Sent(Microsoft().AddParam("@x", zero))); + Assert.Equal("@x=0 -", Sent(Legacy().AddParam("@x", 0L))); + Assert.Equal("@x=0 Int", Sent(Microsoft().AddParam("@x", 0, SqlDbType.Int))); + Assert.Equal("@x=0 Int", Sent(Legacy().AddParamIf(true, "@x", 0, SqlDbType.Int))); + Assert.Equal("@x=0 -", Sent(Microsoft().AddParamIf(true, "@x", 0))); + Assert.Equal("@x=c -", Sent(Legacy().AddParam("@x", 'c'))); + Assert.Equal("@x=c -", Sent(Microsoft().AddParam("@x", 'c'))); + Assert.Equal("@x=a -", Sent(Microsoft().AddParam("@x", "a"))); } [Fact] public static void ASqlDbTypeIsStillASqlDbType() { - Assert.Equal("@x=5 Int Input", Sent(Legacy().AddParam("@x", 5, SqlDbType.Int))); + Assert.Equal("@x=5 Int", Sent(Legacy().AddParam("@x", 5, SqlDbType.Int))); } } diff --git a/Tests/Open.Database.Extensions.LegacyCompiler.Tests/ParameterTypeTests.cs b/Tests/Open.Database.Extensions.LegacyCompiler.Tests/ParameterTypeTests.cs index ca4f3d76..c4f22e59 100644 --- a/Tests/Open.Database.Extensions.LegacyCompiler.Tests/ParameterTypeTests.cs +++ b/Tests/Open.Database.Extensions.LegacyCompiler.Tests/ParameterTypeTests.cs @@ -34,12 +34,12 @@ sealed class NoConnections : IDbConnectionFactory static string Show(object value) => value == null ? "null" : value is DBNull ? "DBNull" : Convert.ToString(value, CultureInfo.InvariantCulture); - // What the command holds: name=value databaseType direction, "-" when no database type was given. + // What the command holds: name=value databaseType, "-" when no database type was given. static string Sent(SqlTyped command) - => string.Join("; ", command.Params.Select(p => $"{p.Name}={Show(p.Value)} {(p.Type.HasValue ? p.Type.Value.ToString() : "-")} {p.Direction}")); + => string.Join("; ", command.Params.Select(p => $"{p.Name}={Show(p.Value)} {(p.Type.HasValue ? p.Type.Value.ToString() : "-")}")); static string SentDb(ExpressiveCommand command) - => string.Join("; ", command.Params.Select(p => $"{p.Name}={Show(p.Value)} {(p.Type.HasValue ? p.Type.Value.ToString() : "-")} {p.Direction}")); + => string.Join("; ", command.Params.Select(p => $"{p.Name}={Show(p.Value)} {(p.Type.HasValue ? p.Type.Value.ToString() : "-")}")); // ---- a value and a database type: the forms that were ambiguous ---- @@ -49,12 +49,12 @@ public static void AddParam_StringAndType() string s = "a"; string n = null; - Assert.Equal("x=a NVarChar Input", Sent(New().AddParam("x", s, SqlDbType.NVarChar))); - Assert.Equal("x=DBNull NVarChar Input", Sent(New().AddParam("x", n, SqlDbType.NVarChar))); - Assert.Equal("x=a NVarChar Input", Sent(New().AddParam("x", "a", SqlDbType.NVarChar))); - Assert.Equal("x=DBNull NVarChar Input", Sent(New().AddParam("x", null, SqlDbType.NVarChar))); - Assert.Equal("x=DBNull NVarChar Input", Sent(New().AddParam("x", null, SqlDbType.NVarChar))); - Assert.Equal("x=a NVarChar Input", Sent(New().AddParam(name: "x", value: s, type: SqlDbType.NVarChar))); + Assert.Equal("x=a NVarChar", Sent(New().AddParam("x", s, SqlDbType.NVarChar))); + Assert.Equal("x=DBNull NVarChar", Sent(New().AddParam("x", n, SqlDbType.NVarChar))); + Assert.Equal("x=a NVarChar", Sent(New().AddParam("x", "a", SqlDbType.NVarChar))); + Assert.Equal("x=DBNull NVarChar", Sent(New().AddParam("x", null, SqlDbType.NVarChar))); + Assert.Equal("x=DBNull NVarChar", Sent(New().AddParam("x", null, SqlDbType.NVarChar))); + Assert.Equal("x=a NVarChar", Sent(New().AddParam(name: "x", value: s, type: SqlDbType.NVarChar))); } [Fact] @@ -65,15 +65,15 @@ public static void AddParam_IntegersAndType() short sh = 7; byte b = 8; - Assert.Equal("x=5 Int Input", Sent(New().AddParam("x", i, SqlDbType.Int))); - Assert.Equal("x=6 BigInt Input", Sent(New().AddParam("x", l, SqlDbType.BigInt))); - Assert.Equal("x=7 SmallInt Input", Sent(New().AddParam("x", sh, SqlDbType.SmallInt))); - Assert.Equal("x=8 TinyInt Input", Sent(New().AddParam("x", b, SqlDbType.TinyInt))); - Assert.Equal("x=5 Int Input", Sent(New().AddParam("x", 5, SqlDbType.Int))); - Assert.Equal("x=0 Int Input", Sent(New().AddParam("x", 0, SqlDbType.Int))); - Assert.Equal("x=6 BigInt Input", Sent(New().AddParam("x", 6L, SqlDbType.BigInt))); - Assert.Equal("x=5 Int Input", Sent(New().AddParam(name: "x", value: i, type: SqlDbType.Int))); - Assert.Equal("x=5 Int Input", Sent(New().AddParam("x", 5, SqlDbType.Int))); + Assert.Equal("x=5 Int", Sent(New().AddParam("x", i, SqlDbType.Int))); + Assert.Equal("x=6 BigInt", Sent(New().AddParam("x", l, SqlDbType.BigInt))); + Assert.Equal("x=7 SmallInt", Sent(New().AddParam("x", sh, SqlDbType.SmallInt))); + Assert.Equal("x=8 TinyInt", Sent(New().AddParam("x", b, SqlDbType.TinyInt))); + Assert.Equal("x=5 Int", Sent(New().AddParam("x", 5, SqlDbType.Int))); + Assert.Equal("x=0 Int", Sent(New().AddParam("x", 0, SqlDbType.Int))); + Assert.Equal("x=6 BigInt", Sent(New().AddParam("x", 6L, SqlDbType.BigInt))); + Assert.Equal("x=5 Int", Sent(New().AddParam(name: "x", value: i, type: SqlDbType.Int))); + Assert.Equal("x=5 Int", Sent(New().AddParam("x", 5, SqlDbType.Int))); } [Fact] @@ -84,10 +84,10 @@ public static void AddParam_NarrowAndUnsignedIntegersAndType_SendTheNumber() uint ui = 5; ulong ul = 6; - Assert.Equal("x=3 SmallInt Input", Sent(New().AddParam("x", sb, SqlDbType.SmallInt))); - Assert.Equal("x=4 Int Input", Sent(New().AddParam("x", us, SqlDbType.Int))); - Assert.Equal("x=5 BigInt Input", Sent(New().AddParam("x", ui, SqlDbType.BigInt))); - Assert.Equal("x=6 Decimal Input", Sent(New().AddParam("x", ul, SqlDbType.Decimal))); + Assert.Equal("x=3 SmallInt", Sent(New().AddParam("x", sb, SqlDbType.SmallInt))); + Assert.Equal("x=4 Int", Sent(New().AddParam("x", us, SqlDbType.Int))); + Assert.Equal("x=5 BigInt", Sent(New().AddParam("x", ui, SqlDbType.BigInt))); + Assert.Equal("x=6 Decimal", Sent(New().AddParam("x", ul, SqlDbType.Decimal))); } // A char is sent as the character, not as its code. @@ -96,9 +96,9 @@ public static void AddParam_CharAndType_SendsTheCharacter() { char c = 'c'; - Assert.Equal("x=c NChar Input", Sent(New().AddParam("x", c, SqlDbType.NChar))); - Assert.Equal("x=c NChar Input", Sent(New().AddParam("x", 'c', SqlDbType.NChar))); - Assert.Equal("x=c NChar Input", Sent(New().AddParamIf(true, "x", c, SqlDbType.NChar))); + Assert.Equal("x=c NChar", Sent(New().AddParam("x", c, SqlDbType.NChar))); + Assert.Equal("x=c NChar", Sent(New().AddParam("x", 'c', SqlDbType.NChar))); + Assert.Equal("x=c NChar", Sent(New().AddParamIf(true, "x", c, SqlDbType.NChar))); } // A char converts implicitly to int, but it is a character: AddParam("x", 'c') sends 'c', not 99, as it did before there was an int overload. An int is still an int. @@ -117,9 +117,9 @@ public static void AddParam_CharWithoutType_SendsTheCharacter_AndAnIntStaysAnInt Assert.Equal('c', Assert.IsType(New().AddParamIf(true, "x", c).Params[0].Value)); Assert.Equal('c', Assert.IsType(New().AddParamIf(true, "x", 'c').Params[0].Value)); Assert.Equal('c', Assert.IsType(New().AddParamIf(true, "x", c, null).Params[0].Value)); - Assert.Equal("x=c - Input", Sent(New().AddParam("x", c))); - Assert.Equal("x=c NChar Input", Sent(New().AddParam("x", c, type))); - Assert.Equal("x=c NChar Input", Sent(New().AddParam("x", c, SqlDbType.NChar))); + Assert.Equal("x=c -", Sent(New().AddParam("x", c))); + Assert.Equal("x=c NChar", Sent(New().AddParam("x", c, type))); + Assert.Equal("x=c NChar", Sent(New().AddParam("x", c, SqlDbType.NChar))); Assert.Equal("", Sent(New().AddParamIf(false, "x", c))); Assert.Equal(5, Assert.IsType(New().AddParam("x", 5).Params[0].Value)); @@ -143,17 +143,17 @@ public static void AddParam_NullableValueAndType() bool? b = true; double? db = 2.5; - Assert.Equal("x=9 Int Input", Sent(New().AddParam("x", ni, SqlDbType.Int))); - Assert.Equal("x=DBNull Int Input", Sent(New().AddParam("x", nn, SqlDbType.Int))); - Assert.Equal("x=DBNull Int Input", Sent(New().AddParam("x", (int?)null, SqlDbType.Int))); - Assert.Equal("x=10 BigInt Input", Sent(New().AddParam("x", ln, SqlDbType.BigInt))); - Assert.Equal("x=11 SmallInt Input", Sent(New().AddParam("x", sh, SqlDbType.SmallInt))); - Assert.Equal("x=12 TinyInt Input", Sent(New().AddParam("x", by, SqlDbType.TinyInt))); - Assert.Equal("x=1.5 Decimal Input", Sent(New().AddParam("x", d, SqlDbType.Decimal))); - Assert.Equal("x=01/02/2020 03:04:05 DateTime2 Input", Sent(New().AddParam("x", dt, SqlDbType.DateTime2))); - Assert.Equal("x=11111111-2222-3333-4444-555555555555 UniqueIdentifier Input", Sent(New().AddParam("x", g, SqlDbType.UniqueIdentifier))); - Assert.Equal("x=True Bit Input", Sent(New().AddParam("x", b, SqlDbType.Bit))); - Assert.Equal("x=2.5 Float Input", Sent(New().AddParam("x", db, SqlDbType.Float))); + Assert.Equal("x=9 Int", Sent(New().AddParam("x", ni, SqlDbType.Int))); + Assert.Equal("x=DBNull Int", Sent(New().AddParam("x", nn, SqlDbType.Int))); + Assert.Equal("x=DBNull Int", Sent(New().AddParam("x", (int?)null, SqlDbType.Int))); + Assert.Equal("x=10 BigInt", Sent(New().AddParam("x", ln, SqlDbType.BigInt))); + Assert.Equal("x=11 SmallInt", Sent(New().AddParam("x", sh, SqlDbType.SmallInt))); + Assert.Equal("x=12 TinyInt", Sent(New().AddParam("x", by, SqlDbType.TinyInt))); + Assert.Equal("x=1.5 Decimal", Sent(New().AddParam("x", d, SqlDbType.Decimal))); + Assert.Equal("x=01/02/2020 03:04:05 DateTime2", Sent(New().AddParam("x", dt, SqlDbType.DateTime2))); + Assert.Equal("x=11111111-2222-3333-4444-555555555555 UniqueIdentifier", Sent(New().AddParam("x", g, SqlDbType.UniqueIdentifier))); + Assert.Equal("x=True Bit", Sent(New().AddParam("x", b, SqlDbType.Bit))); + Assert.Equal("x=2.5 Float", Sent(New().AddParam("x", db, SqlDbType.Float))); } // ---- a value and a database type: the forms that already compiled keep their meaning ---- @@ -163,17 +163,17 @@ public static void AddParam_OtherValuesAndType_AreUnchanged() { object o = "a"; - Assert.Equal("x=1.5 Decimal Input", Sent(New().AddParam("x", 1.5m, SqlDbType.Decimal))); - Assert.Equal("x=01/02/2020 03:04:05 DateTime2 Input", Sent(New().AddParam("x", new DateTime(2020, 1, 2, 3, 4, 5), SqlDbType.DateTime2))); - Assert.Equal("x=11111111-2222-3333-4444-555555555555 UniqueIdentifier Input", Sent(New().AddParam("x", new Guid("11111111-2222-3333-4444-555555555555"), SqlDbType.UniqueIdentifier))); - Assert.Equal("x=True Bit Input", Sent(New().AddParam("x", true, SqlDbType.Bit))); - Assert.Equal("x=System.Byte[] VarBinary Input", Sent(New().AddParam("x", new byte[] { 1 }, SqlDbType.VarBinary))); - Assert.Equal("x=2.5 Float Input", Sent(New().AddParam("x", 2.5, SqlDbType.Float))); - Assert.Equal("x=3.5 Real Input", Sent(New().AddParam("x", 3.5f, SqlDbType.Real))); - Assert.Equal("x=a NVarChar Input", Sent(New().AddParam("x", o, SqlDbType.NVarChar))); - Assert.Equal("x=5 Int Input", Sent(New().AddParam("x", (object)5, SqlDbType.Int))); - Assert.Equal("x=DBNull NVarChar Input", Sent(New().AddParam("x", DBNull.Value, SqlDbType.NVarChar))); - Assert.Equal("x=Monday Int Input", Sent(New().AddParam("x", DayOfWeek.Monday, SqlDbType.Int))); + Assert.Equal("x=1.5 Decimal", Sent(New().AddParam("x", 1.5m, SqlDbType.Decimal))); + Assert.Equal("x=01/02/2020 03:04:05 DateTime2", Sent(New().AddParam("x", new DateTime(2020, 1, 2, 3, 4, 5), SqlDbType.DateTime2))); + Assert.Equal("x=11111111-2222-3333-4444-555555555555 UniqueIdentifier", Sent(New().AddParam("x", new Guid("11111111-2222-3333-4444-555555555555"), SqlDbType.UniqueIdentifier))); + Assert.Equal("x=True Bit", Sent(New().AddParam("x", true, SqlDbType.Bit))); + Assert.Equal("x=System.Byte[] VarBinary", Sent(New().AddParam("x", new byte[] { 1 }, SqlDbType.VarBinary))); + Assert.Equal("x=2.5 Float", Sent(New().AddParam("x", 2.5, SqlDbType.Float))); + Assert.Equal("x=3.5 Real", Sent(New().AddParam("x", 3.5f, SqlDbType.Real))); + Assert.Equal("x=a NVarChar", Sent(New().AddParam("x", o, SqlDbType.NVarChar))); + Assert.Equal("x=5 Int", Sent(New().AddParam("x", (object)5, SqlDbType.Int))); + Assert.Equal("x=DBNull NVarChar", Sent(New().AddParam("x", DBNull.Value, SqlDbType.NVarChar))); + Assert.Equal("x=Monday Int", Sent(New().AddParam("x", DayOfWeek.Monday, SqlDbType.Int))); } [Fact] @@ -184,15 +184,15 @@ public static void AddParam_OptionalTypeForms_AreUnchanged() int? ni = 9; SqlDbType? type = SqlDbType.Int; - Assert.Equal("x=5 - Input", Sent(New().AddParam("x", i))); - Assert.Equal("x=a - Input", Sent(New().AddParam("x", s))); - Assert.Equal("x=9 - Input", Sent(New().AddParam("x", ni))); - Assert.Equal("x=5 - Input", Sent(New().AddParam("x", i, null))); - Assert.Equal("x=a - Input", Sent(New().AddParam("x", s, null))); - Assert.Equal("x=5 - Input", Sent(New().AddParam("x", 5, null))); - Assert.Equal("x=5 Int Input", Sent(New().AddParam("x", i, type))); - Assert.Equal("x=a Int Input", Sent(New().AddParam("x", s, type))); - Assert.Equal("x=9 Int Input", Sent(New().AddParam("x", ni, type))); + Assert.Equal("x=5 -", Sent(New().AddParam("x", i))); + Assert.Equal("x=a -", Sent(New().AddParam("x", s))); + Assert.Equal("x=9 -", Sent(New().AddParam("x", ni))); + Assert.Equal("x=5 -", Sent(New().AddParam("x", i, null))); + Assert.Equal("x=a -", Sent(New().AddParam("x", s, null))); + Assert.Equal("x=5 -", Sent(New().AddParam("x", 5, null))); + Assert.Equal("x=5 Int", Sent(New().AddParam("x", i, type))); + Assert.Equal("x=a Int", Sent(New().AddParam("x", s, type))); + Assert.Equal("x=9 Int", Sent(New().AddParam("x", ni, type))); } // ---- the conditional forms ---- @@ -212,19 +212,19 @@ public static void AddParamIf_ValueAndType_AddsWhenTrue() decimal? dn = 2.5m; var dt = new DateTime(2020, 1, 2, 3, 4, 5); - Assert.Equal("x=a NVarChar Input", Sent(New().AddParamIf(true, "x", s, SqlDbType.NVarChar))); - Assert.Equal("x=DBNull NVarChar Input", Sent(New().AddParamIf(true, "x", n, SqlDbType.NVarChar))); - Assert.Equal("x=DBNull NVarChar Input", Sent(New().AddParamIf(true, "x", null, SqlDbType.NVarChar))); - Assert.Equal("x=5 Int Input", Sent(New().AddParamIf(true, "x", i, SqlDbType.Int))); - Assert.Equal("x=6 BigInt Input", Sent(New().AddParamIf(true, "x", l, SqlDbType.BigInt))); - Assert.Equal("x=7 SmallInt Input", Sent(New().AddParamIf(true, "x", sh, SqlDbType.SmallInt))); - Assert.Equal("x=8 TinyInt Input", Sent(New().AddParamIf(true, "x", b, SqlDbType.TinyInt))); - Assert.Equal("x=9 Int Input", Sent(New().AddParamIf(true, "x", ni, SqlDbType.Int))); - Assert.Equal("x=10 BigInt Input", Sent(New().AddParamIf(true, "x", ln, SqlDbType.BigInt))); - Assert.Equal("x=1.5 Decimal Input", Sent(New().AddParamIf(true, "x", d, SqlDbType.Decimal))); - Assert.Equal("x=2.5 Decimal Input", Sent(New().AddParamIf(true, "x", dn, SqlDbType.Decimal))); - Assert.Equal("x=01/02/2020 03:04:05 DateTime2 Input", Sent(New().AddParamIf(true, "x", dt, SqlDbType.DateTime2))); - Assert.Equal("x=3 Int Input", Sent(New().AddParamIf(true, "x", 3, SqlDbType.Int))); + Assert.Equal("x=a NVarChar", Sent(New().AddParamIf(true, "x", s, SqlDbType.NVarChar))); + Assert.Equal("x=DBNull NVarChar", Sent(New().AddParamIf(true, "x", n, SqlDbType.NVarChar))); + Assert.Equal("x=DBNull NVarChar", Sent(New().AddParamIf(true, "x", null, SqlDbType.NVarChar))); + Assert.Equal("x=5 Int", Sent(New().AddParamIf(true, "x", i, SqlDbType.Int))); + Assert.Equal("x=6 BigInt", Sent(New().AddParamIf(true, "x", l, SqlDbType.BigInt))); + Assert.Equal("x=7 SmallInt", Sent(New().AddParamIf(true, "x", sh, SqlDbType.SmallInt))); + Assert.Equal("x=8 TinyInt", Sent(New().AddParamIf(true, "x", b, SqlDbType.TinyInt))); + Assert.Equal("x=9 Int", Sent(New().AddParamIf(true, "x", ni, SqlDbType.Int))); + Assert.Equal("x=10 BigInt", Sent(New().AddParamIf(true, "x", ln, SqlDbType.BigInt))); + Assert.Equal("x=1.5 Decimal", Sent(New().AddParamIf(true, "x", d, SqlDbType.Decimal))); + Assert.Equal("x=2.5 Decimal", Sent(New().AddParamIf(true, "x", dn, SqlDbType.Decimal))); + Assert.Equal("x=01/02/2020 03:04:05 DateTime2", Sent(New().AddParamIf(true, "x", dt, SqlDbType.DateTime2))); + Assert.Equal("x=3 Int", Sent(New().AddParamIf(true, "x", 3, SqlDbType.Int))); } [Fact] @@ -254,10 +254,10 @@ public static void AddParamIf_OptionalTypeForms_AreUnchanged() int i = 5; SqlDbType? type = SqlDbType.Int; - Assert.Equal("x=a - Input", Sent(New().AddParamIf(true, "x", s))); - Assert.Equal("x=5 - Input", Sent(New().AddParamIf(true, "x", i))); - Assert.Equal("x=5 - Input", Sent(New().AddParamIf(true, "x", i, null))); - Assert.Equal("x=5 Int Input", Sent(New().AddParamIf(true, "x", i, type))); + Assert.Equal("x=a -", Sent(New().AddParamIf(true, "x", s))); + Assert.Equal("x=5 -", Sent(New().AddParamIf(true, "x", i))); + Assert.Equal("x=5 -", Sent(New().AddParamIf(true, "x", i, null))); + Assert.Equal("x=5 Int", Sent(New().AddParamIf(true, "x", i, type))); } // ---- the same with DbType, the database type of ExpressiveCommand ---- @@ -275,22 +275,22 @@ public static void ExpressiveCommand_ValueAndDbType() int? ni = 9; decimal d = 1.5m; - Assert.Equal("x=a String Input", SentDb(NewDb().AddParam("x", s, DbType.String))); - Assert.Equal("x=DBNull String Input", SentDb(NewDb().AddParam("x", n, DbType.String))); - Assert.Equal("x=DBNull String Input", SentDb(NewDb().AddParam("x", null, DbType.String))); - Assert.Equal("x=5 Int32 Input", SentDb(NewDb().AddParam("x", i, DbType.Int32))); - Assert.Equal("x=6 Int64 Input", SentDb(NewDb().AddParam("x", l, DbType.Int64))); - Assert.Equal("x=7 Int16 Input", SentDb(NewDb().AddParam("x", sh, DbType.Int16))); - Assert.Equal("x=8 Byte Input", SentDb(NewDb().AddParam("x", b, DbType.Byte))); - Assert.Equal("x=c StringFixedLength Input", SentDb(NewDb().AddParam("x", c, DbType.StringFixedLength))); - Assert.Equal("x=9 Int32 Input", SentDb(NewDb().AddParam("x", ni, DbType.Int32))); - Assert.Equal("x=1.5 Decimal Input", SentDb(NewDb().AddParam("x", d, DbType.Decimal))); - Assert.Equal("x=5 Int32 Input", SentDb(NewDb().AddParam("x", 5, DbType.Int32))); - Assert.Equal("x=0 Int32 Input", SentDb(NewDb().AddParam("x", 0, DbType.Int32))); - Assert.Equal("x=5 Int32 Input", SentDb(NewDb().AddParamIf(true, "x", i, DbType.Int32))); - Assert.Equal("x=a String Input", SentDb(NewDb().AddParamIf(true, "x", s, DbType.String))); - Assert.Equal("x=6 Int64 Input", SentDb(NewDb().AddParamIf(true, "x", l, DbType.Int64))); - Assert.Equal("x=9 Int32 Input", SentDb(NewDb().AddParamIf(true, "x", ni, DbType.Int32))); + Assert.Equal("x=a String", SentDb(NewDb().AddParam("x", s, DbType.String))); + Assert.Equal("x=DBNull String", SentDb(NewDb().AddParam("x", n, DbType.String))); + Assert.Equal("x=DBNull String", SentDb(NewDb().AddParam("x", null, DbType.String))); + Assert.Equal("x=5 Int32", SentDb(NewDb().AddParam("x", i, DbType.Int32))); + Assert.Equal("x=6 Int64", SentDb(NewDb().AddParam("x", l, DbType.Int64))); + Assert.Equal("x=7 Int16", SentDb(NewDb().AddParam("x", sh, DbType.Int16))); + Assert.Equal("x=8 Byte", SentDb(NewDb().AddParam("x", b, DbType.Byte))); + Assert.Equal("x=c StringFixedLength", SentDb(NewDb().AddParam("x", c, DbType.StringFixedLength))); + Assert.Equal("x=9 Int32", SentDb(NewDb().AddParam("x", ni, DbType.Int32))); + Assert.Equal("x=1.5 Decimal", SentDb(NewDb().AddParam("x", d, DbType.Decimal))); + Assert.Equal("x=5 Int32", SentDb(NewDb().AddParam("x", 5, DbType.Int32))); + Assert.Equal("x=0 Int32", SentDb(NewDb().AddParam("x", 0, DbType.Int32))); + Assert.Equal("x=5 Int32", SentDb(NewDb().AddParamIf(true, "x", i, DbType.Int32))); + Assert.Equal("x=a String", SentDb(NewDb().AddParamIf(true, "x", s, DbType.String))); + Assert.Equal("x=6 Int64", SentDb(NewDb().AddParamIf(true, "x", l, DbType.Int64))); + Assert.Equal("x=9 Int32", SentDb(NewDb().AddParamIf(true, "x", ni, DbType.Int32))); Assert.Equal("", SentDb(NewDb().AddParamIf(false, "x", i, DbType.Int32))); } @@ -300,26 +300,26 @@ public static void ExpressiveCommand_ValueAndDbType() [Fact] public static void AddParam_ALiteralZero_IsAValue_WithNoDatabaseType() { - Assert.Equal("id=0 - Input", SentDb(NewDb().AddParam("id", 0))); - Assert.Equal("id=0 - Input", SentDb(NewDb().AddParam("id", 0L))); - Assert.Equal("id=0 - Input", SentDb(NewDb().AddParamIf(true, "id", 0))); - Assert.Equal("id=0 - Input", SentDb(NewDb().AddParamIf(true, "id", 0L))); - Assert.Equal("id=0 - Input", Sent(New().AddParam("id", 0))); - Assert.Equal("id=0 - Input", Sent(New().AddParam("id", 0L))); - Assert.Equal("id=5 - Input", Sent(New().AddParam("id", 5))); + Assert.Equal("id=0 -", SentDb(NewDb().AddParam("id", 0))); + Assert.Equal("id=0 -", SentDb(NewDb().AddParam("id", 0L))); + Assert.Equal("id=0 -", SentDb(NewDb().AddParamIf(true, "id", 0))); + Assert.Equal("id=0 -", SentDb(NewDb().AddParamIf(true, "id", 0L))); + Assert.Equal("id=0 -", Sent(New().AddParam("id", 0))); + Assert.Equal("id=0 -", Sent(New().AddParam("id", 0L))); + Assert.Equal("id=5 -", Sent(New().AddParam("id", 5))); int five = 5; long six = 6; DbType? noType = null; SqlDbType? sqlNoType = null; - Assert.Equal("id=5 - Input", SentDb(NewDb().AddParam("id", five, null))); - Assert.Equal("id=5 - Input", SentDb(NewDb().AddParam("id", five, noType))); - Assert.Equal("id=5 Int32 Input", SentDb(NewDb().AddParam("id", five, (DbType?)DbType.Int32))); - Assert.Equal("id=6 - Input", SentDb(NewDb().AddParam("id", six, noType))); - Assert.Equal("id=5 - Input", Sent(New().AddParam("id", five, sqlNoType))); - Assert.Equal("id=5 - Input", SentDb(NewDb().AddParamIf(true, "id", five, null))); + Assert.Equal("id=5 -", SentDb(NewDb().AddParam("id", five, null))); + Assert.Equal("id=5 -", SentDb(NewDb().AddParam("id", five, noType))); + Assert.Equal("id=5 Int32", SentDb(NewDb().AddParam("id", five, (DbType?)DbType.Int32))); + Assert.Equal("id=6 -", SentDb(NewDb().AddParam("id", six, noType))); + Assert.Equal("id=5 -", Sent(New().AddParam("id", five, sqlNoType))); + Assert.Equal("id=5 -", SentDb(NewDb().AddParamIf(true, "id", five, null))); // A typed NULL byte array: object value with a database type (DS2 #8). - Assert.Equal("b=DBNull Binary Input", SentDb(NewDb().AddParam("b", (byte[])null, DbType.Binary))); + Assert.Equal("b=DBNull Binary", SentDb(NewDb().AddParam("b", (byte[])null, DbType.Binary))); } } } diff --git a/docsite/articles/release-notes.md b/docsite/articles/release-notes.md index 974aa5bc..0743dea0 100644 --- a/docsite/articles/release-notes.md +++ b/docsite/articles/release-notes.md @@ -9,7 +9,7 @@ Version 11 is `11.0.0-rc.16`. For moving a 10.x codebase, read [Coming from earl - **Generated row readers for `DbQuery` too.** A plain `Map()` on a `DbQuery`, a `DbQuery` or a query bound with `Using` now gets its row reader written at build time, as on a command or a reader; before, it used the runtime map. The runtime map's conversions are therefore no longer applied there: see [Generated readers](mapping.md#generated-readers) for the differences and the switch. - **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`; `AddParam(name, type)`, `AddParam(name, direction)`, `AddParamIf` with only a type or direction, and `AddReturnParam` are gone. 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. +- **Removed: parameter directions on the fluent chain.** `AddParam` and `AddParamIf` no longer take a `ParameterDirection`; `AddParam(name, type)`, `AddParam(name, direction)`, `AddParamIf` with only a type or direction, and `AddReturnParam` are gone. 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. `Param` has no `direction` constructor parameter and no `Direction` property. ### Changes since rc.15 diff --git a/docsite/articles/whats-new-11.md b/docsite/articles/whats-new-11.md index 4de33afa..0ba8b88b 100644 --- a/docsite/articles/whats-new-11.md +++ b/docsite/articles/whats-new-11.md @@ -129,7 +129,7 @@ See [Expressive commands](expressive-commands.md). - **Names from arguments.** `.AddParam(author)` takes the name from the variable and matches it to the stored procedure's real name. `AddParam("name", value)` always wins. - **A typed NULL** such as `AddParam("@id", (long?)null)` is sent with the database type of its overload. - **After a run, `Params` holds what you added,** under the names as added. Read the provider command's `Parameters` in `Execute(command => ...)` to see what was sent. -- **No direction on the chain.** `AddParam`, `AddParamIf` and `AddReturnParam` no longer take a `ParameterDirection`, so a parameter added on the chain is an input; the overloads that took only a direction or only a type, and `AddReturnParam`, are gone. To set a direction, use `ExecuteAsync(command => ...)` with the raw `AddParameter`, `AddParameterType` and `AddReturnParameter` extensions. +- **No direction on the chain.** `AddParam`, `AddParamIf` and `AddReturnParam` no longer take a `ParameterDirection`, so a parameter added on the chain is an input; the overloads that took only a direction or only a type, and `AddReturnParam`, are gone. To set a direction, use `ExecuteAsync(command => ...)` with the raw `AddParameter`, `AddParameterType` and `AddReturnParameter` extensions. `Param` has no `direction` constructor parameter and no `Direction` property. See [Parameters](expressive-commands.md#name-a-parameter-from-its-argument). From 0d883a4a2c51f59576bc3e209fbf4d97cc565cef Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Tue, 1 Dec 2026 19:48:31 -0800 Subject: [PATCH 03/20] Read output parameters into a model with ExecuteOutputAsync. ExecuteOutputAsync() on the expressive commands runs the command and maps its output parameters and return code into a model by name, with the Map() rules (the runtime map, never a generated reader). ExecuteOutputAsync(name) reads one value. A decimal needs its precision and scale, or the server rounds it to a whole number: [Column(TypeName = "decimal(p,s)")] on a member, or ExecuteOutputDecimalAsync(name, precision, scale) and ExecuteOutputAsync(name, precision, scale) for one value. Members match parameters as AddParam(value) does when the names are known, [Column("name")] exactly, and a ReturnValue member reads a procedure's return code. A member whose parameter got a value is sent as InputOutput, any other as Output. DateTime goes as DateTime2, strings and binary with size -1. Core adds the parameters itself after the provider's, per call, never on the command; an output that never arrived throws instead of reading as NULL. Every error names the member, parameter or type, says what is wrong, and gives the fix. ExecuteReturnAsync refuses a model type at the call. Calls without outputs keep their path: one type compare of the run's state. No blocking form (owner decision). Co-Authored-By: Claude Opus 5.5 --- Source/Core/Core/RowMap.cs | 7 + Source/Core/ExpressiveCommandBase.Output.cs | 552 +++++++++++++++ Source/Core/ExpressiveCommandBase.cs | 57 +- Source/Core/NameSet.cs | 6 +- Source/Core/OutputLayout.cs | 629 ++++++++++++++++++ Source/Core/ParameterNames.cs | 19 +- Source/Core/PublicAPI.Unshipped.txt | 4 + Source/Generator/README.md | 1 + .../OutputParameterLocalDbTests.cs | 602 +++++++++++++++++ .../OutputParameterTests.cs | 565 ++++++++++++++++ .../TestHelpers/LocalDbFixture.cs | 8 + docsite/articles/expressive-commands.md | 34 +- docsite/articles/mapping.md | 2 + docsite/articles/release-notes.md | 1 + docsite/articles/whats-new-11.md | 1 + 15 files changed, 2465 insertions(+), 23 deletions(-) create mode 100644 Source/Core/ExpressiveCommandBase.Output.cs create mode 100644 Source/Core/OutputLayout.cs create mode 100644 Tests/Open.Database.Extensions.Core.Tests/OutputParameterLocalDbTests.cs create mode 100644 Tests/Open.Database.Extensions.Core.Tests/OutputParameterTests.cs diff --git a/Source/Core/Core/RowMap.cs b/Source/Core/Core/RowMap.cs index 259aff06..479bd40c 100644 --- a/Source/Core/Core/RowMap.cs +++ b/Source/Core/Core/RowMap.cs @@ -485,6 +485,13 @@ RowMap Converting( /// static readonly ImmutableArray ModelSlots = Model.Slots; + /// + /// Gets the slots of , for the output model of a command (OutputLayout), whose members are exactly the ones a row would feed. + /// + /// The slots; none when cannot be mapped. + [SuppressMessage("Roslynator", "RCS1158:Static member in generic type should use a type parameter", Justification = "They are this T's slots: the type parameter names which T (RowMap.MappedSlots).")] + internal static ImmutableArray MappedSlots => ModelSlots; + /// /// Why cannot be mapped (its shape, else a contradiction in what its members declare), or when it can. /// diff --git a/Source/Core/ExpressiveCommandBase.Output.cs b/Source/Core/ExpressiveCommandBase.Output.cs new file mode 100644 index 00000000..8bcca67c --- /dev/null +++ b/Source/Core/ExpressiveCommandBase.Output.cs @@ -0,0 +1,552 @@ +using System.Diagnostics; + +namespace Open.Database.Extensions; + +// A call that reads output parameters passes its OutputRun as the state of the run, and the run recognizes it by its type: +// the build step resolves the run's members with the names and PrepareCommand adds their parameters. A call without +// outputs pays one compare of its state's type (typeof, never 'state is', which boxes a value-type state in unoptimized +// code: ToListArrayAllocationProbe saw it). The run is never kept on the command. +public abstract partial class ExpressiveCommandBase + where TConnection : class, IDbConnection + where TCommand : class, IDbCommand + where TReader : class, IDataReader + where TDbType : struct + where TThis : ExpressiveCommandBase +{ + /// + /// Asynchronously executes the command, as + /// does, + /// and reads its output parameters and return code into a . + /// + /// + /// + /// Each member Map<TOut>() would read is an output parameter, built by the same rules (constructors, records, + /// required, conversion, [NullPolicy], [NullValue], [NotMapped]). + /// A member is matched to the parameter the way AddParam(value) is: when the names are known (a procedure's, or the + /// @name markers of a text) by the same four tiers, and a member that matches none throws; otherwise it is sent under its own name. + /// [Column("name")] names the parameter exactly. + /// + /// + /// A member whose parameter was given a value (AddParam, AddParams) is sent as + /// , any other as , which sends NULL: + /// a procedure's default for that parameter is not used. + /// A member named ReturnValue reads a stored procedure's return code. + /// + /// + /// A is sent as ; a or array with size -1 (the whole value); + /// a needs [Column(TypeName = "decimal(p,s)")], whose scale also rounds a value sent in. + /// + /// + /// The model the output parameters are read into. + /// + /// A task that represents the asynchronous operation; its result is the model. + /// + /// Before anything runs: has no member to read, is a single value, has a member without its type name or a member of a type + /// that has no database type, or reads the return code of a command that is not a stored procedure. + /// Before the command executes: a member matches no parameter, two match one, or the procedure declares a parameter a ReturnValue member would also match. + /// After: the output parameters were not delivered (the response did not complete). + /// + /// A value does not convert to its member, or is NULL and the member does not take it. + /// + /// The command's token or is canceled. + /// + public ValueTask ExecuteOutputAsync( + CancellationToken cancellationToken = default) + { + OutputLayout layout = OutputLayout.Get(); + if (layout.HasReturnValue) ThrowUnlessProcedure(layout); + + // Thrown synchronously, not through the returned task. + CancellationToken.ThrowIfCancellationRequested(); + cancellationToken.ThrowIfCancellationRequested(); + + return RunOutputAsync( + new OutputRun(layout), + static async (cmd, _, run) => + { + if (cmd is DbCommand dbCommand) + await dbCommand.ExecuteNonQueryAsync(run.Token).ConfigureAwait(false); + else + cmd.ExecuteNonQuery(); + + return run.Map(); + }, + cancellationToken); + } + + /// + /// Asynchronously executes the command, as + /// does, + /// and reads one output parameter, converted to . + /// + /// + /// + /// names the parameter exactly, with or without its @ and in any case; "ReturnValue" names a declared parameter, + /// not the return code (that is ). + /// A value added under the same name makes it . + /// + /// + /// The value converts as Map<T>() converts a single column; NULL is only when takes it. + /// A needs its precision and scale, or the server rounds it to a whole number, so this form refuses it: use + /// or . + /// + /// + /// The type of the value. + /// The name of the output parameter. + /// + /// + /// A task that completes when the command has executed and its output parameters are read; its result is the value. + /// + /// is . + /// is empty, white space or a bare @. + /// + /// Before anything runs: is not a single value, is a , or has no database type. + /// Before the command executes: the names are known and none is . + /// After: the output parameter was not delivered (the response did not complete). + /// + /// The value does not convert to , or is NULL and is a non-nullable value type. + /// + /// The command's token or is canceled. + /// + public ValueTask ExecuteOutputAsync( + string name, + CancellationToken cancellationToken = default) + { + ThrowIfNoName(name); + Contract.EndContractBlock(); + + return RunNamedAsync(OutputValue.Get(name), cancellationToken); + } + + /// + /// Asynchronously executes the command, as + /// does, + /// and reads one output parameter of the given precision and scale, converted to . + /// + /// + /// + /// The parameter is sent as with and , as its SQL type + /// declares them (decimal(19,4): 19 and 4); without them the server rounds the value to a whole number. + /// The scale also rounds a value sent in. + /// + /// + /// Otherwise as : names the parameter exactly, + /// and a value added under the same name makes it . + /// NULL is in a of and an error in a . + /// + /// + /// This form lets decide how NULL is handled and is checked when it is called: any other throws. + /// always returns a of + /// and is checked by the compiler. A model member declares the same with [Column(TypeName = "decimal(p,s)")] + /// (). + /// + /// + /// + /// + /// decimal total = await connection + /// .StoredProcedure("dbo.OrderTotal") + /// .AddParam(orderId) + /// .ExecuteOutputAsync<decimal>("total", 19, 4); + /// + /// + /// , or a of it. + /// The name of the output parameter. + /// The number of digits its SQL type declares, from 1 to 38. + /// The number of those digits after the decimal point, from 0 to . + /// + /// + /// A task that completes when the command has executed and its output parameters are read; its result is the value. + /// + /// is . + /// is empty, white space or a bare @. + /// + /// Before anything runs: is 0 or more than 38, or is more than . + /// + /// + /// Before anything runs: is not a (only a decimal takes a precision and scale). + /// Before the command executes: the names are known and none is . + /// After: the output parameter was not delivered (the response did not complete). + /// + /// The value does not convert to , or is NULL and is . + /// + /// The command's token or is canceled. + /// + public ValueTask ExecuteOutputAsync( + string name, + byte precision, + byte scale, + CancellationToken cancellationToken = default) + { + ThrowIfNoName(name); + OutputValue.ThrowUnlessDecimal(name); + Contract.EndContractBlock(); + + // T is decimal? or decimal. Each cast goes through object to the same type, which the JIT removes in optimized code. + ValueTask value = ExecuteOutputDecimalAsync(name, precision, scale, cancellationToken); + return typeof(T) == typeof(decimal?) + ? (ValueTask)(object)value + : (ValueTask)(object)NotNullAsync(name, value); + } + + /// + /// Awaits a decimal output parameter that a reads: NULL is an error. + /// + /// The parameter's name. + /// The value, as reads it. + /// The value. + /// The value is NULL. + static async ValueTask NotNullAsync(string name, ValueTask value) + => await value.ConfigureAwait(false) + ?? throw new ValueMappingException( + $"The decimal output parameter '{name}' is NULL, which a decimal cannot hold. " + + $"Read it as decimal? (ExecuteOutputAsync(\"{name}\", precision, scale)) or with ExecuteOutputDecimalAsync(\"{name}\", precision, scale), which return null for NULL.", + name, + name, + typeof(decimal)); + + /// + /// Asynchronously executes the command, as + /// does, + /// and reads one output parameter of the given precision and scale. + /// + /// + /// + /// The parameter is sent with and , as its SQL type declares them + /// (decimal(19,4): 19 and 4); without them the server rounds the value to a whole number. + /// + /// + /// This form always returns a of (NULL is ) and is checked by the compiler. + /// lets its type decide how NULL is handled and is checked when it is called. + /// Otherwise the two are the same, and as . + /// + /// + /// + /// + /// decimal? total = await connection + /// .StoredProcedure("dbo.OrderTotal") + /// .AddParam(orderId) + /// .ExecuteOutputDecimalAsync("total", 19, 4); + /// + /// + /// The name of the output parameter. + /// The number of digits its SQL type declares, from 1 to 38. + /// The number of those digits after the decimal point, from 0 to . + /// + /// + /// A task that completes when the command has executed and its output parameters are read; its result is the value, or for NULL. + /// + /// is . + /// is empty, white space or a bare @. + /// + /// Before anything runs: is 0 or more than 38, or is more than . + /// + /// + /// Before the command executes: the names are known and none is . + /// After: the output parameter was not delivered (the response did not complete). + /// + /// The value does not convert to a . + /// + /// The command's token or is canceled. + /// + public ValueTask ExecuteOutputDecimalAsync( + string name, + byte precision, + byte scale, + CancellationToken cancellationToken = default) + { + ThrowIfNoName(name); + ThrowIfBadShape(name, precision, scale); + Contract.EndContractBlock(); + + return RunNamedAsync(OutputValue.Shaped(name, precision, scale), cancellationToken); + } + + // One rule with [Column(TypeName = "decimal(p,s)")]: OutputWire.IsDecimalShape. + static void ThrowIfBadShape(string name, byte precision, byte scale) + { + if (OutputWire.IsDecimalShape(precision, scale)) return; + + if (precision is 0 or > 38) + { + throw new ArgumentOutOfRangeException( + nameof(precision), + precision, + $"The precision of the decimal output parameter '{name}' is {precision}, but it must be from 1 to 38: the number of digits its SQL type declares. " + + $"For decimal(19,4), pass ExecuteOutputAsync(\"{name}\", 19, 4)."); + } + + throw new ArgumentOutOfRangeException( + nameof(scale), + scale, + $"The scale of the decimal output parameter '{name}' is {scale}, more than its precision of {precision}: the scale counts the digits after the decimal point, out of the precision. " + + $"For decimal(19,4), pass ExecuteOutputAsync(\"{name}\", 19, 4)."); + } + + const string NameRequired = "A parameter name is required, for example ExecuteOutputAsync(\"total\")."; + + // First in each named form: a model type with a null name binds here (ExecuteOutputAsync(null) compiles). + static void ThrowIfNoName(string name) + { + if (name is null) throw new ArgumentNullException(nameof(name), NameRequired); + if (string.IsNullOrWhiteSpace(name) || name.Trim() == "@") throw new ArgumentException(NameRequired, nameof(name)); + } + + ValueTask RunNamedAsync(OutputLayout layout, CancellationToken cancellationToken) + { + // Thrown synchronously, not through the returned task. + CancellationToken.ThrowIfCancellationRequested(); + cancellationToken.ThrowIfCancellationRequested(); + + return RunOutputAsync( + new OutputRun(layout), + static async (cmd, _, run) => + { + if (cmd is DbCommand dbCommand) + await dbCommand.ExecuteNonQueryAsync(run.Token).ConfigureAwait(false); + else + cmd.ExecuteNonQuery(); + + return run.Single(); + }, + cancellationToken); + } + + /// + /// Runs a call that reads output parameters, under the one token that governs it. + /// + /// The type of the result. + /// The call's output parameters: the state of the run, which is how the build step knows them. + /// The function that executes the command and reads the values. + /// The token passed to the terminal. + /// A task that represents the asynchronous operation; its result is the result of . + ValueTask RunOutputAsync( + OutputRun run, + Func> func, + CancellationToken callToken) + => CancellationTokens.RunAsync( + CancellationToken, + callToken, + (self: this, run, func), + static (s, token) => + { + s.run.Token = token; + return s.self.ExecuteCoreAsync(s.run, s.func, token); + }); + + /// + /// Gets the output parameters of a call whose state is its , or . + /// + /// The type of the state of the run. + /// The state of the run. + /// The run, when is ; otherwise, . + static OutputRun? OutputOf(TState state) + => typeof(TState) == typeof(OutputRun) + ? (OutputRun)(object)state! + : null; + + /// + /// Throws when a model reads the return code of a command that is not a stored procedure. + /// + /// The model's layout. + /// The command is not a stored procedure. + void ThrowUnlessProcedure(OutputLayout layout) + { + if (Type == CommandType.StoredProcedure) return; + + string display = OutputLayout.ReturnValue; + foreach (OutputMember member in layout.Members) + { + if (member.IsReturnValue) display = member.Display; + } + + throw new InvalidOperationException( + $"{display} reads a stored procedure's return code, but the command is not a stored procedure (it is {Type}), and a text batch's return code is always 0. " + + "Call the procedure as CommandType.StoredProcedure, or read an output parameter (@name OUTPUT) into a member of another name."); + } + + /// + /// Names the command for the messages: a procedure's name, or the command text. + /// + /// The name. + string Where() + => Type == CommandType.StoredProcedure + ? Command + : "the command text"; + + /// + /// Resolves the parameter each output member stands for, while the call is built. + /// + /// + /// It runs inside the build step, so a failure here forgets a procedure's kept names as any failure to build does. + /// An output member merges with an input of the same name (see ); only two outputs can collide. + /// + /// The call's output parameters. + /// The names of the procedure or of the text's markers, or when they are not known. + /// + /// A member matches no parameter, two match one, or a declared parameter matches a ReturnValue member. + /// + void ResolveOutputs(OutputRun run, NameSet? names) + { + OutputLayout layout = run.Layout; + + // A text that is not interned has no remembered set: its markers are read for this call. + NameSet? real = names ?? (Type == CommandType.Text ? new NameSet(SqlTextParameters.Parse(Command)) : null); + bool known = real is { Names.Length: > 0 }; + string where = Where(); + run.Where = where; + + var resolved = new string?[layout.Members.Length]; + for (int i = 0; i < resolved.Length; i++) + { + OutputMember member = layout.Members[i]; + string fix = $"Name its parameter exactly with [Column(\"name\")] on {member.Display}."; + if (member.IsReturnValue) + { + // Only a stored procedure gets here (checked at the call): no declared parameter may also answer to the name. + if (known && real!.Match(OutputLayout.ReturnValue, Command, member.Display, fix) is { } declared) + { + throw new InvalidOperationException( + $"{member.Display} reads the return code, but {where} also declares the parameter '{declared}', which the name {OutputLayout.ReturnValue} matches, so it is unclear which one to read. " + + $"To read that parameter, give the member [Column(\"{declared}\")]; to read the return code, rename the procedure's parameter."); + } + + continue; + } + + if (!known) + { + resolved[i] = member.Name; + continue; + } + + resolved[i] = (member.Exact ? real!.Find(member.Name)?.Real : real!.Match(member.Name, Command, member.Display, fix)) + ?? throw NoOutputMatch(member, layout, real.Names, where); + } + + // Two members that resolve to one parameter would read the same value under two meanings. + for (int i = 0; i < resolved.Length; i++) + { + if (resolved[i] is not { } first) continue; + for (int j = i + 1; j < resolved.Length; j++) + { + if (resolved[j] is not { } second || !DbQueryBinding.SameName(first, second)) continue; + + throw new InvalidOperationException( + $"{layout.Members[i].Display} and {layout.Members[j].Display} both resolve to the output parameter '{first}' of {where}, so one value would be read under two meanings. " + + "Name each member's parameter with [Column(\"name\")], or remove one of them."); + } + } + + run.Names = resolved; + } + + static InvalidOperationException NoOutputMatch(OutputMember member, OutputLayout layout, ImmutableArray real, string where) + { + string declared = string.Join(", ", real); + if (layout.IsNamed) + { + return new( + $"{member.Display} is not a parameter of {where}, which declares: {declared}. " + + "Pass one of those names to ExecuteOutputAsync(name), or add the parameter to the procedure (or its @name marker to the text)."); + } + + if (member.Exact) + { + return new( + $"{member.Display} names its parameter '{member.Name}' with [Column], but {where} declares no parameter of that name (it declares: {declared}). " + + "Change the [Column] name to one it declares, or add the parameter."); + } + + return new( + $"{member.Display} has no matching parameter on {where} (tried {string.Join(", ", ParameterNames.Candidates(member.Name))}; it declares: {declared}). " + + $"Add a parameter named {member.Name} to {where}, or name the member's parameter with [Column(\"name\")]."); + } + + // The provider's parameters are already on the command. An output member whose parameter was given a value turns that + // parameter into InputOutput (keeping a type the caller gave), so one name never yields two parameters. + /// + /// Adds the call's output parameters to the command, or turns the matching input into one. + /// + /// The command, with the provider's parameters. + /// The call's output parameters, resolved. + /// The provider did not add a parameter that was sent. + void AddOutputs(TCommand command, OutputRun run) + { + Debug.Assert(run.Names is not null, "The build step resolves the names first."); + OutputLayout layout = run.Layout; + List? send = ActiveSendList; + var parameters = new IDbDataParameter?[layout.Members.Length]; + bool[] pure = new bool[parameters.Length]; + for (int i = 0; i < parameters.Length; i++) + { + OutputMember member = layout.Members[i]; + if (member.IsReturnValue) + { + parameters[i] = command.AddReturnParameter(); + pure[i] = true; + continue; + } + + string name = run.Names![i]!; + OutputWire wire = member.Wire!; + if (Sent(send, name) is { } input) + { + IDbDataParameter parameter = Find(command, input.Name) + ?? throw new InvalidOperationException( + $"{member.Display} reads back the parameter '{input.Name}', which was given a value, but the command's provider did not add it to the command under that name, so there is nothing to read. " + + "Give the value under the name the provider keeps (AddParam(\"name\", value)), or do not give it a value so it is sent as an output only."); + parameter.Direction = ParameterDirection.InputOutput; + if (!input.Type.HasValue) parameter.DbType = wire.Type; + wire.Apply(parameter); + parameters[i] = parameter; + continue; + } + + IDbDataParameter output = command.CreateParameter(); + output.ParameterName = name; + output.Direction = ParameterDirection.Output; + output.DbType = wire.Type; + wire.Apply(output); + command.Parameters.Add(output); + parameters[i] = output; + pure[i] = true; + } + + run.Parameters = parameters; + run.Pure = pure; + } + + /// + /// Finds what is sent under a name, compared without the @ and ignoring case. + /// + /// What the call sends, or . + /// The name. + /// The parameter sent under it, or . + static Param? Sent(List? send, string name) + { + if (send is null) return null; + + foreach (Param p in send) + { + if (DbQueryBinding.SameName(p.Name, name)) return p; + } + + return null; + } + + /// + /// Finds the provider's parameter of a name, compared without the @ and ignoring case. + /// + /// The command. + /// The name it was sent under. + /// The parameter, or . + static IDbDataParameter? Find(TCommand command, string name) + { + foreach (object? p in command.Parameters) + { + if (p is IDbDataParameter parameter && DbQueryBinding.SameName(parameter.ParameterName, name)) return parameter; + } + + return null; + } +} diff --git a/Source/Core/ExpressiveCommandBase.cs b/Source/Core/ExpressiveCommandBase.cs index 4b8fa5b4..23e22991 100644 --- a/Source/Core/ExpressiveCommandBase.cs +++ b/Source/Core/ExpressiveCommandBase.cs @@ -298,6 +298,15 @@ public ushort Timeout /// The connection creates a command that is not a . /// protected TCommand PrepareCommand(TConnection connection) + => PrepareCommand(connection, null); + + /// + /// Creates the command from the connection, with its parameters and, for a call that reads output parameters, those. + /// + /// The connection to create the command from. + /// The call's output parameters, or for a call that reads none. + /// The new command to use. + TCommand PrepareCommand(TConnection connection, OutputRun? output) { IDbCommand cmd = connection.CreateCommand(Type, Command, Timeout); @@ -309,6 +318,9 @@ protected TCommand PrepareCommand(TConnection connection) if (Transaction != null) c.Transaction = Transaction; if ((ActiveSendList ?? _params) is { Count: > 0 }) AddParams(c); + + // After the provider's own parameters, so an override of AddParams cannot leave them out. + if (output is not null) AddOutputs(c, output); return c; } catch @@ -873,12 +885,14 @@ TCommand PrepareWritten(TConnection connection) /// /// for a command that has no derived names, where only a written name that the text spells differently is resolved. /// + /// The call's output parameters, or for a call that reads none; resolved here, with the names. /// The new command to use. - TCommand PrepareDerived(TConnection connection, NameSet? names, bool written = false) + TCommand PrepareDerived(TConnection connection, NameSet? names, bool written = false, OutputRun? output = null) { // Taken out of the spare slot, so a hook that sets up another // command on this thread builds its own list. - List send = _spareList ?? new(_params!.Count); + // A call that only reads output parameters added none. + List send = _spareList ?? new(_params?.Count ?? 0); _spareList = null; object? outerCommand = _preparing; List? outerList = _sendList; @@ -886,9 +900,10 @@ TCommand PrepareDerived(TConnection connection, NameSet? names, bool written = f { if (written) ResolveWritten(send, names!); else BuildSendList(send, names); + if (output is not null) ResolveOutputs(output, names); _preparing = this; _sendList = send; - return PrepareCommand(connection); + return PrepareCommand(connection, output); } finally { @@ -964,7 +979,9 @@ void ResolveWritten(List send, NameSet text) /// The remembered names, or when they are not known. void BuildSendList(List send, NameSet? real) { - List list = _params!; + // A call that only reads output parameters added none. + if (_params is not { Count: > 0 } list) return; + int count = list.Count; // The name each parameter ends up with (null: not sent), in a pooled array; only the used part is cleared when it goes back. @@ -1195,17 +1212,19 @@ private protected async ValueTask ExecuteCoreAsync(TSt TCommand built; try { - if (_hasDerivedParams) + // No local outlives the await, so the state machine gains no field. + if (_hasDerivedParams || typeof(TState) == typeof(OutputRun)) { names = await ResolveDerivedNamesAsync( single, cancellationToken) .ConfigureAwait(false); + built = PrepareDerived(single, names, output: OutputOf(state)); + } + else + { + built = PrepareWritten(single); } - - built = _hasDerivedParams - ? PrepareDerived(single, names) - : PrepareWritten(single); } catch (Exception ex) when (ProcedureParameterNames.ForgetUnlessCanceled(names, ex)) { @@ -1234,15 +1253,16 @@ private protected async ValueTask ExecuteCoreAsync(TSt TCommand leaseBuilt; try { - if (_hasDerivedParams) + if (_hasDerivedParams || typeof(TState) == typeof(OutputRun)) { leaseNames = await ResolveDerivedNamesAsync(lease.Connection, cancellationToken) .ConfigureAwait(false); + leaseBuilt = PrepareDerived(lease.Connection, leaseNames, output: OutputOf(state)); + } + else + { + leaseBuilt = PrepareWritten(lease.Connection); } - - leaseBuilt = _hasDerivedParams - ? PrepareDerived(lease.Connection, leaseNames) - : PrepareWritten(lease.Connection); } catch (Exception ex) when (ProcedureParameterNames.ForgetUnlessCanceled(leaseNames, ex)) { @@ -1809,8 +1829,15 @@ ValueTask IExecuteReader.ExecuteReaderAsync(Func /// /// /// - public async ValueTask ExecuteReturnAsync( + public ValueTask ExecuteReturnAsync( CancellationToken cancellationToken = default) + { + // A model cannot hold the return code: thrown at the call, before anything runs. + ReturnCode.ThrowUnlessScalar(); + return ReturnAsync(cancellationToken); + } + + async ValueTask ReturnAsync(CancellationToken cancellationToken) => RowMap.ConvertScalar( await ExecuteReturnAsync(cancellationToken).ConfigureAwait(false)); diff --git a/Source/Core/NameSet.cs b/Source/Core/NameSet.cs index d502a5f8..d54230e8 100644 --- a/Source/Core/NameSet.cs +++ b/Source/Core/NameSet.cs @@ -125,10 +125,12 @@ Dictionary BuildEntries() /// /// The text of the argument, or the name of a member of an AddParams object. /// The procedure's name or the command text, for the message of an ambiguity. + /// What matches, for the message of an ambiguity; names the argument. + /// The fix, for the message of an ambiguity; for AddParam("name", value). /// The real name, or when the expression matches none. /// The expression is not derivable. /// The expression fits more than one name equally well. - internal string? Match(string expression, string procedure) + internal string? Match(string expression, string procedure, string? subject = null, string? fix = null) { if (_matches.TryGetValue(expression, out string? remembered)) return remembered; @@ -136,7 +138,7 @@ Dictionary BuildEntries() ImmutableArray candidates = ParameterNames.Describe(expression)?.Candidates ?? ParameterNames.Candidates(expression); // Two threads may both match and store: the answer is the same. - string? found = ParameterNames.MatchBare(candidates, Names, BareNames, expression, procedure); + string? found = ParameterNames.MatchBareAs(candidates, Names, BareNames, expression, procedure, subject, fix); if (_matches.Count < MaxMatches) _matches[expression] = found; return found; diff --git a/Source/Core/OutputLayout.cs b/Source/Core/OutputLayout.cs new file mode 100644 index 00000000..1b41ea7f --- /dev/null +++ b/Source/Core/OutputLayout.cs @@ -0,0 +1,629 @@ +using System.Globalization; + +namespace Open.Database.Extensions; + +// The layout is what a model type says about its output parameters, judged once per type: nothing in it depends on a call or a database. +// A call makes its own OutputRun around it; nothing that changes is shared between calls. +/// +/// One value a call reads back: a member of an output model, or the one value of the named form. +/// +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). + /// 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'. + public OutputMember(string name, bool exact, string label, OutputWire wire, string display) + { + Name = name; + Exact = exact; + Label = label; + Wire = wire; + Display = display; + } + + /// Initializes the member that reads the return code. + /// The member's name. + /// The member for the messages: Model.Member. + public OutputMember(string label, string display) + { + Name = label; + Label = label; + Display = display; + IsReturnValue = true; + } + + /// The member's name, its [Column] name, or the name the caller gave. + public readonly string Name; + + /// 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. + public readonly bool Exact; + + /// What the model's map reads the value as. + public readonly string Label; + + /// Whether the member reads the return code. + public readonly bool IsReturnValue; + + /// How the parameter is sent; for the return code, which is the provider's own. + public readonly OutputWire? Wire; +} + +/// +/// Why a type cannot be sent as an output parameter. +/// +enum OutputWireError +{ + /// It can. + None, + + /// The type has no database type. + NoDbType, + + /// A decimal without a declared type name. + DecimalUndeclared, + + /// A decimal whose declared type name is not decimal(p,s) or numeric(p,s). + DecimalBadTypeName, +} + +/// +/// How an output parameter is sent: its database type, and the size, precision and scale it needs. +/// +/// The database type. +/// The size, or 0 for none. +/// The precision of a , else 0. +/// The scale of a , else 0. +sealed class OutputWire(DbType type, int size, byte precision, byte scale) +{ + /// The fix for a type that has no database type, for the messages. + public const string SupportedTypes = "such as int, long, string, DateTime, Guid or byte[]"; + + /// The database type. + public readonly DbType Type = type; + + /// The size, or 0 for none. + public readonly int Size = size; + + /// The precision of a , else 0. + public readonly byte Precision = precision; + + /// The scale of a , else 0. + public readonly byte Scale = scale; + + /// Whether precision and scale are set. + public bool HasPrecision => Precision != 0; + + /// + /// Sets the size, precision and scale on a parameter (not its type). + /// + /// The parameter. + public void Apply(IDbDataParameter parameter) + { + if (Size != 0) parameter.Size = Size; + if (!HasPrecision) return; + + // DbParameter implements IDbDataParameter.Precision and Scale apart from its virtual ones, so through the interface a + // provider that only overrides the virtual ones (not re-implementing the interface) would never see them. + if (parameter is DbParameter db) + { + db.Precision = Precision; + db.Scale = Scale; + return; + } + + parameter.Precision = Precision; + parameter.Scale = Scale; + } + + // DateTime goes as DateTime2 here only: DbType.DateTime (what ClrDbTypes gives an input) cuts a datetime2 to three decimals and fails + // before 1753. Strings and binary take size -1: a size left unset throws at execute, and a size inferred from a value cuts silently. + /// + /// Works out how a value of a CLR type is sent as an output parameter. + /// + /// The member's type. + /// The member's [Column(TypeName)], or . + /// Why it cannot be sent, or . + /// How it is sent, or with set. + public static OutputWire? Of(Type type, string? typeName, out OutputWireError error) + { + error = OutputWireError.None; + Type underlying = Nullable.GetUnderlyingType(type) ?? type; + if (underlying == typeof(DateTime)) return DateTime2; + + if (ClrDbTypes.From(type) is not { } dbType) + { + error = OutputWireError.NoDbType; + return null; + } + + switch (dbType) + { + case DbType.String or DbType.Binary: + return new(dbType, -1, 0, 0); + case DbType.StringFixedLength: + return new(dbType, 1, 0, 0); + case DbType.Decimal: + if (DecimalOf(typeName) is { } wire) return wire; + error = typeName is null ? OutputWireError.DecimalUndeclared : OutputWireError.DecimalBadTypeName; + return null; + default: + return new(dbType, 0, 0, 0); + } + } + + /// + /// Whether a precision and scale are a decimal's: a precision from 1 to 38 and a scale from 0 to the precision. + /// One rule for [Column(TypeName = "decimal(p,s)")] and the named form's precision and scale. + /// + /// The precision. + /// The scale. + /// when they are valid. + public static bool IsDecimalShape(byte precision, byte scale) + => precision is >= 1 and <= 38 && scale <= precision; + + static readonly OutputWire DateTime2 = new(DbType.DateTime2, 0, 0, 0); + + /// + /// Reads decimal(p,s) or numeric(p,s), in any case and with spaces around the parts. + /// + /// The declared type name. + /// The wire of the decimal, or when the name is not one. + static OutputWire? DecimalOf(string? typeName) + { + if (typeName is null) return null; + + string text = typeName.Trim(); + int open = text.IndexOf('('); + if (open < 0 || text[text.Length - 1] != ')') return null; + + string kind = text.Substring(0, open).Trim(); + if (!kind.Equals("decimal", StringComparison.OrdinalIgnoreCase) && !kind.Equals("numeric", StringComparison.OrdinalIgnoreCase)) return null; + + string[] parts = text.Substring(open + 1, text.Length - open - 2).Split(','); + return parts.Length == 2 + && byte.TryParse(parts[0].Trim(), NumberStyles.None, CultureInfo.InvariantCulture, out byte precision) + && byte.TryParse(parts[1].Trim(), NumberStyles.None, CultureInfo.InvariantCulture, out byte scale) + && IsDecimalShape(precision, scale) + ? new(DbType.Decimal, 0, precision, scale) + : null; + } +} + +/// +/// What a call reads back, in order, and where each value goes in the row its model is built from. +/// +sealed class OutputLayout +{ + /// The name of the member that reads the return code. + public const string ReturnValue = "ReturnValue"; + + /// Initializes a layout. + /// The model's type name, for the messages. + /// The members. + /// The cell of each member in the row. + /// The label of each cell of the row; for a cell no member fills. + public OutputLayout(string model, ImmutableArray members, int[] cells, ImmutableArray labels) + { + Model = model; + Members = members; + Cells = cells; + Labels = labels; + foreach (OutputMember member in members) + HasReturnValue |= member.IsReturnValue; + } + + /// Initializes the layout of the named form: one value. + /// The value. + public OutputLayout(OutputMember member) + : this(member.Name, [member], [0], [member.Label]) + => IsNamed = true; + + /// The model's type name, or the parameter's name in the named form, for the messages. + public readonly string Model; + + /// Whether this is the named form: one value under the name the caller gave. + public readonly bool IsNamed; + + /// The members. + public readonly ImmutableArray Members; + + /// The cell of each member in the row. + public readonly int[] Cells; + + /// The label of each cell of the row, as the model's map matches it; for a cell no member fills. + public readonly ImmutableArray Labels; + + /// Whether a member reads the return code. + public readonly bool HasReturnValue; +} + +/// +/// The output layout of a model type, built once. +/// +/// +/// Its members are the members the type's default map (Map<T>()) reads, so the model is built by the same rules. +/// +/// The model type. +static class OutputLayout +{ + // Never throws: a type that cannot be read holds its error, so the static initializer cannot fail with it. + static readonly OutputLayout? Layout = Build(out Error); + + static readonly string? Error; + + /// + /// Gets the layout. + /// + /// The layout. + /// cannot be mapped, or cannot be read from output parameters. + /// A of cannot be honoured. + public static OutputLayout Get() + { + // A single value is told to use the named form, not why it cannot be mapped as a row. + if (!IsScalar) RowMap.ThrowIfUnmappable(); + return Layout ?? throw new InvalidOperationException(Error); + } + + static readonly bool IsScalar = Shape.IsScalar(typeof(TOut)); + + static OutputLayout? Build(out string? error) + { + error = null; + Type type = typeof(TOut); + string model = Shape.TypeName(type); + if (Shape.IsScalar(type)) + { + error = $"ExecuteOutputAsync<{model}>() reads a model of output parameters, but {model} is a single value with no members to match to parameters. " + + $"Call ExecuteOutputAsync<{model}>(name) with the parameter's name, or read into a model with one member per parameter."; + return null; + } + + ImmutableArray slots = RowMap.MappedSlots; + var members = ImmutableArray.CreateBuilder(slots.Length); + var orders = new List(slots.Length); + OutputMember? returnValue = null; + foreach (Slot slot in slots) + { + if (slot.NotMapped) continue; + + OutputMember? member = Member(slot, model, ref error); + if (member is null) return null; + + if (member.IsReturnValue) + { + if (returnValue is not null) + { + error = $"{returnValue.Display} and {member.Display} both read the return code: a member named {OutputLayout.ReturnValue} (in any case) reads it, and a call has only one. " + + "Remove one, or give it [Column(\"name\")] to read an output parameter instead."; + return null; + } + + returnValue = member; + } + + members.Add(member); + orders.Add(slot.Order); + } + + if (members.Count == 0) + { + error = $"{model} has no member to read an output parameter into, so ExecuteOutputAsync<{model}>() has nothing to match. " + + "Give it a public settable property or a constructor parameter for each output parameter (members with [NotMapped] do not count)."; + return null; + } + + // A member that declares its ordinal ([Column(Order = n)]) gets that cell, the others the first free ones in order; a gap gets no label. + int width = members.Count; + foreach (int order in orders) width = Math.Max(width, order + 1); + string[] labels = new string[width]; + int[] cells = new int[members.Count]; + for (int i = 0; i < members.Count; i++) + { + if (orders[i] < 0) continue; + + cells[i] = orders[i]; + labels[orders[i]] = members[i].Label; + } + + int free = 0; + for (int i = 0; i < members.Count; i++) + { + if (orders[i] >= 0) continue; + + while (labels[free] is not null) free++; + cells[i] = free; + labels[free] = members[i].Label; + } + + return new OutputLayout(model, members.ToImmutable(), cells, ImmutableArray.Create(labels)); + } + + static OutputMember? Member(Slot slot, string model, ref string? error) + { + string label = slot.ColumnName ?? slot.Name; + string display = $"{model}.{slot.Name}"; + if (slot.ColumnName is null && slot.Name.Equals(OutputLayout.ReturnValue, StringComparison.OrdinalIgnoreCase)) + { + if (ReturnCode.Holds(slot.Type)) return new OutputMember(label, display); + + error = $"{display} reads the return code, which is one integer, so {Shape.TypeName(slot.Type)} cannot hold it. Change {display} to int (or int?, long, an enum)."; + return null; + } + + string? typeName = TypeName(slot); + OutputWire? wire = OutputWire.Of(slot.Type, typeName, out OutputWireError reason); + if (wire is not null) + return new OutputMember(label, exact: slot.ColumnName is not null, label, wire, display); + + error = reason switch + { + OutputWireError.DecimalUndeclared + => $"{display} is a decimal output without a declared precision and scale, so the provider would round its value to a whole number. " + + $"Add [Column(TypeName = \"decimal(p,s)\")] to {display} with the parameter's declared type, such as decimal(18,2) (on a positional record, [property: Column(...)]).", + OutputWireError.DecimalBadTypeName + => $"{display} declares [Column(TypeName = \"{typeName}\")], which is not decimal(p,s) or numeric(p,s) with a precision from 1 to 38 and a scale from 0 to the precision. " + + "Change it to the parameter's declared type, such as decimal(18,2).", + _ + => $"{display} is {Shape.TypeName(slot.Type)}, which has no database type, so it cannot be sent as an output parameter. " + + $"Change {display} to a type that has one, {OutputWire.SupportedTypes}.", + }; + + return null; + } + + // Read by full name, as RowMap reads [Column]: a consumer's own copy of the attribute counts. A positional record declares it with [property: Column(...)]. + /// + /// Returns the TypeName the member's property declares with [Column], or . + /// + /// The member. + /// The declared type name, or . + static string? TypeName(Slot slot) + { + if (!slot.IsProperty) return null; + + // The first property of the name, as the slots take it. + foreach (PropertyInfo property in typeof(TOut).GetProperties(BindingFlags.Public | BindingFlags.Instance)) + { + if (property.Name != slot.Name) continue; + + foreach (CustomAttributeData attribute in CustomAttributeData.GetCustomAttributes(property)) + { + if (attribute.AttributeType.FullName != "System.ComponentModel.DataAnnotations.Schema.ColumnAttribute") continue; + + foreach (CustomAttributeNamedArgument named in attribute.NamedArguments) + { + if (named.MemberName == "TypeName" && named.TypedValue.Value is string typeName) return typeName; + } + } + + return null; + } + + return null; + } +} + +/// +/// Why a type cannot be read by the named form. +/// +enum OutputValueRefusal +{ + /// It can. + None, + + /// The type is a model, not a single value. + NotScalar, + + /// A decimal, whose precision and scale the named form cannot declare. + Decimal, + + /// The type has no database type. + NoDbType, +} + +/// +/// How the one value of the named form is sent, per type, worked out once. +/// +/// The type of the value. +static class OutputValue +{ + static readonly OutputWire? Wire = Build(out Reason); + + static readonly OutputValueRefusal Reason; + + /// + /// Gets the layout of one call of the named form. + /// + /// The parameter's name. + /// The layout. + /// cannot be read as one output parameter. + public static OutputLayout Get(string name) + { + string display = $"The output parameter '{name}'"; + OutputWire wire = Wire ?? throw new InvalidOperationException(Message(name, display)); + return new(new OutputMember(name, exact: true, name, wire, display)); + } + + /// + /// Throws unless is a or a of it: only a decimal takes a precision and scale. + /// + /// The parameter's name. + /// is not a . + public static void ThrowUnlessDecimal(string name) + { + if (Reason == OutputValueRefusal.Decimal) return; + + string shown = Shape.TypeName(typeof(T)); + throw new InvalidOperationException( + $"Only a decimal output takes a precision and scale; {shown} needs none (date and time outputs keep full precision). " + + $"Use ExecuteOutputAsync<{shown}>(\"{name}\")."); + } + + /// + /// Gets the layout of one call of the named form with a precision and scale: a decimal of that precision and scale. + /// + /// The parameter's name. + /// The precision, checked by the caller. + /// The scale, checked by the caller. + /// The layout. + /// is not a . + public static OutputLayout Shaped(string name, byte precision, byte scale) + { + ThrowUnlessDecimal(name); + string display = $"The output parameter '{name}'"; + return new(new OutputMember(name, exact: true, name, new OutputWire(DbType.Decimal, 0, precision, scale), display)); + } + + static string Message(string name, string display) + { + string shown = Shape.TypeName(typeof(T)); + return Reason switch + { + OutputValueRefusal.NotScalar + => $"ExecuteOutputAsync<{shown}>(\"{name}\") reads one value, but {shown} is a model, not a single value. " + + $"Call ExecuteOutputAsync<{shown}>() without a name to read its members, or read '{name}' as a single-value type {OutputWire.SupportedTypes}.", + OutputValueRefusal.Decimal + => $"{display} is read as {shown}. A decimal output needs its precision and scale, or the server rounds it to a whole number. " + + $"Use ExecuteOutputAsync(\"{name}\", 19, 4) or ExecuteOutputDecimalAsync(\"{name}\", 19, 4) with the column's precision and scale.", + _ + => $"{display} is read as {shown}, which has no database type, so it cannot be sent as an output parameter. " + + $"Read it as a type that has one, {OutputWire.SupportedTypes}.", + }; + } + + static OutputWire? Build(out OutputValueRefusal reason) + { + Type type = typeof(T); + if (!Shape.IsScalar(type)) + { + reason = OutputValueRefusal.NotScalar; + return null; + } + + if ((Nullable.GetUnderlyingType(type) ?? type) == typeof(decimal)) + { + reason = OutputValueRefusal.Decimal; + return null; + } + + OutputWire? wire = OutputWire.Of(type, null, out OutputWireError error); + reason = error == OutputWireError.None ? OutputValueRefusal.None : OutputValueRefusal.NoDbType; + return wire; + } +} + +/// +/// One call that reads output parameters: what it reads, the names they resolved to, and the parameters made for them. +/// +/// +/// It belongs to the one call that made it and is passed along as that call's state, never kept on the command: +/// one command may run on several threads at once. +/// +/// What the call reads. +sealed class OutputRun(OutputLayout layout) +{ + /// What the call reads. + public readonly OutputLayout Layout = layout; + + /// The token that governs the call. + public CancellationToken Token; + + /// The command, for the messages: a procedure's name, or "the command text"; set while the call is built. + public string? Where; + + /// The parameter each member resolved to ( for the return code), set while the call is built. + public string?[]? Names; + + /// The parameter of each member on the provider's command, set while the call is built. + public IDbDataParameter?[]? Parameters; + + /// Whether each member's parameter is pure output (no value sent), so a means it never arrived. + public bool[]? Pure; + + /// + /// Gets the value of a member once the response is complete. + /// + /// The member. + /// The value: for NULL. + /// The value never arrived. + public object? Value(int index) + { + object? value = Parameters![index]!.Value; + if (value is null && Pure![index]) + { + OutputMember member = Layout.Members[index]; + string which = member.IsReturnValue ? "the return code was" : $"the output parameter '{Names![index]}' was"; + throw new InvalidOperationException( + $"{member.Display} has no value after {Where} ran: {which} not delivered, because the response did not complete (as when a statement after the outputs are set fails). Nothing is read as NULL. " + + "Read the results to the end without stopping early, check the procedure for an error raised after its result sets, and treat the call as possibly committed."); + } + + return value; + } + + /// + /// Builds the model from the values, once the response is complete. + /// + /// The model type. + /// The model. + /// The values never arrived. + /// A value does not convert to its member. + public TOut Map() + { + // The values are copied out, so nothing of the provider's command is kept. + var row = new object?[Layout.Labels.Length]; + for (int i = 0; i < Layout.Members.Length; i++) row[Layout.Cells[i]] = Value(i); + return RowMap.Default.ArrayMapper(Layout.Labels)(row); + } + + /// + /// Converts the one value of the named form, once the response is complete. + /// + /// The type of the value. + /// The value. + /// The value never arrived. + /// The value does not convert to , or it is NULL and is a non-nullable value type. + public T Single() => RowMap.ConvertScalar(Value(0)); +} + +/// +/// Whether a type can hold a return code, worked out once per type. +/// +/// The type. +static class ReturnCode +{ + static readonly bool IsScalar = Holds(typeof(T)); + + /// + /// Whether a type can hold the return code: a single value, or . + /// + /// The type. + /// when it can. + public static bool Holds(Type type) + => type == typeof(object) || Shape.IsScalar(type); + + /// + /// Throws when is a model, which cannot hold the return code. + /// + /// is not a single value. + public static void ThrowUnlessScalar() + { + if (IsScalar) return; + + throw new InvalidOperationException(Message(Shape.TypeName(typeof(T)))); + } + + /// + /// Says that a type cannot hold the return code, and what can. + /// + /// The type, or the member, as the message names it. + /// The message. + public static string Message(string shown) + => $"The return code is one integer, so {shown} cannot hold it. Use int (or int?, long, an enum), or a ReturnValue member on the output model."; +} diff --git a/Source/Core/ParameterNames.cs b/Source/Core/ParameterNames.cs index 0ca6569f..6ad133fc 100644 --- a/Source/Core/ParameterNames.cs +++ b/Source/Core/ParameterNames.cs @@ -303,10 +303,21 @@ static bool ClosesAt(string s, int open, int close) /// The real name as the provider reported it, or when no candidate matches any parameter. /// One candidate matches more than one parameter at the same tier. internal static string? MatchBare(ImmutableArray candidates, ImmutableArray parameterNames, ImmutableArray bareNames, string expression, string procedure) + => MatchBareAs(candidates, parameterNames, bareNames, expression, procedure, null, null); + + /// + /// The candidates from . + /// The real names as the provider reports them (a leading @ is allowed). + /// The same names without a leading @. + /// 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. + /// The fix, for the message of an ambiguity; for AddParam("name", value). + internal static string? MatchBareAs(ImmutableArray candidates, ImmutableArray parameterNames, ImmutableArray bareNames, string expression, string procedure, string? subject, string? fix) { foreach (string candidate in candidates) { - if (Find(expression, procedure, candidate, parameterNames, bareNames) is { } found) return found; + if (Find(expression, procedure, candidate, parameterNames, bareNames, subject, fix) is { } found) return found; } return null; @@ -326,7 +337,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) + static string? Find(string expression, string procedure, string candidate, ImmutableArray parameterNames, ImmutableArray bareNames, string? subject, string? fix) { // 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++) @@ -339,9 +350,9 @@ static bool ClosesAt(string s, int open, int close) if (found is not null) { throw new InvalidOperationException( - $"The argument '{expression}' matches both '{found}' and '{real}' of '{procedure}'. " + $"{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)}. Name the parameter explicitly: AddParam(\"name\", value)."); + + $"The procedure declares: {string.Join(", ", parameterNames)}. {fix ?? "Name the parameter explicitly: AddParam(\"name\", value)."}"); } found = real; diff --git a/Source/Core/PublicAPI.Unshipped.txt b/Source/Core/PublicAPI.Unshipped.txt index e29ac7e7..af63ca7f 100644 --- a/Source/Core/PublicAPI.Unshipped.txt +++ b/Source/Core/PublicAPI.Unshipped.txt @@ -70,3 +70,7 @@ Open.Database.Extensions.ExpressiveCommandBase.Param.Direction.get -> System.Data.ParameterDirection *REMOVED*Open.Database.Extensions.ExpressiveCommandBase.Param.Param(string! name, object? value, TDbType? type = null, System.Data.ParameterDirection direction = System.Data.ParameterDirection.Input) -> void Open.Database.Extensions.ExpressiveCommandBase.Param.Param(string! name, object? value, TDbType? type = null) -> void +Open.Database.Extensions.ExpressiveCommandBase.ExecuteOutputAsync(string! name, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +Open.Database.Extensions.ExpressiveCommandBase.ExecuteOutputAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +Open.Database.Extensions.ExpressiveCommandBase.ExecuteOutputAsync(string! name, byte precision, byte scale, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +Open.Database.Extensions.ExpressiveCommandBase.ExecuteOutputDecimalAsync(string! name, byte precision, byte scale, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask diff --git a/Source/Generator/README.md b/Source/Generator/README.md index 98275910..548a7277 100644 --- a/Source/Generator/README.md +++ b/Source/Generator/README.md @@ -78,6 +78,7 @@ a `ref struct` property that can be set or a `ref struct` constructor parameter, a file-local or extern-alias type, a constructor with an `OverloadResolutionPriority`, a `DataTable` receiver, a call written `x?.Map()`, and a call inside a generic method (`Map()` with an open `T`). A `dynamic` member is read as an `object` member. A model with a `char` member is not intercepted. A model that declares a NULL policy is not intercepted either, so the policy is never silently ignored: `NullPolicy` on the type or a base type, `NullPolicy` or `NullValue` on a property or on a constructor or positional record parameter. +Only `Map()` call sites are intercepted, so the output model of `ExecuteOutputAsync()` (output parameters read into a model, one record per call) always uses the runtime map. A partial model (it or a base type declared `partial`) is checked once, when first read, against the built type: if another source generator added constructors or settable properties that this one could not see, the runtime map reads that model. The check uses reflection on the built type, diff --git a/Tests/Open.Database.Extensions.Core.Tests/OutputParameterLocalDbTests.cs b/Tests/Open.Database.Extensions.Core.Tests/OutputParameterLocalDbTests.cs new file mode 100644 index 00000000..1dc5ace6 --- /dev/null +++ b/Tests/Open.Database.Extensions.Core.Tests/OutputParameterLocalDbTests.cs @@ -0,0 +1,602 @@ +using Microsoft.Data.SqlClient; +using System.ComponentModel.DataAnnotations.Schema; + +#nullable enable + +namespace Open.Database.Extensions.Tests; + +// ExecuteOutputAsync() and its named form against SQL Server: one test per fact the design rests on (sizes, decimal scale, +// datetime2, NULLs, the lost default, the return code, names known and forgotten, a text's markers, a later statement's error). +// Skipped without LocalDB (see LocalDbFixture). +[ExcludeFromCodeCoverage] +[Collection("LocalDB DDL")] +public static class OutputParameterLocalDbTests +{ + static CancellationToken Token => TestContext.Current.CancellationToken; + + public sealed record PostTexts(string Title, string Body, byte[] Thumbnail); + + public sealed record PostTitle(string Title); + + public sealed record OrderTotals( + [property: Column(TypeName = "decimal(10,2)")] decimal Total, + [property: Column(TypeName = "decimal(10,2)")] decimal Echo); + + public sealed record PostTimes(DateTime CreatedUtc, DateTime First); + + public sealed record PostCounts(int? A, int? B); + + public sealed record StrictCounts(int A, int? B); + + public sealed record PostViews(int? Views); + + public sealed record Touched(int Count, int ReturnValue); + + public sealed record ReturnOnly(int ReturnValue); + + public sealed record Declared([property: Column("return_value")] int Value); + + public sealed record NewPostId(int PostId); + + public sealed record Cursor(long Position); + + public sealed record Twice(int Total, [property: Column("total")] int Sum); + + public sealed record Missing(int Absent); + + public sealed record Elsewhere([property: Column("@sum")] int Total); + + public sealed record Counted(int PostCount); + + static LocalDbFixture.Scratch Procedure(string parameters, string body) + => LocalDbFixture.CreateProcedureWithBody(parameters, "set nocount on; " + body, "ode_out"); + + static async Task OpenAsync() + { + SqlConnection connection = LocalDbFixture.Create(); + await connection.OpenAsync(Token); + return connection; + } + + // Size -1 returns each declared size whole (a size inferred from a value cuts silently, P4). + [Fact] + public static async Task StringsAndBinary_ComeBackWhole() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = Procedure( + "@title nvarchar(50) output, @body varchar(max) output, @thumbnail varbinary(8) output", + "set @title = replicate(N'x', 60); set @body = replicate(convert(varchar(max), 'y'), 9000); set @thumbnail = 0x0102030405060708090A;"); + await using SqlConnection connection = await OpenAsync(); + + PostTexts texts = await connection + .StoredProcedure("dbo." + procedure.Name) + .ExecuteOutputAsync(Token); + + Assert.Equal(50, texts.Title.Length); + Assert.Equal(9000, texts.Body.Length); + Assert.Equal(8, texts.Thumbnail.Length); + } + + [Fact] + public static async Task AnInputOutputString_IsNotCutToTheValueSent() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = Procedure( + "@title nvarchar(50) output", + "set @title = @title + replicate(N'z', 20);"); + await using SqlConnection connection = await OpenAsync(); + + PostTitle title = await connection + .StoredProcedure("dbo." + procedure.Name) + .AddParam("title", "abc") + .ExecuteOutputAsync(Token); + + Assert.Equal(23, title.Title.Length); + } + + // The declared precision and scale are sent (without them the value rounds to a whole number, P5), and the scale also rounds + // a value sent in (P14b): 1.239 arrives as 1.24. + [Fact] + public static async Task ADecimal_TakesItsTypeName_OutputAndInputOutput() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = Procedure( + "@total decimal(10,2) output, @echo decimal(10,3) output", + "set @total = 1234.56;"); + await using SqlConnection connection = await OpenAsync(); + + OrderTotals totals = await connection + .StoredProcedure("dbo." + procedure.Name) + .AddParam("echo", 1.239m) + .ExecuteOutputAsync(Token); + + Assert.Equal(1234.56m, totals.Total); + Assert.Equal(1.24m, totals.Echo); + } + + // DbType.DateTime would cut to three decimals and fail before 1753 (P14a): DateTime is sent as DateTime2. + [Fact] + public static async Task ADateTime_IsExact_InADatetime2_IncludingYearOne() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = Procedure( + "@created_utc datetime2(7) output, @first datetime2(7) output", + "set @created_utc = '2026-12-01T12:34:56.1234567'; set @first = '0001-01-01T00:00:00.0000001';"); + await using SqlConnection connection = await OpenAsync(); + + PostTimes times = await connection + .StoredProcedure("dbo." + procedure.Name) + .ExecuteOutputAsync(Token); + + Assert.Equal(new DateTime(2026, 12, 1, 12, 34, 56).AddTicks(1234567), times.CreatedUtc); + Assert.Equal(new DateTime(1, 1, 1).AddTicks(1), times.First); + } + + [Fact] + public static async Task Null_IsNullInANullableMember_AndAnErrorInANonNullableOne() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = Procedure("@a int output, @b int output", "set @a = null;"); + await using SqlConnection connection = await OpenAsync(); + + Assert.Equal(new PostCounts(null, null), await connection.StoredProcedure("dbo." + procedure.Name).ExecuteOutputAsync(Token)); + await Assert.ThrowsAsync(async () => await connection.StoredProcedure("dbo." + procedure.Name).ExecuteOutputAsync(Token)); + } + + // An Output parameter sends NULL in, so the procedure's default is not used (P8): documented. + [Fact] + public static async Task AnOutput_LosesTheProceduresDefault() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = Procedure("@views int = 10 output", "set @views = @views + 1;"); + await using SqlConnection connection = await OpenAsync(); + + Assert.Null((await connection.StoredProcedure("dbo." + procedure.Name).ExecuteOutputAsync(Token)).Views); + } + + [Fact] + public static async Task AReturnValueMember_ReadsTheReturnCode() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = Procedure("@count int output", "set @count = 4; return 3;"); + await using SqlConnection connection = await OpenAsync(); + + Assert.Equal(new Touched(4, 3), await connection.StoredProcedure("dbo." + procedure.Name).ExecuteOutputAsync(Token)); + } + + // When the names are known, a declared parameter that a ReturnValue member would also match throws: no silent hijack. + [Fact] + public static async Task ADeclaredReturnValue_AndAReturnValueMember_Throw_AndColumnReadsTheParameter() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = Procedure("@return_value int output", "set @return_value = 9; return 3;"); + await using SqlConnection connection = await OpenAsync(); + + var ex = await Assert.ThrowsAsync(async () => await connection.StoredProcedure("dbo." + procedure.Name).ExecuteOutputAsync(Token)); + Assert.Contains("ReturnOnly.ReturnValue reads the return code, but dbo.", ex.Message); + Assert.Contains("[Column(\"@return_value\")]", ex.Message); + Assert.Equal(9, (await connection.StoredProcedure("dbo." + procedure.Name).ExecuteOutputAsync(Token)).Value); + } + + // A later statement's error: SqlClient reports it through the execute call itself (ExecuteNonQuery reads the whole response), + // so the call throws the provider's error rather than the not-delivered one (which the fake-provider test covers). + [Fact] + public static async Task ALaterStatementsError_IsTheProvidersError() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = Procedure("@views int output", "set @views = 7; select convert(int, 'x');"); + await using SqlConnection connection = await OpenAsync(); + + var ex = await Assert.ThrowsAsync(async () => await connection.StoredProcedure("dbo." + procedure.Name).ExecuteOutputAsync(Token)); + Assert.Equal(245, ex.Number); + } + + // An output member on an input-only parameter is the provider's error (8162, P14e), and the kept names are forgotten: + // the next call reads them again and finds the renamed parameter. + [Fact] + public static async Task AnOutputOnAnInputOnlyParameter_IsTheProvidersError_AndTheNamesAreForgotten() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = Procedure("@post_id int", "select 1;"); + await using SqlConnection connection = await OpenAsync(); + string name = "dbo." + procedure.Name; + + var ex = await Assert.ThrowsAsync(async () => await connection.StoredProcedure(name).ExecuteOutputAsync(Token)); + Assert.Equal(8162, ex.Number); + + LocalDbFixture.Execute($"alter procedure dbo.[{procedure.Name}] @p_post_id int output as set @p_post_id = 5"); + Assert.Equal(5, (await connection.StoredProcedure(name).ExecuteOutputAsync(Token)).PostId); + } + + // A text command's @name OUTPUT marker works (P14f). + [Fact] + public static async Task ATextCommand_ReadsAnOutputMarker() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = Procedure("@post_id int, @views int output", "set @views = @post_id + 1;"); + await using SqlConnection connection = await OpenAsync(); + const int postId = 5; + + PostViews views = await connection + .Command($"exec dbo.[{procedure.Name}] @post_id, @views output") + .AddParam(postId) + .ExecuteOutputAsync(Token); + + Assert.Equal(6, views.Views); + } + + [Fact] + public static async Task AnInputOutput_ReadsBackTheValueTheProcedureSet() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = Procedure("@position bigint output", "set @position = @position + 10;"); + await using SqlConnection connection = await OpenAsync(); + const long position = 5; + + Assert.Equal(15, (await connection.StoredProcedure("dbo." + procedure.Name).AddParam("@position", 5L).ExecuteOutputAsync(Token)).Position); + Assert.Equal(15, (await connection.StoredProcedure("dbo." + procedure.Name).AddParam(position).ExecuteOutputAsync(Token)).Position); + Assert.Equal(15, await connection.StoredProcedure("dbo." + procedure.Name).AddParam("position", 5L).ExecuteOutputAsync("position", Token)); + } + + [Fact] + public static async Task WhenTheNamesAreKnown_NoMatchAndTwoMembersOnOneParameter_ThrowBeforeTheRun() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = Procedure("@total int output", "set @total = 1;"); + await using SqlConnection connection = await OpenAsync(); + + var none = await Assert.ThrowsAsync(async () => await connection.StoredProcedure("dbo." + procedure.Name).ExecuteOutputAsync(Token)); + Assert.Contains("Missing.Absent has no matching parameter on dbo.", none.Message); + Assert.Contains("it declares: @total", none.Message); + Assert.Contains("Add a parameter named Absent", none.Message); + + var twice = await Assert.ThrowsAsync(async () => await connection.StoredProcedure("dbo." + procedure.Name).ExecuteOutputAsync(Token)); + Assert.Contains("Twice.Total and Twice.Sum both resolve to the output parameter '@total'", twice.Message); + + var column = await Assert.ThrowsAsync(async () => await connection.StoredProcedure("dbo." + procedure.Name).ExecuteOutputAsync(Token)); + Assert.Contains("Elsewhere.Total names its parameter '@sum' with [Column], but dbo.", column.Message); + Assert.Contains("Change the [Column] name to one it declares", column.Message); + + using LocalDbFixture.Scratch two = Procedure("@post_count int output, @postcount_ int output", "set @post_count = 1;"); + var ambiguous = await Assert.ThrowsAsync(async () => await connection.StoredProcedure("dbo." + two.Name).ExecuteOutputAsync(Token)); + Assert.Contains("Counted.PostCount matches both", ambiguous.Message); + 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. + [Fact] + public static async Task TheNamedForm_MatchesTheNameExactly() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = Procedure( + "@post_id int = null output, @ReturnValue int = null output", + "set @post_id = 7; set @ReturnValue = 9; return 3;"); + await using SqlConnection connection = await OpenAsync(); + string name = "dbo." + procedure.Name; + + 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.Contains("Pass one of those names to ExecuteOutputAsync(name)", ex.Message); + } + + // ---- the owner's matrix: each type as a model member and as a named value; return only; failures ---------------- + + public enum PostStatus + { + Draft, + Published = 2, + } + + public sealed record PostRow( + int Id, + string Title, + [property: Column(TypeName = "decimal(10,2)")] decimal Total, + DateTime CreatedUtc, + Guid Key, + byte[] Thumbnail, + PostStatus Status, + int? IdN, + [property: Column(TypeName = "decimal(10,2)")] decimal? TotalN, + DateTime? CreatedUtcN, + Guid? KeyN, + PostStatus? StatusN); + + public sealed record PostRowNullable( + int? Id, + string? Title, + [property: Column(TypeName = "decimal(10,2)")] decimal? Total, + DateTime? CreatedUtc, + Guid? Key, + byte[]? Thumbnail, + PostStatus? Status); + + static readonly Guid PostKey = new("6f9619ff-8b86-d011-b42d-00c04fc964ff"); + + static readonly DateTime Created = new DateTime(2026, 12, 1, 12, 34, 56).AddTicks(1234567); + + static readonly DateTime YearOne = new DateTime(1, 1, 1).AddTicks(1); + + // Every output has a default (= null), so the named form can read one and leave the rest; @nulls = 1 leaves them all NULL. + static LocalDbFixture.Scratch EveryType() + => Procedure( + "@nulls bit = 0, @id int = null output, @title nvarchar(100) = null output, @total decimal(10,2) = null output," + + " @created_utc datetime2(7) = null output, @key uniqueidentifier = null output, @thumbnail varbinary(max) = null output," + + " @status int = null output, @id_n int = null output, @total_n decimal(10,2) = null output," + + " @created_utc_n datetime2(7) = null output, @key_n uniqueidentifier = null output, @status_n int = null output", + "if @nulls = 1 return 0;" + + " set @id = 7; set @title = N'Hello'; set @total = 1234.56; set @created_utc = '2026-12-01T12:34:56.1234567';" + + " set @key = '6f9619ff-8b86-d011-b42d-00c04fc964ff'; set @thumbnail = 0x010203; set @status = 2;" + + " set @id_n = 8; set @total_n = 0.5; set @created_utc_n = '0001-01-01T00:00:00.0000001'; set @key_n = @key; set @status_n = 2;"); + + // (1) Outputs only, into a model: int, string, decimal, DateTime, Guid, byte[], an enum, and the nullable form of each value type. + [Fact] + public static async Task EachType_AsAModelMember_IsRead() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = EveryType(); + await using SqlConnection connection = await OpenAsync(); + + PostRow row = await connection + .StoredProcedure("dbo." + procedure.Name) + .ExecuteOutputAsync(Token); + + Assert.Equal((7, "Hello", 1234.56m, Created, PostKey), (row.Id, row.Title, row.Total, row.CreatedUtc, row.Key)); + Assert.Equal([1, 2, 3], row.Thumbnail); + Assert.Equal(PostStatus.Published, row.Status); + Assert.Equal((8, 0.5m, YearOne, PostKey, PostStatus.Published), (row.IdN, row.TotalN, row.CreatedUtcN, row.KeyN, row.StatusN)); + } + + // (1) Outputs only, one value by name: each type, and the nullable form of each value type. + // ExecuteOutputAsync(name) throws (see TheDecimalForm_ReadsADecimal_ByItsPrecisionAndScale). + [Fact] + public static async Task EachType_AsANamedValue_IsRead_ADecimalByItsPrecisionAndScale() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = EveryType(); + await using SqlConnection connection = await OpenAsync(); + string name = "dbo." + procedure.Name; + + Assert.Equal(7, await connection.StoredProcedure(name).ExecuteOutputAsync("id", Token)); + Assert.Equal("Hello", await connection.StoredProcedure(name).ExecuteOutputAsync("title", Token)); + Assert.Equal(Created, await connection.StoredProcedure(name).ExecuteOutputAsync("created_utc", Token)); + Assert.Equal(PostKey, await connection.StoredProcedure(name).ExecuteOutputAsync("key", Token)); + Assert.Equal([1, 2, 3], await connection.StoredProcedure(name).ExecuteOutputAsync("thumbnail", Token)); + Assert.Equal(PostStatus.Published, await connection.StoredProcedure(name).ExecuteOutputAsync("status", Token)); + Assert.Equal(8, await connection.StoredProcedure(name).ExecuteOutputAsync("id_n", Token)); + Assert.Equal(YearOne, await connection.StoredProcedure(name).ExecuteOutputAsync("created_utc_n", Token)); + Assert.Equal(PostKey, await connection.StoredProcedure(name).ExecuteOutputAsync("key_n", Token)); + Assert.Equal(PostStatus.Published, await connection.StoredProcedure(name).ExecuteOutputAsync("status_n", Token)); + Assert.Equal(1234.56m, await connection.StoredProcedure(name).ExecuteOutputAsync("total", 10, 2, Token)); + Assert.Equal(0.5m, await connection.StoredProcedure(name).ExecuteOutputDecimalAsync("total_n", 10, 2, Token)); + + var ex = Assert.Throws(() => connection.StoredProcedure(name).ExecuteOutputAsync("total", Token)); + Assert.Contains("The output parameter 'total' is read as Decimal", ex.Message); + Assert.Contains("A decimal output needs its precision and scale, or the server rounds it to a whole number. Use ExecuteOutputAsync(\"total\", 19, 4) or ExecuteOutputDecimalAsync(\"total\", 19, 4)", ex.Message); + Assert.Throws(() => connection.StoredProcedure(name).ExecuteOutputAsync("total_n", Token)); + } + + // (5) NULL outputs: each nullable member and named value is null; each non-nullable value type throws ValueMappingException. + [Fact] + public static async Task NullOutputs_AreNullWhereNullable_AndAnErrorWhereNot() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = EveryType(); + await using SqlConnection connection = await OpenAsync(); + string name = "dbo." + procedure.Name; + + PostRowNullable row = await connection.StoredProcedure(name).AddParam("nulls", true).ExecuteOutputAsync(Token); + Assert.Equal(new PostRowNullable(null, null, null, null, null, null, null), row); + await Assert.ThrowsAsync(async () => await connection.StoredProcedure(name).AddParam("nulls", true).ExecuteOutputAsync(Token)); + + Assert.Null(await connection.StoredProcedure(name).AddParam("nulls", true).ExecuteOutputAsync("id", Token)); + Assert.Null(await connection.StoredProcedure(name).AddParam("nulls", true).ExecuteOutputAsync("title", Token)); + Assert.Null(await connection.StoredProcedure(name).AddParam("nulls", true).ExecuteOutputAsync("created_utc", Token)); + Assert.Null(await connection.StoredProcedure(name).AddParam("nulls", true).ExecuteOutputAsync("key", Token)); + Assert.Null(await connection.StoredProcedure(name).AddParam("nulls", true).ExecuteOutputAsync("thumbnail", Token)); + Assert.Null(await connection.StoredProcedure(name).AddParam("nulls", true).ExecuteOutputAsync("status", Token)); + + await Assert.ThrowsAsync(async () => await connection.StoredProcedure(name).AddParam("nulls", true).ExecuteOutputAsync("id", Token)); + await Assert.ThrowsAsync(async () => await connection.StoredProcedure(name).AddParam("nulls", true).ExecuteOutputAsync("created_utc", Token)); + await Assert.ThrowsAsync(async () => await connection.StoredProcedure(name).AddParam("nulls", true).ExecuteOutputAsync("key", Token)); + await Assert.ThrowsAsync(async () => await connection.StoredProcedure(name).AddParam("nulls", true).ExecuteOutputAsync("status", Token)); + } + + // (2) Return only: ExecuteReturnAsync as int, int?, long and an int-based enum, and a model whose one member is ReturnValue. + [Fact] + public static async Task ReturnOnly_ReadsTheReturnCode_AsEachType_AndIntoAModel() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = Procedure("@count int = null output", "return 2;"); + await using SqlConnection connection = await OpenAsync(); + string name = "dbo." + procedure.Name; + + Assert.Equal(2, await connection.StoredProcedure(name).ExecuteReturnAsync(Token)); + Assert.Equal(2, await connection.StoredProcedure(name).ExecuteReturnAsync(Token)); + Assert.Equal(2L, await connection.StoredProcedure(name).ExecuteReturnAsync(Token)); + Assert.Equal(PostStatus.Published, await connection.StoredProcedure(name).ExecuteReturnAsync(Token)); + Assert.Equal(new ReturnOnly(2), await connection.StoredProcedure(name).ExecuteOutputAsync(Token)); + } + + // (5) Not delivered, on a real server: with FireInfoMessageEventOnUserErrors SqlClient does not throw a later statement's error, + // the batch ends before the outputs are sent, and the call throws instead of reading NULL. + [Fact] + public static async Task ALaterStatementsError_ThatTheProviderDoesNotThrow_IsNotDelivered() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = Procedure("@views int output", "set @views = 7; select convert(int, 'x');"); + await using SqlConnection connection = await OpenAsync(); + connection.FireInfoMessageEventOnUserErrors = true; + + var ex = await Assert.ThrowsAsync(async () => await connection.StoredProcedure("dbo." + procedure.Name).ExecuteOutputAsync(Token)); + Assert.Contains("PostViews.Views has no value after dbo.", ex.Message); + Assert.Contains("the output parameter '@views' was not delivered", ex.Message); + } + + // (5) A conversion failure in .NET: the caller typed the value as a string, the procedure returns text, the member is int. + [Fact] + public static async Task AConversionFailure_InDotNet_IsAValueMappingException() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = Procedure("@views nvarchar(10) output", "set @views = N'abc';"); + await using SqlConnection connection = await OpenAsync(); + string name = "dbo." + procedure.Name; + + await Assert.ThrowsAsync(async () => await connection.StoredProcedure(name).AddParam("views", "x", DbType.String).ExecuteOutputAsync(Token)); + await Assert.ThrowsAsync(async () => await connection.StoredProcedure(name).AddParam("views", "x", DbType.String).ExecuteOutputAsync("views", Token)); + } + + // (5) A conversion failure on the server (8114): a string sent to an int parameter. + [Fact] + public static async Task AConversionFailure_OnTheServer_IsTheProvidersError() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = Procedure("@views int output", "set @views = @views + 1;"); + await using SqlConnection connection = await OpenAsync(); + string name = "dbo." + procedure.Name; + + var ex = await Assert.ThrowsAsync(async () => await connection.StoredProcedure(name).AddParam("views", "abc", DbType.String).ExecuteOutputAsync(Token)); + Assert.Equal(8114, ex.Number); + ex = await Assert.ThrowsAsync(async () => await connection.StoredProcedure(name).AddParam("views", "abc", DbType.String).ExecuteOutputAsync("views", Token)); + Assert.Equal(8114, ex.Number); + } + + // (5) Canceled before: nothing runs. Canceled during: the server stops the procedure and the call is canceled. + [Fact] + public static async Task Cancel_BeforeAndDuring() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = Procedure("@views int = null output", "waitfor delay '00:00:05'; set @views = 1;"); + await using SqlConnection connection = await OpenAsync(); + string name = "dbo." + procedure.Name; + + using var before = new CancellationTokenSource(); + before.Cancel(); + Assert.Throws(() => connection.StoredProcedure(name).ExecuteOutputAsync(before.Token)); + Assert.Throws(() => connection.StoredProcedure(name).ExecuteOutputAsync("views", before.Token)); + + using var during = CancellationTokenSource.CreateLinkedTokenSource(Token); + during.CancelAfter(300); + var watch = System.Diagnostics.Stopwatch.StartNew(); + Exception? ex = await Record.ExceptionAsync(async () => await connection.StoredProcedure(name).ExecuteOutputAsync(during.Token)); + Assert.True(watch.Elapsed < TimeSpan.FromSeconds(4), $"Not canceled: {watch.Elapsed}."); + + // SqlClient reports a command canceled while it runs with its own error ("A severe error occurred on the current command"), not an + // OperationCanceledException; the call stops either way, and nothing is read. + Assert.True(ex is OperationCanceledException or SqlException, $"Expected a cancellation, got: {ex}"); + } + + // The decimal forms (owner Q9): ExecuteOutputAsync(name, precision, scale) and ExecuteOutputDecimalAsync keep 4 places of a + // decimal(19,4) (bound with int literals); NULL is null in decimal? and an error in decimal; an InputOutput takes a value in and reads + // the changed one; a precision or scale out of range, a shape on another type, and a decimal without a shape throw before the run. + [Fact] + public static async Task TheDecimalForms_ReadADecimal_ByItsPrecisionAndScale() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = Procedure( + "@nulls bit = 0, @total decimal(19,4) = null output", + "if @nulls = 0 set @total = isnull(@total * 2, 12.3456);"); + await using SqlConnection connection = await OpenAsync(); + string name = "dbo." + procedure.Name; + + decimal total = await connection.StoredProcedure(name).ExecuteOutputAsync("total", 19, 4, Token); + Assert.Equal((12.3456m, 4), (total, (int)total.Scale)); + decimal? same = await connection.StoredProcedure(name).ExecuteOutputDecimalAsync("total", 19, 4, Token); + Assert.Equal((12.3456m, 4), (same!.Value, (int)same.Value.Scale)); + + Assert.Null(await connection.StoredProcedure(name).AddParam("nulls", true).ExecuteOutputDecimalAsync("total", 19, 4, Token)); + Assert.Null(await connection.StoredProcedure(name).AddParam("nulls", true).ExecuteOutputAsync("total", 19, 4, Token)); + var nullDecimal = await Assert.ThrowsAsync(async () => await connection.StoredProcedure(name).AddParam("nulls", true).ExecuteOutputAsync("total", 19, 4, Token)); + Assert.Contains("The decimal output parameter 'total' is NULL, which a decimal cannot hold", nullDecimal.Message); + + Assert.Equal(3.0000m, await connection.StoredProcedure(name).AddParam("total", 1.5m).ExecuteOutputAsync("@total", 19, 4, Token)); + Assert.Equal(3.0000m, await connection.StoredProcedure(name).AddParam("total", 1.5m).ExecuteOutputDecimalAsync("@total", 19, 4, Token)); + + var range = Assert.Throws(() => connection.StoredProcedure(name).ExecuteOutputDecimalAsync("total", 4, 19, Token)); + Assert.Contains("The scale of the decimal output parameter 'total' is 19, more than its precision of 4", range.Message); + Assert.Throws(() => connection.StoredProcedure(name).ExecuteOutputAsync("total", 0, 0, Token)); + var other = Assert.Throws(() => connection.StoredProcedure(name).ExecuteOutputAsync("total", 19, 4, Token)); + Assert.Contains("Only a decimal output takes a precision and scale; Int32 needs none", other.Message); + Assert.Throws(() => connection.StoredProcedure(name).ExecuteOutputAsync("total", 19, 4, Token)); + + const string fix = "Use ExecuteOutputAsync(\"total\", 19, 4) or ExecuteOutputDecimalAsync(\"total\", 19, 4) with the column's precision and scale."; + Assert.Contains(fix, Assert.Throws(() => connection.StoredProcedure(name).ExecuteOutputAsync("total", Token)).Message); + Assert.Contains(fix, Assert.Throws(() => connection.StoredProcedure(name).ExecuteOutputAsync("total", Token)).Message); + } + + public sealed record PostClock(TimeSpan Span, DateTimeOffset At, DateTime Stamp); + + public sealed record PostDay(DateOnly Day); + + // Time types with no shape set read back exactly, with all 7 fraction digits, as model members and as named values. + // DateOnly has no database type for an output (ClrDbTypes gives none), so it is refused before the run (reported, not worked around). + [Fact] + public static async Task TimeTypes_WithNoShapeSet_ReadBackExactly() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = Procedure( + "@span time(7) = null output, @at datetimeoffset(7) = null output, @day date = null output, @stamp datetime2(7) = null output", + "set @span = '12:34:56.1234567'; set @at = '2026-12-01T12:34:56.1234567+02:00'; set @day = '2026-12-01'; set @stamp = '2026-12-01T12:34:56.1234567';"); + await using SqlConnection connection = await OpenAsync(); + string name = "dbo." + procedure.Name; + TimeSpan span = new TimeSpan(0, 12, 34, 56).Add(TimeSpan.FromTicks(1234567)); + var at = new DateTimeOffset(new DateTime(2026, 12, 1, 12, 34, 56).AddTicks(1234567), TimeSpan.FromHours(2)); + DateTime stamp = new DateTime(2026, 12, 1, 12, 34, 56).AddTicks(1234567); + + PostClock clock = await connection.StoredProcedure(name).ExecuteOutputAsync(Token); + Assert.Equal(span, clock.Span); + Assert.Equal((at, at.Offset), (clock.At, clock.At.Offset)); + Assert.Equal(stamp, clock.Stamp); + + Assert.Equal(span, await connection.StoredProcedure(name).ExecuteOutputAsync("span", Token)); + DateTimeOffset named = await connection.StoredProcedure(name).ExecuteOutputAsync("at", Token); + Assert.Equal((at, at.Offset), (named, named.Offset)); + Assert.Equal(stamp, await connection.StoredProcedure(name).ExecuteOutputAsync("stamp", Token)); + + var model = Assert.Throws(() => connection.StoredProcedure(name).ExecuteOutputAsync(Token)); + Assert.Contains("PostDay.Day is DateOnly, which has no database type", model.Message); + var single = Assert.Throws(() => connection.StoredProcedure(name).ExecuteOutputAsync("day", Token)); + Assert.Contains("The output parameter 'day' is read as DateOnly, which has no database type", single.Message); + } + + public sealed record PostMisc(long Views, bool Published, double Rating, string Code); + + // long, bool, double, and char(5) into a string (padded to 5), as model members and as named values. + [Fact] + public static async Task OtherTypes_ReadBackExactly_AndACharIsPadded() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = Procedure( + "@views bigint = null output, @published bit = null output, @rating float = null output, @code char(5) = null output", + "set @views = 9007199254740993; set @published = 1; set @rating = 0.1; set @code = 'ab';"); + await using SqlConnection connection = await OpenAsync(); + string name = "dbo." + procedure.Name; + + Assert.Equal(new PostMisc(9007199254740993L, true, 0.1, "ab "), await connection.StoredProcedure(name).ExecuteOutputAsync(Token)); + Assert.Equal(9007199254740993L, await connection.StoredProcedure(name).ExecuteOutputAsync("views", Token)); + Assert.True(await connection.StoredProcedure(name).ExecuteOutputAsync("published", Token)); + Assert.Equal(0.1, await connection.StoredProcedure(name).ExecuteOutputAsync("rating", Token)); + Assert.Equal("ab ", await connection.StoredProcedure(name).ExecuteOutputAsync("code", Token)); + } + + public sealed record PostLegacyTimes(DateTime Minute); + + // Legacy smalldatetime into DateTime, which is sent as datetime2: exact. A legacy datetime is not asserted: .997 reads back as + // .9966667 through datetime2 (reported to the owner, not worked around). + [Fact] + public static async Task ALegacySmallDateTime_ReadsBackExactly() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = Procedure( + "@minute smalldatetime = null output", + "set @minute = '2026-12-01T12:35:00';"); + await using SqlConnection connection = await OpenAsync(); + string name = "dbo." + procedure.Name; + var minute = new DateTime(2026, 12, 1, 12, 35, 0); + + Assert.Equal(minute, await connection.StoredProcedure(name).ExecuteOutputAsync("minute", Token)); + Assert.Equal(new PostLegacyTimes(minute), await connection.StoredProcedure(name).ExecuteOutputAsync(Token)); + } +} diff --git a/Tests/Open.Database.Extensions.Core.Tests/OutputParameterTests.cs b/Tests/Open.Database.Extensions.Core.Tests/OutputParameterTests.cs new file mode 100644 index 00000000..62c0602a --- /dev/null +++ b/Tests/Open.Database.Extensions.Core.Tests/OutputParameterTests.cs @@ -0,0 +1,565 @@ +using Open.Database.Extensions.Benchmarks; +using System.ComponentModel.DataAnnotations.Schema; +using System.Data.Common; + +#nullable enable + +namespace Open.Database.Extensions.Tests; + +// ExecuteOutputAsync() and its named form on a provider that records the parameters it is given and fills the outputs +// as the test says: how each parameter is sent, what merges, what throws before anything runs, and what never arrived. +// The names are not known here (the provider has no schema collection), so members go under their own names. +[ExcludeFromCodeCoverage] +public static class OutputParameterTests +{ + static CancellationToken Token => TestContext.Current.CancellationToken; + + // ---- the models -------------------------------------------------------------- + + public sealed record NewPost(int Id, DateTime CreatedUtc); + + public sealed record PostTexts(string Title, byte[] Thumbnail, char Grade); + + public sealed record OrderTotal([property: Column(TypeName = "decimal(10,2)")] decimal Total); + + public sealed record OrderTotalNumeric([property: Column(TypeName = " Numeric ( 18 , 4 ) ")] decimal? Total); + + public sealed record NoScale(decimal Total); + + public sealed record BadScale([property: Column(TypeName = "decimal(10,12)")] decimal Total); + + public sealed record Touched(int Count, int ReturnValue); + + public sealed record ModelReturn(NewPost ReturnValue); + + public sealed class TwoReturns + { + public int ReturnValue { get; set; } + + public int RETURNVALUE { get; set; } + } + + public sealed record Cursor(long Position); + + public sealed record Ordered([property: Column(Order = 2)] int Total, int Count); + + public sealed record Renamed([property: Column("@post_count")] int Count); + + public sealed record Twice(int Total, [property: Column("total")] int Sum); + + public sealed record WithDateOnly(DateOnly Day); + + public sealed record WithChars(char[] Code); + + public sealed class NoMembers + { + public int Id => 1; + } + + public sealed class NotMappedOnly + { + [NotMapped] + public int Id { get; set; } + + public int Count { get; set; } + } + + // ---- the provider ------------------------------------------------------------ + + // Hands out commands that record their parameters and, when executed, let the test fill the outputs. + sealed class OutputConnection(Action? onExecute = null) : DbConnection + { + public OutputCommand? Last { get; private set; } + + public int Executed { get; set; } + + [AllowNull] + public override string ConnectionString { get; set; } = "output"; + public override string Database => "output"; + public override string DataSource => "output"; + public override string ServerVersion => "1.0"; + public override ConnectionState State => ConnectionState.Open; + public override void ChangeDatabase(string databaseName) { } + public override void Close() { } + public override void Open() { } + protected override DbTransaction BeginDbTransaction(IsolationLevel isolationLevel) => throw new NotSupportedException(); + protected override DbCommand CreateDbCommand() => Last = new OutputCommand(this, onExecute); + } + + sealed class OutputCommand(OutputConnection connection, Action? onExecute) : DbCommand + { + readonly BenchParameterCollection _parameters = []; + + public IReadOnlyList All => [.. _parameters.Cast()]; + + public DbParameter Named(string name) => All.Single(p => p.ParameterName == name); + + [AllowNull] + public override string CommandText { get; set; } = ""; + public override int CommandTimeout { get; set; } + public override CommandType CommandType { get; set; } + public override bool DesignTimeVisible { get; set; } + public override UpdateRowSource UpdatedRowSource { get; set; } + protected override DbConnection? DbConnection { get => connection; set { } } + protected override DbParameterCollection DbParameterCollection => _parameters; + protected override DbTransaction? DbTransaction { get; set; } + public override void Cancel() { } + public override void Prepare() { } + public override object? ExecuteScalar() => throw new NotSupportedException(); + protected override DbParameter CreateDbParameter() => new OutputParameter(); + protected override DbDataReader ExecuteDbDataReader(CommandBehavior behavior) => throw new NotSupportedException(); + + public override int ExecuteNonQuery() + { + connection.Executed++; + onExecute?.Invoke(this); + return 1; + } + } + + // A parameter that keeps what it is given (DbParameter's own Precision and Scale keep nothing), Input by default as a provider's is. + sealed class OutputParameter : DbParameter + { + public override DbType DbType { get; set; } + public override ParameterDirection Direction { get; set; } = ParameterDirection.Input; + public override bool IsNullable { get; set; } + [AllowNull] + public override string ParameterName { get; set; } = ""; + public override int Size { get; set; } + public override byte Precision { get; set; } + public override byte Scale { get; set; } + [AllowNull] + public override string SourceColumn { get; set; } = ""; + public override bool SourceColumnNullMapping { get; set; } + public override object? Value { get; set; } + public override void ResetDbType() { } + } + + // Sets every output (and return-value) parameter from the values given by name; the return value under "". + static Action Fill(params (string Name, object? Value)[] values) + => command => + { + foreach (DbParameter p in command.All) + { + if (p.Direction == ParameterDirection.Input) continue; + + string key = p.Direction == ParameterDirection.ReturnValue ? "" : p.ParameterName; + foreach ((string name, object? value) in values) + { + if (name == key) p.Value = value; + } + } + }; + + // ---- how each parameter is sent ---------------------------------------------- + + [Fact] + public static async Task AnOutputOnlyCall_SendsEachMemberAsAnOutput_AndReadsTheModel() + { + var created = new DateTime(2026, 12, 1, 12, 34, 56).AddTicks(1234567); + var c = new OutputConnection(Fill(("Id", 7), ("CreatedUtc", created))); + + NewPost post = await c + .StoredProcedure("dbo.AddPost") + .ExecuteOutputAsync(Token); + + Assert.Equal(new NewPost(7, created), post); + OutputCommand command = c.Last!; + Assert.Equal(2, command.All.Count); + Assert.All(command.All, static p => Assert.Equal(ParameterDirection.Output, p.Direction)); + Assert.Equal(DbType.Int32, command.Named("Id").DbType); + + // A DateTime goes as DateTime2 (DateTime cuts a datetime2 to three decimals and fails before 1753). + Assert.Equal(DbType.DateTime2, command.Named("CreatedUtc").DbType); + } + + [Fact] + public static async Task StringsAndBinary_TakeSizeMinusOne_AndACharSizeOne() + { + var c = new OutputConnection(Fill(("Title", "t"), ("Thumbnail", new byte[] { 1, 2 }), ("Grade", "A"))); + + PostTexts texts = await c + .StoredProcedure("dbo.PostTexts") + .ExecuteOutputAsync(Token); + + Assert.Equal("t", texts.Title); + Assert.Equal([1, 2], texts.Thumbnail); + Assert.Equal('A', texts.Grade); + OutputCommand command = c.Last!; + Assert.Equal((DbType.String, -1), (command.Named("Title").DbType, command.Named("Title").Size)); + Assert.Equal((DbType.Binary, -1), (command.Named("Thumbnail").DbType, command.Named("Thumbnail").Size)); + Assert.Equal((DbType.StringFixedLength, 1), (command.Named("Grade").DbType, command.Named("Grade").Size)); + } + + [Fact] + public static async Task ADecimal_TakesThePrecisionAndScaleItsTypeNameDeclares() + { + var c = new OutputConnection(Fill(("Total", 1234.56m))); + + Assert.Equal(1234.56m, (await c.StoredProcedure("dbo.OrderTotal").ExecuteOutputAsync(Token)).Total); + DbParameter total = c.Last!.Named("Total"); + Assert.Equal((DbType.Decimal, (byte)10, (byte)2), (total.DbType, total.Precision, total.Scale)); + + Assert.Equal(1234.56m, (await c.StoredProcedure("dbo.OrderTotal").ExecuteOutputAsync(Token)).Total); + total = c.Last!.Named("Total"); + Assert.Equal(((byte)18, (byte)4), (total.Precision, total.Scale)); + } + + // ---- merging with an input ----------------------------------------------------- + + [Fact] + public static async Task AMemberWhoseParameterGotAValue_IsSentAsInputOutput_UnderTheNameAsWritten() + { + var c = new OutputConnection(command => + { + DbParameter p = command.Named("@position"); + p.Value = (long)p.Value! + 10; + }); + + Cursor cursor = await c + .StoredProcedure("dbo.Advance") + .AddParam("@position", 5L) + .ExecuteOutputAsync(Token); + + Assert.Equal(15, cursor.Position); + DbParameter position = Assert.Single(c.Last!.All); + Assert.Equal(ParameterDirection.InputOutput, position.Direction); + Assert.Equal(DbType.Int64, position.DbType); + } + + [Fact] + public static async Task AnInputOutput_KeepsTheTypeTheCallerGave() + { + var c = new OutputConnection(); + + await c + .StoredProcedure("dbo.Advance") + .AddParam("position", 5, DbType.Int32) + .ExecuteOutputAsync(Token); + + DbParameter position = Assert.Single(c.Last!.All); + Assert.Equal((ParameterDirection.InputOutput, DbType.Int32), (position.Direction, position.DbType)); + } + + [Fact] + public static async Task AnInputOutput_FromADerivedName_Merges() + { + var c = new OutputConnection(); + const long position = 5; + + Cursor cursor = await c + .StoredProcedure("dbo.Advance") + .AddParam(position) + .ExecuteOutputAsync(Token); + + // Never delivered, an InputOutput keeps the value sent: it cannot be told apart (documented). + Assert.Equal(5, cursor.Position); + Assert.Equal(ParameterDirection.InputOutput, Assert.Single(c.Last!.All).Direction); + } + + [Fact] + public static async Task AnInputOfAnotherName_StaysAnInput() + { + var c = new OutputConnection(Fill(("Position", 9L))); + + Cursor cursor = await c + .StoredProcedure("dbo.Advance") + .AddParam("step", 5) + .ExecuteOutputAsync(Token); + + Assert.Equal(9, cursor.Position); + Assert.Equal(ParameterDirection.Input, c.Last!.Named("step").Direction); + Assert.Equal(ParameterDirection.Output, c.Last!.Named("Position").Direction); + } + + // ---- names, order, the return code ------------------------------------------------- + + [Fact] + public static async Task AColumnName_IsTheParameterName() + { + var c = new OutputConnection(Fill(("@post_count", 3))); + + Assert.Equal(3, (await c.StoredProcedure("dbo.Count").ExecuteOutputAsync(Token)).Count); + Assert.Equal("@post_count", Assert.Single(c.Last!.All).ParameterName); + } + + [Fact] + public static async Task AMemberWithAnOrdinal_IsRead() + { + var c = new OutputConnection(Fill(("Total", 9), ("Count", 2))); + + Assert.Equal(new Ordered(9, 2), await c.StoredProcedure("dbo.Count").ExecuteOutputAsync(Token)); + } + + [Fact] + public static async Task AReturnValueMember_ReadsTheReturnCode() + { + var c = new OutputConnection(Fill(("Count", 4), ("", 3))); + + Assert.Equal(new Touched(4, 3), await c.StoredProcedure("dbo.Touch").ExecuteOutputAsync(Token)); + Assert.Contains(c.Last!.All, static p => p.Direction == ParameterDirection.ReturnValue); + } + + [Fact] + public static async Task TwoMembers_ThatResolveToOneParameter_Throw() + { + var c = new OutputConnection(); + + var ex = await Assert.ThrowsAsync(async () => await c.StoredProcedure("dbo.Count").ExecuteOutputAsync(Token)); + Assert.Contains("Twice.Total and Twice.Sum both resolve to the output parameter 'Total' of dbo.Count", ex.Message); + Assert.Contains("Name each member's parameter with [Column(\"name\")]", ex.Message); + Assert.Equal(0, c.Executed); + } + + // ---- not delivered --------------------------------------------------------------- + + // A pure Output that is still CLR null when the call returns never arrived (as when a later statement's error is swallowed + // while the response is read): never read as NULL. + [Fact] + public static async Task AnOutputThatNeverArrived_Throws_NeverReadsAsNull() + { + var c = new OutputConnection(); + + var ex = await Assert.ThrowsAsync(async () => await c.StoredProcedure("dbo.AddPost").ExecuteOutputAsync(Token)); + Assert.Contains("NewPost.Id has no value after dbo.AddPost ran: the output parameter 'Id' was not delivered", ex.Message); + Assert.Contains("Read the results to the end without stopping early, check the procedure for an error raised after its result sets, and treat the call as possibly committed.", ex.Message); + + ex = await Assert.ThrowsAsync(async () => await c.StoredProcedure("dbo.AddPost").ExecuteOutputAsync("Id", Token)); + Assert.Contains("The output parameter 'Id' has no value after dbo.AddPost ran", ex.Message); + + // A return code that never arrived is the same. + c = new OutputConnection(Fill(("Count", 4))); + ex = await Assert.ThrowsAsync(async () => await c.StoredProcedure("dbo.Touch").ExecuteOutputAsync(Token)); + Assert.Contains("Touched.ReturnValue has no value after dbo.Touch ran: the return code was not delivered", ex.Message); + + // On a text command the message names the command text. + c = new OutputConnection(); + ex = await Assert.ThrowsAsync(async () => await c.Command("set @Count = 1").ExecuteOutputAsync(Token)); + Assert.Contains("NotMappedOnly.Count has no value after the command text ran", ex.Message); + } + + [Fact] + public static async Task NullIsNull_InANullableMember_AndAnErrorInANonNullableOne() + { + var c = new OutputConnection(Fill(("Id", DBNull.Value), ("CreatedUtc", DateTime.MinValue))); + + await Assert.ThrowsAsync(async () => await c.StoredProcedure("dbo.AddPost").ExecuteOutputAsync(Token)); + Assert.Null(await c.StoredProcedure("dbo.AddPost").ExecuteOutputAsync("Id", Token)); + await Assert.ThrowsAsync(async () => await c.StoredProcedure("dbo.AddPost").ExecuteOutputAsync("Id", Token)); + } + + // ---- what throws before anything runs ---------------------------------------------- + + // Each message names the member, parameter or type, says what is wrong, and gives the fix: the phrases are asserted. + static void ThrowsAtTheCall(Func call, params string[] phrases) + where TException : Exception + { + var c = new OutputConnection(); + var ex = Assert.Throws(() => call(c)); + foreach (string phrase in phrases) Assert.Contains(phrase, ex.Message); + Assert.Null(c.Last); + } + + [Fact] + public static void AModelThatCannotBeRead_ThrowsAtTheCall() + { + ThrowsAtTheCall( + c => c.StoredProcedure("p").ExecuteOutputAsync(Token), + "NoScale.Total is a decimal output without a declared precision and scale", + "round its value to a whole number", + "Add [Column(TypeName = \"decimal(p,s)\")] to NoScale.Total"); + ThrowsAtTheCall( + c => c.StoredProcedure("p").ExecuteOutputAsync(Token), + "BadScale.Total declares [Column(TypeName = \"decimal(10,12)\")], which is not decimal(p,s)", + "Change it to the parameter's declared type"); + ThrowsAtTheCall( + c => c.StoredProcedure("p").ExecuteOutputAsync(Token), + "ExecuteOutputAsync() reads a model of output parameters, but Int32 is a single value", + "Call ExecuteOutputAsync(name)"); + ThrowsAtTheCall( + c => c.StoredProcedure("p").ExecuteOutputAsync(Token), + "String is a single value", + "Call ExecuteOutputAsync(name)"); + ThrowsAtTheCall( + c => c.StoredProcedure("p").ExecuteOutputAsync(Token), + "NoMembers has no member to read an output parameter into", + "Give it a public settable property or a constructor parameter"); + ThrowsAtTheCall( + c => c.StoredProcedure("p").ExecuteOutputAsync(Token), + "WithDateOnly.Day is DateOnly, which has no database type", + "Change WithDateOnly.Day to a type that has one"); + ThrowsAtTheCall( + c => c.StoredProcedure("p").ExecuteOutputAsync(Token), + "WithChars.Code is Char[], which has no database type"); + ThrowsAtTheCall( + c => c.StoredProcedure("p").ExecuteOutputAsync(Token), + "TwoReturns.ReturnValue and TwoReturns.RETURNVALUE both read the return code", + "Remove one, or give it [Column(\"name\")]"); + + // The error is kept: a second call throws the same. + ThrowsAtTheCall(c => c.StoredProcedure("p").ExecuteOutputAsync(Token), "NoScale.Total is a decimal"); + } + + [Fact] + public static async Task ANotMappedMember_IsNotAnOutput() + { + var c = new OutputConnection(Fill(("Count", 2))); + + Assert.Equal(2, (await c.StoredProcedure("p").ExecuteOutputAsync(Token)).Count); + Assert.Equal("Count", Assert.Single(c.Last!.All).ParameterName); + } + + [Fact] + public static void AReturnValueMember_OnATextCommand_ThrowsAtTheCall() + { + ThrowsAtTheCall( + c => c.Command("exec dbo.Touch @Count output").ExecuteOutputAsync(Token), + "Touched.ReturnValue reads a stored procedure's return code, but the command is not a stored procedure (it is Text)", + "Call the procedure as CommandType.StoredProcedure"); + } + + [Fact] + public static void TheNamedForm_TakesOneValueOfAType_ThatNeedsNoDeclaration() + { + ThrowsAtTheCall( + c => c.StoredProcedure("p").ExecuteOutputAsync("id", Token), + "ExecuteOutputAsync(\"id\") reads one value, but NewPost is a model", + "Call ExecuteOutputAsync() without a name"); + + // A decimal needs its precision and scale: without them, the call throws and gives the two forms that take them. + ThrowsAtTheCall( + c => c.StoredProcedure("p").ExecuteOutputAsync("total", Token), + "The output parameter 'total' is read as Decimal", + "A decimal output needs its precision and scale, or the server rounds it to a whole number. Use ExecuteOutputAsync(\"total\", 19, 4) or ExecuteOutputDecimalAsync(\"total\", 19, 4) with the column's precision and scale."); + ThrowsAtTheCall( + c => c.StoredProcedure("p").ExecuteOutputAsync("total", Token), + "The output parameter 'total' is read as Decimal", + "ExecuteOutputDecimalAsync(\"total\", 19, 4)"); + ThrowsAtTheCall( + c => c.StoredProcedure("p").ExecuteOutputAsync("day", Token), + "The output parameter 'day' is read as DateOnly, which has no database type", + "Read it as a type that has one"); + } + + // The name is checked first in every named form: a model type with a null name binds to the named form. + [Fact] + public static void TheNamedForms_RequireAName_First() + { + const string required = "A parameter name is required, for example ExecuteOutputAsync(\"total\")."; + ThrowsAtTheCall(c => c.StoredProcedure("p").ExecuteOutputAsync(null!, Token), required); + ThrowsAtTheCall(c => c.StoredProcedure("p").ExecuteOutputAsync(null!, Token), required); + ThrowsAtTheCall(c => c.StoredProcedure("p").ExecuteOutputAsync(" ", Token), required); + ThrowsAtTheCall(c => c.StoredProcedure("p").ExecuteOutputAsync("@", Token), required); + ThrowsAtTheCall(c => c.StoredProcedure("p").ExecuteOutputAsync(null!, 19, 4, Token), required); + ThrowsAtTheCall(c => c.StoredProcedure("p").ExecuteOutputDecimalAsync("@", 19, 4, Token), required); + } + + // A model cannot hold the return code: ExecuteReturnAsync and a ReturnValue member of a model type throw at the call. + [Fact] + public static void TheReturnCode_IsOneInteger() + { + ThrowsAtTheCall( + c => c.StoredProcedure("p").ExecuteReturnAsync(Token), + "The return code is one integer, so NewPost cannot hold it. Use int (or int?, long, an enum), or a ReturnValue member on the output model."); + ThrowsAtTheCall( + c => c.StoredProcedure("p").ExecuteOutputAsync(Token), + "ModelReturn.ReturnValue reads the return code, which is one integer, so NewPost cannot hold it. Change ModelReturn.ReturnValue to int"); + } + + [Fact] + public static void ACanceledToken_ThrowsBeforeAnythingRuns() + { + using var canceled = new CancellationTokenSource(); + canceled.Cancel(); + ThrowsAtTheCall(c => c.StoredProcedure("p").ExecuteOutputAsync(canceled.Token)); + ThrowsAtTheCall(c => c.StoredProcedure("p").UseCancellationToken(canceled.Token).ExecuteOutputAsync("id")); + } + + [Fact] + public static async Task TheNamedForm_SendsTheNameAsGiven_AndConverts() + { + var c = new OutputConnection(Fill(("@id", 7))); + + Assert.Equal(7L, await c.StoredProcedure("dbo.AddPost").ExecuteOutputAsync("@id", Token)); + DbParameter id = Assert.Single(c.Last!.All); + Assert.Equal((ParameterDirection.Output, DbType.Int64), (id.Direction, id.DbType)); + + // A value added under the same name makes it InputOutput. + c = new OutputConnection(); + Assert.Equal(5, await c.StoredProcedure("dbo.AddPost").AddParam("id", 5).ExecuteOutputAsync("@id", Token)); + Assert.Equal(ParameterDirection.InputOutput, Assert.Single(c.Last!.All).Direction); + } + + // The decimal forms send the precision and scale they are given. ExecuteOutputDecimalAsync returns decimal?; + // ExecuteOutputAsync lets T decide NULL: null in a decimal?, an error in a decimal. + [Fact] + public static async Task TheDecimalForms_SendThePrecisionAndScale_AndTDecidesNull() + { + var c = new OutputConnection(Fill(("total", 12.3456m))); + + Assert.Equal(12.3456m, await c.StoredProcedure("dbo.OrderTotal").ExecuteOutputAsync("total", 19, 4, Token)); + DbParameter total = Assert.Single(c.Last!.All); + Assert.Equal((ParameterDirection.Output, DbType.Decimal, (byte)19, (byte)4), (total.Direction, total.DbType, total.Precision, total.Scale)); + Assert.Equal(12.3456m, await c.StoredProcedure("dbo.OrderTotal").ExecuteOutputDecimalAsync("total", 19, 4, Token)); + Assert.Equal(12.3456m, await c.StoredProcedure("dbo.OrderTotal").ExecuteOutputAsync("total", 19, 4, Token)); + + c = new OutputConnection(Fill(("total", DBNull.Value))); + Assert.Null(await c.StoredProcedure("dbo.OrderTotal").ExecuteOutputDecimalAsync("total", 38, 0, Token)); + Assert.Null(await c.StoredProcedure("dbo.OrderTotal").ExecuteOutputAsync("total", 38, 0, Token)); + var ex = await Assert.ThrowsAsync(async () => await c.StoredProcedure("dbo.OrderTotal").ExecuteOutputAsync("total", 38, 0, Token)); + Assert.Contains("The decimal output parameter 'total' is NULL, which a decimal cannot hold", ex.Message); + Assert.Contains("Read it as decimal?", ex.Message); + + // A value added under the same name makes it InputOutput. + c = new OutputConnection(); + Assert.Equal(1.5m, await c.StoredProcedure("dbo.OrderTotal").AddParam("total", 1.5m).ExecuteOutputDecimalAsync("@total", 10, 2, Token)); + total = Assert.Single(c.Last!.All); + Assert.Equal((ParameterDirection.InputOutput, (byte)10, (byte)2), (total.Direction, total.Precision, total.Scale)); + } + + [Fact] + public static void TheDecimalForms_RefuseAPrecisionOrScaleOutOfRange_OrAnotherType_AtTheCall() + { + ThrowsAtTheCall( + c => c.StoredProcedure("p").ExecuteOutputAsync("total", 0, 0, Token), + "The precision of the decimal output parameter 'total' is 0, but it must be from 1 to 38", + "For decimal(19,4), pass ExecuteOutputAsync(\"total\", 19, 4)"); + ThrowsAtTheCall( + c => c.StoredProcedure("p").ExecuteOutputDecimalAsync("total", 39, 2, Token), + "is 39, but it must be from 1 to 38"); + ThrowsAtTheCall( + c => c.StoredProcedure("p").ExecuteOutputDecimalAsync("total", 10, 12, Token), + "The scale of the decimal output parameter 'total' is 12, more than its precision of 10", + "For decimal(19,4), pass ExecuteOutputAsync(\"total\", 19, 4)"); + ThrowsAtTheCall( + c => c.StoredProcedure("p").ExecuteOutputAsync("count", 19, 4, Token), + "Only a decimal output takes a precision and scale; Int32 needs none (date and time outputs keep full precision). Use ExecuteOutputAsync(\"count\")."); + ThrowsAtTheCall( + c => c.StoredProcedure("p").ExecuteOutputAsync("created", 19, 4, Token), + "Only a decimal output takes a precision and scale; DateTime needs none"); + } + + // SQLite refuses any direction but Input on the setter (P10): its own exception, while the call is built. + [Fact] + public static async Task SQLite_RefusesAnOutput_WithItsOwnError() + { + await using var c = new Microsoft.Data.Sqlite.SqliteConnection("Data Source=:memory:"); + await c.OpenAsync(Token); + + await Assert.ThrowsAsync(async () => await c.Command("select @Count").ExecuteOutputAsync(Token)); + } + + // One command can run on several threads at once: each call has its own output parameters. + [Fact] + public static async Task ConcurrentCalls_OnOneCommand_EachReadTheirOwn() + { + int next = 0; + var c = new OutputConnection(command => command.Named("Id").Value = Interlocked.Increment(ref next)); + var factory = new DbConnectionFactory(() => c); + ExpressiveDbCommand command = factory.StoredProcedure("dbo.Next"); + + int[] ids = await Task.WhenAll(Enumerable.Range(0, 64).Select(_ => Task.Run(async () => await command.ExecuteOutputAsync("Id", Token), Token))); + + Assert.Equal(Enumerable.Range(1, 64), ids.Order()); + } +} diff --git a/Tests/Open.Database.Extensions.Core.Tests/TestHelpers/LocalDbFixture.cs b/Tests/Open.Database.Extensions.Core.Tests/TestHelpers/LocalDbFixture.cs index 9153f1c2..d503f097 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/TestHelpers/LocalDbFixture.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/TestHelpers/LocalDbFixture.cs @@ -110,6 +110,14 @@ public static Scratch CreateProcedure(string parameters, string prefix = "ode_p" return new Scratch("procedure", name); } + /// A stored procedure with the given parameter list and body (the statements after as). + public static Scratch CreateProcedureWithBody(string parameters, string body, string prefix = "ode_p") + { + string name = UniqueName(prefix); + Execute($"create procedure dbo.[{name}] {parameters} as {body}"); + return new Scratch("procedure", name); + } + /// An object created in tempdb for one test. Disposing it drops the object. public sealed class Scratch(string kind, string name) : IDisposable { diff --git a/docsite/articles/expressive-commands.md b/docsite/articles/expressive-commands.md index 60da0f84..c08978a3 100644 --- a/docsite/articles/expressive-commands.md +++ b/docsite/articles/expressive-commands.md @@ -179,7 +179,36 @@ To get the id an insert generated, select it in the same command and read it wit [!code-csharp[](../samples/SqlServer.cs#sql_server_return)] -Output values cannot be read back, and a direction cannot be set on the chain: `AddParam` adds inputs only. To set a direction, use `ExecuteAsync(command => ...)` with the raw `AddParameter`, `AddParameterType` and `AddReturnParameter` extensions on the command. A result set and the return value are readable on the chain. +A result set and the return value are readable on the chain; output parameters are read with `ExecuteOutputAsync` (below). `AddParam` adds inputs only. To set a direction yourself, use `ExecuteAsync(command => ...)` with the raw `AddParameter`, `AddParameterType` and `AddReturnParameter` extensions on the command. + +### Output parameters + +`ExecuteOutputAsync()` runs the command and reads its output parameters, and its return code, into one model. Each member `Map()` would read is an output parameter, and the model is built by the same rules (records, constructors, `required`, conversions, `[NullPolicy]`): + +```csharp +record NewPost(int Id, DateTime CreatedUtc); // @id OUTPUT, @created_utc OUTPUT + +NewPost created = await db.StoredProcedure("dbo.AddPost") + .AddParam(title) + .ExecuteOutputAsync(cancellationToken); +``` + +- **Names.** A member finds its parameter as `AddParam(value)` does: through the four tiers when the names are known (a procedure's, or a text's `@name` markers, so `exec dbo.AddPost @id output` works too), else under its own name. `[Column("name")]` names the parameter exactly. A member that matches no parameter, or two members on one parameter, throw `InvalidOperationException` before the command runs. +- **Direction.** A member whose parameter got a value (`AddParam`, `AddParams`) is sent as InputOutput; any other as Output. +- **Return code.** A member named `ReturnValue` reads a stored procedure's return code. On a text command it throws, and so does a procedure that declares a parameter that name would also match: name that member with `[Column]`. +- **Types.** A `DateTime` is sent as `datetime2`; a `string` or `byte[]` with size -1, so the whole value comes back. 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. +- **Not delivered.** An Output parameter still empty after the call means the response never completed: the call throws `InvalidOperationException`, never a NULL. + +There is no blocking form. Known limits: + +- An Output parameter sends NULL in, so the procedure's default for it is not used. +- 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 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`. +- SqlClient reports an error after the outputs are set, and a cancel while the command runs, with its own `SqlException`. +- A `DateTime` output is read through `datetime2`, so a legacy `datetime` arrives as its exact stored value (`.997` as `.9966667`). A `DateOnly` or `TimeOnly` member has no database type for an output and throws before the call runs. +- Output models use the runtime map, not a generated reader. ## Terminals @@ -188,6 +217,7 @@ Output values cannot be read back, and a direction cannot be set on the chain: ` | `ExecuteNonQueryAsync(token)` | Rows affected | | `ExecuteScalarAsync(token)`, `ExecuteScalarAsync(value => ..., token)`, `ExecuteScalarAsync(token)` | The first column of the first row: [which form](#which-scalar-form) | | `ExecuteReturnAsync(token)` | The value of the return-value parameter: [see above](#return-values-and-output-parameters) | +| `ExecuteOutputAsync(token)`, `ExecuteOutputAsync(name, token)`, `ExecuteOutputAsync(name, precision, scale, token)`, `ExecuteOutputDecimalAsync(name, precision, scale, token)` | Output parameters and the return code as a model, or one output parameter: [see above](#output-parameters) | | `ExecuteAsync(command => ...)` | Whatever your function returns, given the raw command with its text, parameters and timeout applied: use it for a call the other terminals do not wrap | | `ExecuteReaderAsync(reader => ..., token)` | Whatever your function returns, given the live reader | | `Map()` then a terminal | Mapped objects, or one value per row such as `int` read from the first column: see [Mapping rows to objects](mapping.md) and [One value per row](mapping.md#one-value-per-row) | @@ -201,7 +231,7 @@ The blocking forms (the same names without `Async`) are in the `Open.Database.Ex The `Async` terminals honor the command's cancellation token (`UseCancellationToken(token)`); `ExecuteNonQueryAsync` and `ExecuteScalarAsync` are on `ExpressiveDbCommand` and `ExpressiveSqlCommand`. `SetTimeout(seconds)` sets the command timeout. The default is 60 seconds. On SQL Server the lookup of a stored procedure's parameter names uses the same timeout. A failed lookup throws the provider's own exception (a `SqlException` stays a `SqlException`, so a retry policy still sees it), with the procedure's name in `Exception.Data["Procedure"]`. -`UseCancellationToken(token)` sets a token for the command. A token passed to an async terminal such as `ToListAsync(token)` is combined with it, and either one cancels the call. The `Async` terminals of the command itself (`ExecuteNonQueryAsync`, `ExecuteScalarAsync`, `ExecuteReaderAsync`, `ExecuteReturnAsync`) take a `CancellationToken` too, and it is combined with this one. The call then stops with `OperationCanceledException`, except that a provider may report a cancellation that arrives while the command is executing as its own exception (SQL Server's `SqlException`, "Operation cancelled by user"); the library does not translate it. The token covers opening the connection, looking up stored-procedure parameter names, executing the command and reading the rows. +`UseCancellationToken(token)` sets a token for the command. A token passed to an async terminal such as `ToListAsync(token)` is combined with it, and either one cancels the call. The `Async` terminals of the command itself (`ExecuteNonQueryAsync`, `ExecuteScalarAsync`, `ExecuteReaderAsync`, `ExecuteReturnAsync`, `ExecuteOutputAsync`, `ExecuteOutputDecimalAsync`) take a `CancellationToken` too, and it is combined with this one. The call then stops with `OperationCanceledException`, except that a provider may report a cancellation that arrives while the command is executing as its own exception (SQL Server's `SqlException`, "Operation cancelled by user"); the library does not translate it. The token covers opening the connection, looking up stored-procedure parameter names, executing the command and reading the rows. ### Sequential access, for very large values diff --git a/docsite/articles/mapping.md b/docsite/articles/mapping.md index f2248b00..6c684ce1 100644 --- a/docsite/articles/mapping.md +++ b/docsite/articles/mapping.md @@ -239,6 +239,8 @@ To switch the generator off for a project (the setting applies to the project it The [generator's README](https://github.com/Open-NET-Libraries/Open.Database.Extensions/blob/master/Source/Generator/README.md) lists what is left to the runtime map. +Output parameters read into a model (`ExecuteOutputAsync()`, see [Output parameters](expressive-commands.md#output-parameters)) follow the rules of this page: each member is matched to a parameter and the model is built as from a row, always by the runtime map, never a generated reader. Two things apply only there: a `decimal` member needs `[Column(TypeName = "decimal(p,s)")]` for the precision and scale it is sent with, and a `DateTime` member is sent as `DbType.DateTime2`. + ## Types and NULL This section, and the NULL messages below, describe the runtime map; a [generated reader](#generated-readers) reads each member with its type's getter and converts nothing of its own. Values are read with the provider's typed getters (`GetInt32`, `GetString`, ...), so nothing is boxed on the common path. When the column type and the property type differ: diff --git a/docsite/articles/release-notes.md b/docsite/articles/release-notes.md index 0743dea0..5526323a 100644 --- a/docsite/articles/release-notes.md +++ b/docsite/articles/release-notes.md @@ -10,6 +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`; `AddParam(name, type)`, `AddParam(name, direction)`, `AddParamIf` with only a type or direction, and `AddReturnParam` are gone. 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. `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). ### Changes since rc.15 diff --git a/docsite/articles/whats-new-11.md b/docsite/articles/whats-new-11.md index 0ba8b88b..f83234a7 100644 --- a/docsite/articles/whats-new-11.md +++ b/docsite/articles/whats-new-11.md @@ -130,6 +130,7 @@ See [Expressive commands](expressive-commands.md). - **A typed NULL** such as `AddParam("@id", (long?)null)` is sent with the database type of its overload. - **After a run, `Params` holds what you added,** under the names as added. Read the provider command's `Parameters` in `Execute(command => ...)` to see what was sent. - **No direction on the chain.** `AddParam`, `AddParamIf` and `AddReturnParam` no longer take a `ParameterDirection`, so a parameter added on the chain is an input; the overloads that took only a direction or only a type, and `AddReturnParam`, are gone. To set a direction, use `ExecuteAsync(command => ...)` with the raw `AddParameter`, `AddParameterType` and `AddReturnParameter` extensions. `Param` has no `direction` constructor parameter and no `Direction` property. +- **Output parameters into a model.** `ExecuteOutputAsync()` reads a command's output parameters and return code into a model by name (`ExecuteOutputAsync(name)` for one value): see [Output parameters](expressive-commands.md#output-parameters). See [Parameters](expressive-commands.md#name-a-parameter-from-its-argument). From dfcd80ee9fd1084939be9e0b915c877cebc1f22c Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Tue, 1 Dec 2026 20:14:26 -0800 Subject: [PATCH 04/20] Make the removed fluent direction and type-only shapes compile errors. AddParam(name, direction), AddParamIf(condition, name, direction), AddParam(name, type) and AddParamIf(condition, name, type) would otherwise still compile and send the enum as the value. They are now kept as obsolete-as-error overloads that explain what to do instead, and throw NotSupportedException if reached by reflection. Stale docs about output parameters are corrected, and a test keeps the check that derived-name parameters carry no direction. Co-Authored-By: Claude Sonnet 5.5 --- Source/Core/ExpressiveCommandBase.cs | 56 +++++++++++++++++++ Source/Core/PublicAPI.Unshipped.txt | 4 +- Source/MSSqlClient/README.md | 2 +- .../ChainTrapOverloadTests.cs | 38 +++++++++++++ .../DerivedParameterNameTests.cs | 17 ++++++ .../RemovedMembersTests.cs | 3 +- docsite/articles/release-notes.md | 2 +- docsite/articles/whats-new-11.md | 4 +- 8 files changed, 119 insertions(+), 7 deletions(-) create mode 100644 Tests/Open.Database.Extensions.Core.Tests/ChainTrapOverloadTests.cs diff --git a/Source/Core/ExpressiveCommandBase.cs b/Source/Core/ExpressiveCommandBase.cs index 23e22991..1567cdd4 100644 --- a/Source/Core/ExpressiveCommandBase.cs +++ b/Source/Core/ExpressiveCommandBase.cs @@ -1,3 +1,4 @@ +using System.ComponentModel; using Open.Database.Extensions.Synchronous; namespace Open.Database.Extensions; @@ -700,6 +701,61 @@ public TThis AddParamIf(bool condition, string name, T? value, TDbType type) where T : struct => condition ? AddParam(name, value, type) : (TThis)this; + // These shapes are not part of the API. They exist only so that a call that used to set a direction or send an output type fails to compile + // with an explanation, instead of binding to a value overload and sending the enum as the value. + const string DirectionMessage = "A parameter direction cannot be set on the chain. Read outputs with ExecuteOutputAsync, or set the direction on the raw command inside ExecuteAsync(command => ...)."; + const string TypeOnlyMessage = "Pass a value with the type, for example AddParam(name, (int?)null, type)."; + + /// + /// Not usable: a parameter direction cannot be set on the chain. + /// + /// Not used. + /// Not used. + /// Never returns. + /// Always. + [Obsolete(DirectionMessage, error: true)] + [EditorBrowsable(EditorBrowsableState.Never)] + public TThis AddParam(string name, ParameterDirection direction) + => throw new NotSupportedException(DirectionMessage); + + /// + /// Not usable: a parameter direction cannot be set on the chain. + /// + /// Not used. + /// Not used. + /// Not used. + /// Never returns. + /// Always. + [Obsolete(DirectionMessage, error: true)] + [EditorBrowsable(EditorBrowsableState.Never)] + public TThis AddParamIf(bool condition, string name, ParameterDirection direction) + => throw new NotSupportedException(DirectionMessage); + + /// + /// Not usable: a parameter needs a value as well as a type. + /// + /// Not used. + /// Not used. + /// Never returns. + /// Always. + [Obsolete(TypeOnlyMessage, error: true)] + [EditorBrowsable(EditorBrowsableState.Never)] + public TThis AddParam(string name, TDbType type) + => throw new NotSupportedException(TypeOnlyMessage); + + /// + /// Not usable: a parameter needs a value as well as a type. + /// + /// Not used. + /// Not used. + /// Not used. + /// Never returns. + /// Always. + [Obsolete(TypeOnlyMessage, error: true)] + [EditorBrowsable(EditorBrowsableState.Never)] + public TThis AddParamIf(bool condition, string name, TDbType type) + => throw new NotSupportedException(TypeOnlyMessage); + /// /// Handles adding the list of parameters to a new command. /// diff --git a/Source/Core/PublicAPI.Unshipped.txt b/Source/Core/PublicAPI.Unshipped.txt index af63ca7f..6dcc8ab9 100644 --- a/Source/Core/PublicAPI.Unshipped.txt +++ b/Source/Core/PublicAPI.Unshipped.txt @@ -13,7 +13,6 @@ Open.Database.Extensions.MappedQueryWithTake.SequentialAccess() -> Open.Datab static Open.Database.Extensions.Synchronous.SyncCommandExtensions.ToDataTable(this System.Data.IDbCommand! command, System.Data.CommandBehavior behavior = System.Data.CommandBehavior.Default) -> System.Data.DataTable! *REMOVED*static Open.Database.Extensions.Synchronous.SyncCommandExtensions.ToDataTables(this System.Data.IDbCommand! command, System.Data.CommandBehavior behavior = System.Data.CommandBehavior.SequentialAccess) -> System.Collections.Generic.List! static Open.Database.Extensions.Synchronous.SyncCommandExtensions.ToDataTables(this System.Data.IDbCommand! command, System.Data.CommandBehavior behavior = System.Data.CommandBehavior.Default) -> System.Collections.Generic.List! -*REMOVED*Open.Database.Extensions.ExpressiveCommandBase.AddParam(string! name, System.Data.ParameterDirection direction) -> TThis! *REMOVED*Open.Database.Extensions.ExpressiveCommandBase.AddParam(string! name, TDbType type, System.Data.ParameterDirection direction = System.Data.ParameterDirection.Input) -> TThis! *REMOVED*Open.Database.Extensions.ExpressiveCommandBase.AddParam(string! name, char value, TDbType type, System.Data.ParameterDirection direction = System.Data.ParameterDirection.Input) -> TThis! Open.Database.Extensions.ExpressiveCommandBase.AddParam(string! name, char value, TDbType type) -> TThis! @@ -37,7 +36,6 @@ Open.Database.Extensions.ExpressiveCommandBase.AddParam(string! name, T? value, TDbType type) -> TThis! *REMOVED*Open.Database.Extensions.ExpressiveCommandBase.AddParam(string! name, T? value, TDbType? type = null, System.Data.ParameterDirection direction = System.Data.ParameterDirection.Input) -> TThis! Open.Database.Extensions.ExpressiveCommandBase.AddParam(string! name, T? value, TDbType? type = null) -> TThis! -*REMOVED*Open.Database.Extensions.ExpressiveCommandBase.AddParamIf(bool condition, string! name, System.Data.ParameterDirection direction) -> TThis! *REMOVED*Open.Database.Extensions.ExpressiveCommandBase.AddParamIf(bool condition, string! name, TDbType type, System.Data.ParameterDirection direction = System.Data.ParameterDirection.Input) -> TThis! *REMOVED*Open.Database.Extensions.ExpressiveCommandBase.AddParamIf(bool condition, string! name, char value, TDbType type, System.Data.ParameterDirection direction = System.Data.ParameterDirection.Input) -> TThis! Open.Database.Extensions.ExpressiveCommandBase.AddParamIf(bool condition, string! name, char value, TDbType type) -> TThis! @@ -74,3 +72,5 @@ Open.Database.Extensions.ExpressiveCommandBase.ExecuteOutputAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask Open.Database.Extensions.ExpressiveCommandBase.ExecuteOutputAsync(string! name, byte precision, byte scale, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask Open.Database.Extensions.ExpressiveCommandBase.ExecuteOutputDecimalAsync(string! name, byte precision, byte scale, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +Open.Database.Extensions.ExpressiveCommandBase.AddParam(string! name, TDbType type) -> TThis! +Open.Database.Extensions.ExpressiveCommandBase.AddParamIf(bool condition, string! name, TDbType type) -> TThis! diff --git a/Source/MSSqlClient/README.md b/Source/MSSqlClient/README.md index a3f63f93..80312062 100644 --- a/Source/MSSqlClient/README.md +++ b/Source/MSSqlClient/README.md @@ -47,7 +47,7 @@ posts = await connectionFactory .ToArrayAsync(); ``` -Parameter names are read once per connection factory, and again after a call that cannot be built or that the database rejects (keep one factory: a connection or factory you create for each call reads them for every command). The return value of a procedure is readable with `ExecuteReturn()`; output parameters can be sent, but their values cannot be read back. See [Expressive commands](https://open-net-libraries.github.io/Open.Database.Extensions/articles/expressive-commands.html) for the rules and limits. +Parameter names are read once per connection factory, and again after a call that cannot be built or that the database rejects (keep one factory: a connection or factory you create for each call reads them for every command). The return value of a procedure is readable with `ExecuteReturn()`; output parameters are not set on the chain: read them with `ExecuteOutputAsync`, or use the raw extensions inside `ExecuteAsync(command => ...)`. See [Expressive commands](https://open-net-libraries.github.io/Open.Database.Extensions/articles/expressive-commands.html) for the rules and limits. ## The packages diff --git a/Tests/Open.Database.Extensions.Core.Tests/ChainTrapOverloadTests.cs b/Tests/Open.Database.Extensions.Core.Tests/ChainTrapOverloadTests.cs new file mode 100644 index 00000000..915d8132 --- /dev/null +++ b/Tests/Open.Database.Extensions.Core.Tests/ChainTrapOverloadTests.cs @@ -0,0 +1,38 @@ +using System.Reflection; + +namespace Open.Database.Extensions.Tests; + +#nullable enable + +// The four shapes that would otherwise bind silently to a value overload (sending the enum as the value) are compile errors; reflection can still reach them. +[ExcludeFromCodeCoverage] +public static class ChainTrapOverloadTests +{ + static MethodInfo Find(string name, params Type[] parameters) + => typeof(ExpressiveCommand).GetMethod(name, parameters) + ?? throw new InvalidOperationException($"{name} with {parameters.Length} parameters was not found."); + + public static TheoryData Shapes => new() + { + { "AddParam", [typeof(string), typeof(ParameterDirection)], ["o", ParameterDirection.Output] }, + { "AddParamIf", [typeof(bool), typeof(string), typeof(ParameterDirection)], [true, "o", ParameterDirection.Output] }, + { "AddParam", [typeof(string), typeof(DbType)], ["x", DbType.Int32] }, + { "AddParamIf", [typeof(bool), typeof(string), typeof(DbType)], [true, "x", DbType.Int32] }, + }; + + [Theory] + [MemberData(nameof(Shapes))] + public static void TheShape_IsAnObsoleteError_AndThrowsWhenInvoked(string name, Type[] parameters, object?[] arguments) + { + MethodInfo method = Find(name, parameters); + + ObsoleteAttribute obsolete = Assert.IsType(Assert.Single(method.GetCustomAttributes(typeof(ObsoleteAttribute), false))); + Assert.True(obsolete.IsError); + Assert.NotEmpty(obsolete.Message!); + + var command = new ExpressiveCommand(Substitute.For(), CommandType.Text, "select 1"); + var thrown = Assert.Throws(() => method.Invoke(command, arguments)); + Assert.IsType(thrown.InnerException); + Assert.Equal(obsolete.Message, thrown.InnerException!.Message); + } +} diff --git a/Tests/Open.Database.Extensions.Core.Tests/DerivedParameterNameTests.cs b/Tests/Open.Database.Extensions.Core.Tests/DerivedParameterNameTests.cs index 701eacb6..b2c00b4d 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/DerivedParameterNameTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/DerivedParameterNameTests.cs @@ -953,4 +953,21 @@ public static void AddParams_MixesWithDerivedAndNamedParams_InAnyOrder() Assert.Equal(new Dictionary { ["@mode"] = 1, ["@company_serial_num"] = 42, ["@region"] = "west", ["@limit"] = 10 }, Sent(probe)); } + + // A name that is derived from the argument is still an input: no direction is set on it, before or after its real name is known. + [Fact] + public static void AnArgumentNamedByItsExpression_IsSentAsAnInput() + { + var recorder = new RecordingDbCommand(); + const int orderId = 5; + + new ExpressiveDbCommand(new OpenDbConnection(recorder), CommandType.StoredProcedure, "dbo.p") + .AddParam(orderId) + .AddParams(new { Name = "ann" }) + .ExecuteNonQuery(); + + Assert.Equal(["orderId", "Name"], recorder.Sent.Select(p => p.ParameterName)); + // The chain sets no direction: each parameter reports what the provider gives a new one. + Assert.All(recorder.Sent, p => Assert.Equal(recorder.CreateParameter().Direction, p.Direction)); + } } diff --git a/Tests/Open.Database.Extensions.Core.Tests/RemovedMembersTests.cs b/Tests/Open.Database.Extensions.Core.Tests/RemovedMembersTests.cs index 59c79d0a..2c8c7ff0 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/RemovedMembersTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/RemovedMembersTests.cs @@ -21,7 +21,8 @@ public static void TheCorePackage_ShipsNothingObsolete() if (type.GetCustomAttribute() is not null) obsolete.Add(type.FullName!); foreach (MemberInfo member in type.GetMembers(All)) { - if (member.GetCustomAttribute() is not null) + // The four chain overloads that would otherwise rebind silently are compile errors, kept on purpose (see ChainTrapOverloadTests). + if (member.GetCustomAttribute() is { IsError: false }) obsolete.Add($"{type.FullName}.{member.Name}"); } } diff --git a/docsite/articles/release-notes.md b/docsite/articles/release-notes.md index 5526323a..6738eca2 100644 --- a/docsite/articles/release-notes.md +++ b/docsite/articles/release-notes.md @@ -9,7 +9,7 @@ Version 11 is `11.0.0-rc.16`. For moving a 10.x codebase, read [Coming from earl - **Generated row readers for `DbQuery` too.** A plain `Map()` on a `DbQuery`, a `DbQuery` or a query bound with `Using` now gets its row reader written at build time, as on a command or a reader; before, it used the runtime map. The runtime map's conversions are therefore no longer applied there: see [Generated readers](mapping.md#generated-readers) for the differences and the switch. - **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`; `AddParam(name, type)`, `AddParam(name, direction)`, `AddParamIf` with only a type or direction, and `AddReturnParam` are gone. 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. `Param` has no `direction` constructor parameter and no `Direction` property. +- **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. 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. `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). ### Changes since rc.15 diff --git a/docsite/articles/whats-new-11.md b/docsite/articles/whats-new-11.md index f83234a7..57745614 100644 --- a/docsite/articles/whats-new-11.md +++ b/docsite/articles/whats-new-11.md @@ -129,7 +129,7 @@ See [Expressive commands](expressive-commands.md). - **Names from arguments.** `.AddParam(author)` takes the name from the variable and matches it to the stored procedure's real name. `AddParam("name", value)` always wins. - **A typed NULL** such as `AddParam("@id", (long?)null)` is sent with the database type of its overload. - **After a run, `Params` holds what you added,** under the names as added. Read the provider command's `Parameters` in `Execute(command => ...)` to see what was sent. -- **No direction on the chain.** `AddParam`, `AddParamIf` and `AddReturnParam` no longer take a `ParameterDirection`, so a parameter added on the chain is an input; the overloads that took only a direction or only a type, and `AddReturnParam`, are gone. To set a direction, use `ExecuteAsync(command => ...)` with the raw `AddParameter`, `AddParameterType` and `AddReturnParameter` extensions. `Param` has no `direction` constructor parameter and no `Direction` property. +- **No direction on the chain.** `AddParam`, `AddParamIf` and `AddReturnParam` no longer take a `ParameterDirection`, so a parameter added on the chain is an input; `AddReturnParam` is gone. Calls that never passed a direction compile unchanged; `AddParam(name, direction)`, `AddParamIf(condition, name, direction)`, `AddParam(name, type)` and `AddParamIf(condition, name, type)` are now compile errors that say what to do instead. To set a direction, use `ExecuteAsync(command => ...)` with the raw `AddParameter`, `AddParameterType` and `AddReturnParameter` extensions. `Param` has no `direction` constructor parameter and no `Direction` property. - **Output parameters into a model.** `ExecuteOutputAsync()` reads a command's output parameters and return code into a model by name (`ExecuteOutputAsync(name)` for one value): see [Output parameters](expressive-commands.md#output-parameters). See [Parameters](expressive-commands.md#name-a-parameter-from-its-argument). @@ -163,7 +163,7 @@ Every mapped overload takes one `RowMap? map` where 10.x took key/value pairs ## Known limitations - The library is not marked trimmable and does not support native AOT. The runtime map builds its row readers as expression trees; under native AOT, .NET interprets them instead of compiling them, so every row it reads is slower. A trimmed app keeps its model types and the provider's reader type: the recipe is in the [Core README](https://github.com/Open-NET-Libraries/Open.Database.Extensions/blob/master/Source/Core/README.md#trimming-and-native-aot). -- Output parameters can be sent, but their values cannot be read back after the call. On providers other than SQL Server, which report no procedure parameter names, `AddParam(search.Author)` sends the last member of the expression, `Author`, as the name. +- Output parameters are not set on the chain: read them with `ExecuteOutputAsync`, or use the raw extensions inside `ExecuteAsync(command => ...)`. On providers other than SQL Server, which report no procedure parameter names, `AddParam(search.Author)` sends the last member of the expression, `Author`, as the name. - A missing column for a `required` property is reported by `Map` at the first row, so an empty result does not report it. - The unmapped `ToChannel` overloads can lose the row that was in flight when a read fails while the target is full. The cause is in the underlying channel library. - The synchronous `ToTargetBlock` overloads post each row without waiting: when the target is complete, or bounded and full, reading stops without an error, and only the number the call returns (the rows read and handed over) shows the shortfall. Use the `Async` overload to feed a bounded target. From 176446051f40a6d6a71f7e7bf00dd29803349cfb Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Tue, 1 Dec 2026 20:28:25 -0800 Subject: [PATCH 05/20] Output parameters: DateOnly and TimeOnly, legacy datetime documented, review fixes. DateOnly is sent as Date and TimeOnly as Time (nullable forms included) and read back by the row conversion. A legacy datetime output reading .9966667 is documented with its remedy (SqlDateTime, or datetime2(3)) and pinned by tests. The decimal shape overload guards its arguments once, the shape message only suggests calls that work for the type, ExecuteOutputAsync documents when it completes and links the named and decimal forms, and a not-delivered output wins over a conversion failure. Co-Authored-By: Claude Sonnet 5.5 --- Source/Core/ExpressiveCommandBase.Output.cs | 16 +++- Source/Core/OutputLayout.cs | 24 +++-- .../OutputParameterLocalDbTests.cs | 89 ++++++++++++++++--- .../OutputParameterTests.cs | 71 +++++++++++++-- docsite/articles/expressive-commands.md | 4 +- docsite/articles/mapping.md | 2 +- 6 files changed, 176 insertions(+), 30 deletions(-) diff --git a/Source/Core/ExpressiveCommandBase.Output.cs b/Source/Core/ExpressiveCommandBase.Output.cs index 8bcca67c..1af7245e 100644 --- a/Source/Core/ExpressiveCommandBase.Output.cs +++ b/Source/Core/ExpressiveCommandBase.Output.cs @@ -35,11 +35,19 @@ public abstract partial class ExpressiveCommandBase /// A is sent as ; a or array with size -1 (the whole value); /// a needs [Column(TypeName = "decimal(p,s)")], whose scale also rounds a value sent in. + /// A member of a read from a legacy datetime can differ from a row's in the last digit (see the article on expressive commands). + /// + /// + /// To read one value instead of a model, name it: . + /// A of a given precision and scale is read with + /// or . /// /// /// The model the output parameters are read into. /// - /// A task that represents the asynchronous operation; its result is the model. + /// + /// A task that completes when the command has executed and its output parameters have arrived; its result is the model. + /// /// /// Before anything runs: has no member to read, is a single value, has a member without its type name or a member of a type /// that has no database type, or reads the return code of a command that is not a stored procedure. @@ -179,10 +187,12 @@ public ValueTask ExecuteOutputAsync( { ThrowIfNoName(name); OutputValue.ThrowUnlessDecimal(name); + ThrowIfBadShape(name, precision, scale); Contract.EndContractBlock(); - // T is decimal? or decimal. Each cast goes through object to the same type, which the JIT removes in optimized code. - ValueTask value = ExecuteOutputDecimalAsync(name, precision, scale, cancellationToken); + // T is decimal? or decimal, and the arguments are checked: the run is the one ExecuteOutputDecimalAsync makes after its own guard. + // Each cast goes through object to the same type, which the JIT removes in optimized code. + ValueTask value = RunNamedAsync(OutputValue.Shaped(name, precision, scale), cancellationToken); return typeof(T) == typeof(decimal?) ? (ValueTask)(object)value : (ValueTask)(object)NotNullAsync(name, value); diff --git a/Source/Core/OutputLayout.cs b/Source/Core/OutputLayout.cs index 1b41ea7f..fd5f1f10 100644 --- a/Source/Core/OutputLayout.cs +++ b/Source/Core/OutputLayout.cs @@ -1,3 +1,4 @@ +using System.Diagnostics; using System.Globalization; namespace Open.Database.Extensions; @@ -135,6 +136,11 @@ public void Apply(IDbDataParameter parameter) error = OutputWireError.None; Type underlying = Nullable.GetUnderlyingType(type) ?? type; if (underlying == typeof(DateTime)) return DateTime2; +#if NET10_0_OR_GREATER + // Not in ClrDbTypes (an input's type): read back by RowMap's own conversion, as a row's DateOnly and TimeOnly are. + if (underlying == typeof(DateOnly)) return new(DbType.Date, 0, 0, 0); + if (underlying == typeof(TimeOnly)) return new(DbType.Time, 0, 0, 0); +#endif if (ClrDbTypes.From(type) is not { } dbType) { @@ -460,9 +466,18 @@ public static void ThrowUnlessDecimal(string name) if (Reason == OutputValueRefusal.Decimal) return; string shown = Shape.TypeName(typeof(T)); + string fix = Reason switch + { + // A model has no single value to read: the named form refuses it too. + OutputValueRefusal.NotScalar + => $"{shown} is a model; call ExecuteOutputAsync<{shown}>() without a name to read its members, giving each decimal member [Column(TypeName = \"decimal(p,s)\")].", + OutputValueRefusal.NoDbType + => $"{shown} has no database type for an output; read it as a type that has one, {OutputWire.SupportedTypes}.", + _ => $"Use ExecuteOutputAsync<{shown}>(\"{name}\").", + }; + throw new InvalidOperationException( - $"Only a decimal output takes a precision and scale; {shown} needs none (date and time outputs keep full precision). " - + $"Use ExecuteOutputAsync<{shown}>(\"{name}\")."); + $"Only a decimal output takes a precision and scale; {shown} needs none (date and time outputs keep full precision). {fix}"); } /// @@ -471,11 +486,10 @@ public static void ThrowUnlessDecimal(string name) /// The parameter's name. /// The precision, checked by the caller. /// The scale, checked by the caller. - /// The layout. - /// is not a . + /// The layout; is checked by the caller, which has called . public static OutputLayout Shaped(string name, byte precision, byte scale) { - ThrowUnlessDecimal(name); + Debug.Assert(Reason == OutputValueRefusal.Decimal); string display = $"The output parameter '{name}'"; return new(new OutputMember(name, exact: true, name, new OutputWire(DbType.Decimal, 0, precision, scale), display)); } diff --git a/Tests/Open.Database.Extensions.Core.Tests/OutputParameterLocalDbTests.cs b/Tests/Open.Database.Extensions.Core.Tests/OutputParameterLocalDbTests.cs index 1dc5ace6..e2cb828c 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/OutputParameterLocalDbTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/OutputParameterLocalDbTests.cs @@ -528,17 +528,14 @@ public static async Task TheDecimalForms_ReadADecimal_ByItsPrecisionAndScale() public sealed record PostClock(TimeSpan Span, DateTimeOffset At, DateTime Stamp); - public sealed record PostDay(DateOnly Day); - // Time types with no shape set read back exactly, with all 7 fraction digits, as model members and as named values. - // DateOnly has no database type for an output (ClrDbTypes gives none), so it is refused before the run (reported, not worked around). [Fact] public static async Task TimeTypes_WithNoShapeSet_ReadBackExactly() { LocalDbFixture.SkipUnlessAvailable(); using LocalDbFixture.Scratch procedure = Procedure( - "@span time(7) = null output, @at datetimeoffset(7) = null output, @day date = null output, @stamp datetime2(7) = null output", - "set @span = '12:34:56.1234567'; set @at = '2026-12-01T12:34:56.1234567+02:00'; set @day = '2026-12-01'; set @stamp = '2026-12-01T12:34:56.1234567';"); + "@span time(7) = null output, @at datetimeoffset(7) = null output, @stamp datetime2(7) = null output", + "set @span = '12:34:56.1234567'; set @at = '2026-12-01T12:34:56.1234567+02:00'; set @stamp = '2026-12-01T12:34:56.1234567';"); await using SqlConnection connection = await OpenAsync(); string name = "dbo." + procedure.Name; TimeSpan span = new TimeSpan(0, 12, 34, 56).Add(TimeSpan.FromTicks(1234567)); @@ -554,11 +551,6 @@ public static async Task TimeTypes_WithNoShapeSet_ReadBackExactly() DateTimeOffset named = await connection.StoredProcedure(name).ExecuteOutputAsync("at", Token); Assert.Equal((at, at.Offset), (named, named.Offset)); Assert.Equal(stamp, await connection.StoredProcedure(name).ExecuteOutputAsync("stamp", Token)); - - var model = Assert.Throws(() => connection.StoredProcedure(name).ExecuteOutputAsync(Token)); - Assert.Contains("PostDay.Day is DateOnly, which has no database type", model.Message); - var single = Assert.Throws(() => connection.StoredProcedure(name).ExecuteOutputAsync("day", Token)); - Assert.Contains("The output parameter 'day' is read as DateOnly, which has no database type", single.Message); } public sealed record PostMisc(long Views, bool Published, double Rating, string Code); @@ -583,8 +575,7 @@ public static async Task OtherTypes_ReadBackExactly_AndACharIsPadded() public sealed record PostLegacyTimes(DateTime Minute); - // Legacy smalldatetime into DateTime, which is sent as datetime2: exact. A legacy datetime is not asserted: .997 reads back as - // .9966667 through datetime2 (reported to the owner, not worked around). + // Legacy smalldatetime into DateTime, which is sent as datetime2: exact. [Fact] public static async Task ALegacySmallDateTime_ReadsBackExactly() { @@ -599,4 +590,78 @@ public static async Task ALegacySmallDateTime_ReadsBackExactly() Assert.Equal(minute, await connection.StoredProcedure(name).ExecuteOutputAsync("minute", Token)); Assert.Equal(new PostLegacyTimes(minute), await connection.StoredProcedure(name).ExecuteOutputAsync(Token)); } + + // A documented limit, not a goal: outputs are sent as datetime2, so a legacy datetime that stores .997 reads back as .9966667, + // where a row read of the same stored value gives .997 (docsite: expressive-commands.md). It is revisited if an opt-in is chosen. + [Fact] + public static async Task ALegacyDateTime_ReadsBackAsItsDateTime2Value_ADocumentedLimit() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = Procedure( + "@moment datetime = null output", + "set @moment = '2026-12-01T12:34:56.997';"); + await using SqlConnection connection = await OpenAsync(); + string name = "dbo." + procedure.Name; + var second = new DateTime(2026, 12, 1, 12, 34, 56); + + Assert.Equal(second.AddTicks(9966667), await connection.StoredProcedure(name).ExecuteOutputAsync("moment", Token)); + DateTime row = await connection + .Command("select cast('2026-12-01T12:34:56.997' as datetime)") + .ExecuteScalarAsync(Token); + Assert.Equal(second.AddMilliseconds(997), row); + + // The remedy: through SqlDateTime, the output is the row's value. + DateTime output = await connection.StoredProcedure(name).ExecuteOutputAsync("moment", Token); + Assert.Equal(row, new System.Data.SqlTypes.SqlDateTime(output).Value); + } + + // What a datetime output reads can be sent back in: an input of type datetime rounds it to the same stored tick. + [Fact] + public static async Task ALegacyDateTimeOutput_FedBackAsAnInput_LandsOnTheSameStoredTick() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch read = Procedure( + "@moment datetime = null output", + "set @moment = '2026-12-01T12:34:56.997';"); + using LocalDbFixture.Scratch compare = Procedure( + "@moment datetime, @same bit = null output", + "set @same = case when @moment = '2026-12-01T12:34:56.997' then 1 else 0 end;"); + await using SqlConnection connection = await OpenAsync(); + + DateTime output = await connection.StoredProcedure("dbo." + read.Name).ExecuteOutputAsync("moment", Token); + bool same = await connection + .StoredProcedure("dbo." + compare.Name) + .AddParam("moment", output) + .ExecuteOutputAsync("same", Token); + + Assert.True(same); + } + + public sealed record PostDates(DateOnly Day, TimeOnly Clock3, TimeOnly Clock7, DateOnly? NoDay, TimeOnly? NoClock); + + // DateOnly from date, TimeOnly from time(3) and time(7) (seven fraction digits: TimeOnly holds ticks, so exact), NULL into the + // nullable forms, each as a model member and as a named value. + [Fact] + public static async Task DateOnlyAndTimeOnly_ReadBackExactly() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = Procedure( + "@day date = null output, @clock3 time(3) = null output, @clock7 time(7) = null output, @no_day date = null output, @no_clock time(7) = null output", + "set @day = '2026-12-01'; set @clock3 = '12:34:56.789'; set @clock7 = '12:34:56.1234567'; set @no_day = null; set @no_clock = null;"); + await using SqlConnection connection = await OpenAsync(); + string name = "dbo." + procedure.Name; + var day = new DateOnly(2026, 12, 1); + TimeOnly clock3 = new TimeOnly(12, 34, 56).Add(TimeSpan.FromMilliseconds(789)); + TimeOnly clock7 = new TimeOnly(12, 34, 56).Add(TimeSpan.FromTicks(1234567)); + + PostDates model = await connection.StoredProcedure(name).ExecuteOutputAsync(Token); + Assert.Equal(new PostDates(day, clock3, clock7, null, null), model); + Assert.Equal(1234567, model.Clock7.Ticks % TimeSpan.TicksPerSecond); + + Assert.Equal(day, await connection.StoredProcedure(name).ExecuteOutputAsync("day", Token)); + Assert.Equal(clock3, await connection.StoredProcedure(name).ExecuteOutputAsync("clock3", Token)); + Assert.Equal(clock7, await connection.StoredProcedure(name).ExecuteOutputAsync("clock7", Token)); + Assert.Null(await connection.StoredProcedure(name).ExecuteOutputAsync("no_day", Token)); + Assert.Null(await connection.StoredProcedure(name).ExecuteOutputAsync("no_clock", Token)); + } } diff --git a/Tests/Open.Database.Extensions.Core.Tests/OutputParameterTests.cs b/Tests/Open.Database.Extensions.Core.Tests/OutputParameterTests.cs index 62c0602a..2702ef6f 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/OutputParameterTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/OutputParameterTests.cs @@ -47,7 +47,7 @@ public sealed record Renamed([property: Column("@post_count")] int Count); public sealed record Twice(int Total, [property: Column("total")] int Sum); - public sealed record WithDateOnly(DateOnly Day); + public sealed record DateAndTime(DateOnly Day, TimeOnly Clock, DateOnly? MaybeDay, TimeOnly? MaybeClock); public sealed record WithChars(char[] Code); @@ -338,6 +338,67 @@ public static async Task AnOutputThatNeverArrived_Throws_NeverReadsAsNull() Assert.Contains("NotMappedOnly.Count has no value after the command text ran", ex.Message); } + // "Not delivered" is decided before any value is converted: the model is never half built from what did arrive. + [Fact] + public static async Task NotDelivered_WinsOverAConversionFailure() + { + // CreatedUtc arrives as something a DateTime cannot read; Id never arrives (CLR null). + var c = new OutputConnection(Fill(("CreatedUtc", "not a date"))); + + var ex = await Assert.ThrowsAsync(async () => await c.StoredProcedure("dbo.AddPost").ExecuteOutputAsync(Token)); + Assert.Contains("NewPost.Id has no value after dbo.AddPost ran: the output parameter 'Id' was not delivered", ex.Message); + } + + // DateOnly goes as Date and TimeOnly as Time, nullable forms too, and is read back by RowMap's conversion. + [Fact] + public static async Task DateOnlyAndTimeOnly_AreSentAsDateAndTime_AndReadByTheRowConversion() + { + var c = new OutputConnection(Fill(("Day", new DateTime(2026, 12, 1)), ("Clock", new TimeSpan(12, 34, 56).Add(TimeSpan.FromTicks(1234567))), ("MaybeDay", DBNull.Value), ("MaybeClock", DBNull.Value))); + + DateAndTime model = await c.StoredProcedure("p").ExecuteOutputAsync(Token); + + Assert.Equal(new DateAndTime(new DateOnly(2026, 12, 1), new TimeOnly(12, 34, 56).Add(TimeSpan.FromTicks(1234567)), null, null), model); + OutputCommand command = c.Last!; + Assert.Equal(DbType.Date, command.Named("Day").DbType); + Assert.Equal(DbType.Time, command.Named("Clock").DbType); + Assert.Equal(DbType.Date, command.Named("MaybeDay").DbType); + Assert.Equal(DbType.Time, command.Named("MaybeClock").DbType); + + c = new OutputConnection(Fill(("day", new DateTime(2026, 12, 1)))); + Assert.Equal(new DateOnly(2026, 12, 1), await c.StoredProcedure("p").ExecuteOutputAsync("day", Token)); + Assert.Equal(DbType.Date, c.Last!.Named("day").DbType); + c = new OutputConnection(Fill(("clock", new TimeSpan(1, 2, 3)))); + Assert.Equal(new TimeOnly(1, 2, 3), await c.StoredProcedure("p").ExecuteOutputAsync("clock", Token)); + Assert.Equal(DbType.Time, c.Last!.Named("clock").DbType); + } + + // The documented remedy for a legacy datetime: through SqlDateTime, the value of datetime2 an output gives (.0033333, .0066667) + // is the value a row read gives (.003, .007). + [Theory] + [InlineData(0, 0)] + [InlineData(33333, 3)] + [InlineData(66667, 7)] + [InlineData(9966667, 997)] + public static void ASqlDateTime_GivesTheValueARowReadGives(int fractionTicks, int rowMilliseconds) + { + var output = new DateTime(2026, 12, 1, 12, 34, 56).AddTicks(fractionTicks); + var row = new DateTime(2026, 12, 1, 12, 34, 56).AddMilliseconds(rowMilliseconds); + + Assert.Equal(row, new System.Data.SqlTypes.SqlDateTime(output).Value); + } + + // The hint names a call that works for the type that reached it. + [Fact] + public static void APrecisionOnAModelType_PointsToTheModelForm_NotToTheNamedForm() + { + ThrowsAtTheCall( + c => c.StoredProcedure("p").ExecuteOutputAsync("id", 19, 4, Token), + "Only a decimal output takes a precision and scale; NewPost needs none", + "NewPost is a model; call ExecuteOutputAsync() without a name"); + ThrowsAtTheCall( + c => c.StoredProcedure("p").ExecuteOutputAsync("code", 19, 4, Token), + "IntPtr has no database type for an output"); + } [Fact] public static async Task NullIsNull_InANullableMember_AndAnErrorInANonNullableOne() { @@ -384,10 +445,6 @@ public static void AModelThatCannotBeRead_ThrowsAtTheCall() c => c.StoredProcedure("p").ExecuteOutputAsync(Token), "NoMembers has no member to read an output parameter into", "Give it a public settable property or a constructor parameter"); - ThrowsAtTheCall( - c => c.StoredProcedure("p").ExecuteOutputAsync(Token), - "WithDateOnly.Day is DateOnly, which has no database type", - "Change WithDateOnly.Day to a type that has one"); ThrowsAtTheCall( c => c.StoredProcedure("p").ExecuteOutputAsync(Token), "WithChars.Code is Char[], which has no database type"); @@ -436,8 +493,8 @@ public static void TheNamedForm_TakesOneValueOfAType_ThatNeedsNoDeclaration() "The output parameter 'total' is read as Decimal", "ExecuteOutputDecimalAsync(\"total\", 19, 4)"); ThrowsAtTheCall( - c => c.StoredProcedure("p").ExecuteOutputAsync("day", Token), - "The output parameter 'day' is read as DateOnly, which has no database type", + c => c.StoredProcedure("p").ExecuteOutputAsync("code", Token), + "The output parameter 'code' is read as IntPtr, which has no database type", "Read it as a type that has one"); } diff --git a/docsite/articles/expressive-commands.md b/docsite/articles/expressive-commands.md index c08978a3..bec120a5 100644 --- a/docsite/articles/expressive-commands.md +++ b/docsite/articles/expressive-commands.md @@ -196,7 +196,7 @@ NewPost created = await db.StoredProcedure("dbo.AddPost") - **Names.** A member finds its parameter as `AddParam(value)` does: through the four tiers when the names are known (a procedure's, or a text's `@name` markers, so `exec dbo.AddPost @id output` works too), else under its own name. `[Column("name")]` names the parameter exactly. A member that matches no parameter, or two members on one parameter, throw `InvalidOperationException` before the command runs. - **Direction.** A member whose parameter got a value (`AddParam`, `AddParams`) is sent as InputOutput; any other as Output. - **Return code.** A member named `ReturnValue` reads a stored procedure's return code. On a text command it throws, and so does a procedure that declares a parameter that name would also match: name that member with `[Column]`. -- **Types.** A `DateTime` is sent as `datetime2`; a `string` or `byte[]` with size -1, so the whole value comes back. A `decimal` needs `[Column(TypeName = "decimal(10,2)")]` (positional records: `[property: Column(...)]`); without it the call throws before it runs. +- **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 `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. - **Not delivered.** An Output parameter still empty after the call means the response never completed: the call throws `InvalidOperationException`, never a NULL. @@ -207,7 +207,7 @@ There is no blocking form. Known limits: - An InputOutput parameter whose outputs never arrive keeps the value sent: that case cannot be told from a real answer. - 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`. - SqlClient reports an error after the outputs are set, and a cancel while the command runs, with its own `SqlException`. -- A `DateTime` output is read through `datetime2`, so a legacy `datetime` arrives as its exact stored value (`.997` as `.9966667`). A `DateOnly` or `TimeOnly` member has no database type for an output and throws before the call runs. +- **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. ## Terminals diff --git a/docsite/articles/mapping.md b/docsite/articles/mapping.md index 6c684ce1..15410158 100644 --- a/docsite/articles/mapping.md +++ b/docsite/articles/mapping.md @@ -239,7 +239,7 @@ To switch the generator off for a project (the setting applies to the project it The [generator's README](https://github.com/Open-NET-Libraries/Open.Database.Extensions/blob/master/Source/Generator/README.md) lists what is left to the runtime map. -Output parameters read into a model (`ExecuteOutputAsync()`, see [Output parameters](expressive-commands.md#output-parameters)) follow the rules of this page: each member is matched to a parameter and the model is built as from a row, always by the runtime map, never a generated reader. Two things apply only there: a `decimal` member needs `[Column(TypeName = "decimal(p,s)")]` for the precision and scale it is sent with, and a `DateTime` member is sent as `DbType.DateTime2`. +Output parameters read into a model (`ExecuteOutputAsync()`, see [Output parameters](expressive-commands.md#output-parameters)) follow the rules of this page: each member is matched to a parameter and the model is built as from a row, always by the runtime map, never a generated reader. Two things apply only there: a `decimal` member needs `[Column(TypeName = "decimal(p,s)")]` for the precision and scale it is sent with, a `DateTime` member is sent as `DbType.DateTime2`, a `DateOnly` as `DbType.Date` and a `TimeOnly` as `DbType.Time`. ## Types and NULL From dab8030c93bb595c4c6d5903fe1d9d9d3b83c496 Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Tue, 1 Dec 2026 20:30:33 -0800 Subject: [PATCH 06/20] Narrow the obsolete-member exemption to the four chain overloads, and note the byte-zero call. TheCorePackage_ShipsNothingObsolete now exempts only the AddParam/AddParamIf compile-error overloads on ExpressiveCommandBase and asserts there are exactly four, so any other obsolete member still fails it. The release notes say that AddParam(name, (byte)0) on the SQL Server command, which used to bind silently to the direction overload, is now an ambiguous-call error, and what to write instead. The derived-name test is renamed to say what it checks: the chain sets no direction, so a parameter keeps the provider's default. Co-Authored-By: Claude Opus 5.5 --- .../DerivedParameterNameTests.cs | 4 ++-- .../RemovedMembersTests.cs | 18 ++++++++++++++++-- docsite/articles/release-notes.md | 2 +- 3 files changed, 19 insertions(+), 5 deletions(-) diff --git a/Tests/Open.Database.Extensions.Core.Tests/DerivedParameterNameTests.cs b/Tests/Open.Database.Extensions.Core.Tests/DerivedParameterNameTests.cs index b2c00b4d..a5a42423 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/DerivedParameterNameTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/DerivedParameterNameTests.cs @@ -954,9 +954,9 @@ public static void AddParams_MixesWithDerivedAndNamedParams_InAnyOrder() Assert.Equal(new Dictionary { ["@mode"] = 1, ["@company_serial_num"] = 42, ["@region"] = "west", ["@limit"] = 10 }, Sent(probe)); } - // A name that is derived from the argument is still an input: no direction is set on it, before or after its real name is known. + // A name that is derived from the argument gets no direction from the chain, before or after its real name is known: it keeps the provider's default. [Fact] - public static void AnArgumentNamedByItsExpression_IsSentAsAnInput() + public static void AnArgumentNamedByItsExpression_KeepsTheProvidersDefaultDirection() { var recorder = new RecordingDbCommand(); const int orderId = 5; diff --git a/Tests/Open.Database.Extensions.Core.Tests/RemovedMembersTests.cs b/Tests/Open.Database.Extensions.Core.Tests/RemovedMembersTests.cs index 2c8c7ff0..b0f9c84a 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/RemovedMembersTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/RemovedMembersTests.cs @@ -16,17 +16,31 @@ public static class RemovedMembersTests public static void TheCorePackage_ShipsNothingObsolete() { var obsolete = new List(); + int chainTraps = 0; foreach (Type type in typeof(CoreExtensions).Assembly.GetExportedTypes()) { if (type.GetCustomAttribute() is not null) obsolete.Add(type.FullName!); foreach (MemberInfo member in type.GetMembers(All)) { + if (member.GetCustomAttribute() is not { } attribute) continue; + // The four chain overloads that would otherwise rebind silently are compile errors, kept on purpose (see ChainTrapOverloadTests). - if (member.GetCustomAttribute() is { IsError: false }) - obsolete.Add($"{type.FullName}.{member.Name}"); + if (attribute.IsError && IsChainTrap(type, member)) + { + chainTraps++; + continue; + } + + obsolete.Add($"{type.FullName}.{member.Name}"); } } Assert.Empty(obsolete); + Assert.Equal(4, chainTraps); } + + static bool IsChainTrap(Type type, MemberInfo member) + => type.IsGenericTypeDefinition + && type.Name.StartsWith("ExpressiveCommandBase`", StringComparison.Ordinal) + && member.Name is "AddParam" or "AddParamIf"; } diff --git a/docsite/articles/release-notes.md b/docsite/articles/release-notes.md index 6738eca2..2f15a92f 100644 --- a/docsite/articles/release-notes.md +++ b/docsite/articles/release-notes.md @@ -9,7 +9,7 @@ Version 11 is `11.0.0-rc.16`. For moving a 10.x codebase, read [Coming from earl - **Generated row readers for `DbQuery` too.** A plain `Map()` on a `DbQuery`, a `DbQuery` or a query bound with `Using` now gets its row reader written at build time, as on a command or a reader; before, it used the runtime map. The runtime map's conversions are therefore no longer applied there: see [Generated readers](mapping.md#generated-readers) for the differences and the switch. - **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. 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. `Param` has no `direction` constructor parameter and no `Direction` property. +- **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. 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). ### Changes since rc.15 From 590948b560a8043a7a2924c6b5ce19462fb2252b Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Tue, 1 Dec 2026 21:02:13 -0800 Subject: [PATCH 07/20] Output parameters: review fixes in docs, messages, tests and analyzer findings. Documents the placeholder-null InputOutput limit, the removed three-argument direction forms, that ValueMappingException is thrown after the command ran, the ReturnValue name in the named forms and the synchronous cancel check. Renames the decimal refusal member, names the call in the no-match message, builds the ambiguity fix text only when it throws, and removes the unused MatchBare. Tests: conversion-vs-not-delivered ordering, char outputs, the cancel-during SqlException, and the analyzer and style findings (CA2012, CA1822, xUnit1045, IDE0022, IDE0032, IDE0056, IDE0057, CA2012 in the decimal form). Co-Authored-By: Claude Sonnet 5.5 --- Source/Core/Core/RowMap.cs | 22 ++--- Source/Core/ExpressiveCommandBase.Output.cs | 75 +++++++++++------ Source/Core/ExpressiveCommandBase.cs | 1 - Source/Core/NameSet.cs | 7 +- Source/Core/OutputLayout.cs | 20 ++--- Source/Core/ParameterNames.cs | 22 ++--- .../AllocationQuickWinTests.cs | 10 +-- .../ChainTrapOverloadTests.cs | 23 +++-- .../OutputParameterLocalDbTests.cs | 53 +++++++++--- .../OutputParameterTests.cs | 84 ++++++++++--------- .../ParameterNameAddParamsTests.cs | 8 +- .../SqlServerParameterTypeTests.cs | 4 +- docsite/articles/expressive-commands.md | 3 +- docsite/articles/release-notes.md | 2 +- docsite/articles/whats-new-11.md | 2 +- 15 files changed, 190 insertions(+), 146 deletions(-) diff --git a/Source/Core/Core/RowMap.cs b/Source/Core/Core/RowMap.cs index 479bd40c..bac1c832 100644 --- a/Source/Core/Core/RowMap.cs +++ b/Source/Core/Core/RowMap.cs @@ -132,7 +132,7 @@ public RowMap(params ReadOnlySpan> mappings) { // A model type that cannot be mapped fails here, at the call, not when the first row is read. ThrowIfUnmappable(); - _slots = ModelSlots; + _slots = MappedSlots; _slotIndex = ModelSlotIndex; // slot → column, in slot order; a slot reads the column its member declares ([Column(Name)]), else the column of its own name, unless a pair says otherwise. @@ -459,7 +459,7 @@ RowMap Converting( // The statics below are one immutable copy per model type: see TypeShape. // Never throws: an unmappable T holds its error, so no static initializer here can fail with it. - // The per-model-type statics (TypeShape, ModelSlots, ModelSlotIndex, Default) are one immutable copy per T, built once. + // The per-model-type statics (TypeShape, MappedSlots, ModelSlotIndex, Default) are one immutable copy per T, built once. // Any cache of compiled readers keyed by model type lives as long and costs a lookup per call; a static on the generic type is the cheapest place for it. // Nothing that does not depend on T belongs here. /// @@ -479,18 +479,12 @@ RowMap Converting( static readonly SlotTable Model = BuildSlots(); /// - /// What a column can feed: one slot per parameter of the constructor the model is built through + /// What a column can feed, and what the output model of a command (OutputLayout) reads: one slot per parameter of the constructor the model is built through /// (none for a model built as it always was), then one per settable public instance property no parameter covers, /// in declaration order (a property hidden by name keeps the first). /// - static readonly ImmutableArray ModelSlots = Model.Slots; - - /// - /// Gets the slots of , for the output model of a command (OutputLayout), whose members are exactly the ones a row would feed. - /// - /// The slots; none when cannot be mapped. [SuppressMessage("Roslynator", "RCS1158:Static member in generic type should use a type parameter", Justification = "They are this T's slots: the type parameter names which T (RowMap.MappedSlots).")] - internal static ImmutableArray MappedSlots => ModelSlots; + internal static ImmutableArray MappedSlots { get; } = Model.Slots; /// /// Why cannot be mapped (its shape, else a contradiction in what its members declare), or when it can. @@ -772,8 +766,8 @@ static void AddParameterSlots(ConstructorInfo constructor, List list, Hash static bool MustHaveColumn(PropertyInfo property) => !TypeShape.SetsRequiredMembers && Shape.IsRequired(property); // Static initializers run in textual order; each must follow what it uses. - /// The index of by name. - static readonly FrozenDictionary ModelSlotIndex = BuildSlotIndex(ModelSlots); + /// The index of by name. + static readonly FrozenDictionary ModelSlotIndex = BuildSlotIndex(MappedSlots); static FrozenDictionary BuildSlotIndex(ImmutableArray slots) { @@ -790,7 +784,7 @@ public static RowMap Default { // Null when T cannot be mapped, so reading Default throws instead of a static initializer failing. get => field ?? throw (TypeError is not null ? new InvalidOperationException(TypeError) : new ArgumentException(PolicyError)); - } = TypeError is null && PolicyError is null ? new() : null; // Declared after TypeShape, ModelSlots and ModelSlotIndex: its constructor reads them. + } = TypeError is null && PolicyError is null ? new() : null; // Declared after TypeShape, MappedSlots and ModelSlotIndex: its constructor reads them. /// /// Throws when cannot be mapped. @@ -807,7 +801,7 @@ internal static void ThrowIfUnmappable() if (PolicyError is not null) throw new ArgumentException(PolicyError); } - /// What this map's columns can feed: the model's own slots (ModelSlots), or the parameters of its factory (From(factory, pairs)). + /// What this map's columns can feed: the model's own slots (MappedSlots), or the parameters of its factory (From(factory, pairs)). readonly ImmutableArray _slots; /// The slots by name. readonly FrozenDictionary _slotIndex; diff --git a/Source/Core/ExpressiveCommandBase.Output.cs b/Source/Core/ExpressiveCommandBase.Output.cs index 1af7245e..f7769804 100644 --- a/Source/Core/ExpressiveCommandBase.Output.cs +++ b/Source/Core/ExpressiveCommandBase.Output.cs @@ -5,7 +5,7 @@ namespace Open.Database.Extensions; // A call that reads output parameters passes its OutputRun as the state of the run, and the run recognizes it by its type: // the build step resolves the run's members with the names and PrepareCommand adds their parameters. A call without // outputs pays one compare of its state's type (typeof, never 'state is', which boxes a value-type state in unoptimized -// code: ToListArrayAllocationProbe saw it). The run is never kept on the command. +// code). The run is never kept on the command. public abstract partial class ExpressiveCommandBase where TConnection : class, IDbConnection where TCommand : class, IDbCommand @@ -23,19 +23,20 @@ public abstract partial class ExpressiveCommandBaseMap<TOut>() would read is an output parameter, built by the same rules (constructors, records, /// required, conversion, [NullPolicy], [NullValue], [NotMapped]). /// A member is matched to the parameter the way AddParam(value) is: when the names are known (a procedure's, or the - /// @name markers of a text) by the same four tiers, and a member that matches none throws; otherwise it is sent under its own name. + /// @name markers of a text) by the same tiers (exact, ignoring case, ignoring case and underscores, then after a common prefix such as p_ is removed from the parameter's name), and a member that matches none throws; otherwise it is sent under its own name. /// [Column("name")] names the parameter exactly. /// /// /// A member whose parameter was given a value (AddParam, AddParams) is sent as /// , any other as , which sends NULL: /// a procedure's default for that parameter is not used. - /// A member named ReturnValue reads a stored procedure's return code. + /// A parameter added with a null value is sent as InputOutput too, so a lost output cannot be told from a NULL: add no value for a pure output, only when the procedure reads it. + /// A member named ReturnValue reads a stored procedure's return code. (In the named forms, "ReturnValue" names a declared parameter: the return code is .) /// /// /// A is sent as ; a or array with size -1 (the whole value); - /// a needs [Column(TypeName = "decimal(p,s)")], whose scale also rounds a value sent in. - /// A member of a read from a legacy datetime can differ from a row's in the last digit (see the article on expressive commands). + /// a needs [Column(TypeName = "decimal(p,s)")]; the declared scale also rounds a value sent in. + /// A member of a read from a legacy datetime can differ from a row's in the last digits of its fraction (.997 reads back as .9966667; see the article on expressive commands). /// /// /// To read one value instead of a model, name it: . @@ -54,9 +55,9 @@ public abstract partial class ExpressiveCommandBaseReturnValue member would also match. /// After: the output parameters were not delivered (the response did not complete). /// - /// A value does not convert to its member, or is NULL and the member does not take it. + /// After the command has run, so its effects have happened: a value does not convert to its member, or is NULL and the member does not take it. /// - /// The command's token or is canceled. + /// The command's token or is canceled; one already canceled throws before a task is returned. /// public ValueTask ExecuteOutputAsync( CancellationToken cancellationToken = default) @@ -91,7 +92,7 @@ static async (cmd, _, run) => /// /// names the parameter exactly, with or without its @ and in any case; "ReturnValue" names a declared parameter, /// not the return code (that is ). - /// A value added under the same name makes it . + /// A value added under the same name makes it (a null value too: then a lost output cannot be told from a NULL, so add no value for a pure output, only when the procedure reads it). /// /// /// The value converts as Map<T>() converts a single column; NULL is only when takes it. @@ -112,9 +113,9 @@ static async (cmd, _, run) => /// Before the command executes: the names are known and none is . /// After: the output parameter was not delivered (the response did not complete). /// - /// The value does not convert to , or is NULL and is a non-nullable value type. + /// After the command has run, so its effects have happened: the value does not convert to , or is NULL and is a non-nullable value type. /// - /// The command's token or is canceled. + /// The command's token or is canceled; one already canceled throws before a task is returned. /// public ValueTask ExecuteOutputAsync( string name, @@ -139,7 +140,7 @@ public ValueTask ExecuteOutputAsync( /// /// /// Otherwise as : names the parameter exactly, - /// and a value added under the same name makes it . + /// and a value added under the same name makes it (a null value too: then a lost output cannot be told from a NULL, so add no value for a pure output, only when the procedure reads it). "ReturnValue" names a declared parameter, not the return code (that is ). /// NULL is in a of and an error in a . /// /// @@ -175,9 +176,9 @@ public ValueTask ExecuteOutputAsync( /// Before the command executes: the names are known and none is . /// After: the output parameter was not delivered (the response did not complete). /// - /// The value does not convert to , or is NULL and is . + /// After the command has run, so its effects have happened: the value does not convert to , or is NULL and is . /// - /// The command's token or is canceled. + /// The command's token or is canceled; one already canceled throws before a task is returned. /// public ValueTask ExecuteOutputAsync( string name, @@ -192,12 +193,32 @@ public ValueTask ExecuteOutputAsync( // T is decimal? or decimal, and the arguments are checked: the run is the one ExecuteOutputDecimalAsync makes after its own guard. // Each cast goes through object to the same type, which the JIT removes in optimized code. - ValueTask value = RunNamedAsync(OutputValue.Shaped(name, precision, scale), cancellationToken); - return typeof(T) == typeof(decimal?) - ? (ValueTask)(object)value - : (ValueTask)(object)NotNullAsync(name, value); + if (typeof(T) == typeof(decimal?)) + { + return Same(RunNamedAsync(OutputValue.Shaped(name, precision, scale), cancellationToken)); + } + + return Same(NotNullAsync(name, RunNamedAsync(OutputValue.Shaped(name, precision, scale), cancellationToken))); } + /// + /// Casts a task of a of to a task of , which the caller has checked is that type. + /// + /// The type: a of . + /// The task. + /// The same task. + static ValueTask Same(ValueTask value) + => (ValueTask)(object)value; + + /// + /// Casts a task of a to a task of , which the caller has checked is that type. + /// + /// The type: . + /// The task. + /// The same task. + static ValueTask Same(ValueTask value) + => (ValueTask)(object)value; + /// /// Awaits a decimal output parameter that a reads: NULL is an error. /// @@ -254,9 +275,9 @@ static async ValueTask NotNullAsync(string name, ValueTask va /// Before the command executes: the names are known and none is . /// After: the output parameter was not delivered (the response did not complete). /// - /// The value does not convert to a . + /// After the command has run, so its effects have happened: the value does not convert to a . /// - /// The command's token or is canceled. + /// The command's token or is canceled; one already canceled throws before a task is returned. /// public ValueTask ExecuteOutputDecimalAsync( string name, @@ -370,8 +391,8 @@ void ThrowUnlessProcedure(OutputLayout layout) } throw new InvalidOperationException( - $"{display} reads a stored procedure's return code, but the command is not a stored procedure (it is {Type}), and a text batch's return code is always 0. " - + "Call the procedure as CommandType.StoredProcedure, or read an output parameter (@name OUTPUT) into a member of another name."); + $"{display} reads a stored procedure's return code, but the command is not a stored procedure (it is {Type}), and a command of another type has no return code to read: the provider reports 0. " + + "Set CommandType.StoredProcedure to call a procedure, or read an output parameter (declared @name OUTPUT in the text) into a member of another name."); } /// @@ -409,11 +430,10 @@ void ResolveOutputs(OutputRun run, NameSet? names) for (int i = 0; i < resolved.Length; i++) { OutputMember member = layout.Members[i]; - string fix = $"Name its parameter exactly with [Column(\"name\")] on {member.Display}."; if (member.IsReturnValue) { // Only a stored procedure gets here (checked at the call): no declared parameter may also answer to the name. - if (known && real!.Match(OutputLayout.ReturnValue, Command, member.Display, fix) is { } declared) + if (known && real!.Match(OutputLayout.ReturnValue, Command, member.Display) is { } declared) { throw new InvalidOperationException( $"{member.Display} reads the return code, but {where} also declares the parameter '{declared}', which the name {OutputLayout.ReturnValue} matches, so it is unclear which one to read. " @@ -429,7 +449,7 @@ void ResolveOutputs(OutputRun run, NameSet? names) continue; } - resolved[i] = (member.Exact ? real!.Find(member.Name)?.Real : real!.Match(member.Name, Command, member.Display, fix)) + resolved[i] = (member.Exact ? real!.Find(member.Name)?.Real : real!.Match(member.Name, Command, member.Display)) ?? throw NoOutputMatch(member, layout, real.Names, where); } @@ -455,9 +475,14 @@ static InvalidOperationException NoOutputMatch(OutputMember member, OutputLayout string declared = string.Join(", ", real); if (layout.IsNamed) { + // A decimal reaches here through the form that takes a precision and scale; any other type through the plain named form. + string call = member.Wire!.Type == DbType.Decimal + ? "Pass one of those names to ExecuteOutputAsync(name, precision, scale) or ExecuteOutputDecimalAsync(name, precision, scale)" + : "Pass one of those names to ExecuteOutputAsync(name)"; + return new( $"{member.Display} is not a parameter of {where}, which declares: {declared}. " - + "Pass one of those names to ExecuteOutputAsync(name), or add the parameter to the procedure (or its @name marker to the text)."); + + call + ", or add the parameter to the procedure (or its @name marker to the text)."); } if (member.Exact) diff --git a/Source/Core/ExpressiveCommandBase.cs b/Source/Core/ExpressiveCommandBase.cs index 1567cdd4..2bc577b2 100644 --- a/Source/Core/ExpressiveCommandBase.cs +++ b/Source/Core/ExpressiveCommandBase.cs @@ -947,7 +947,6 @@ TCommand PrepareDerived(TConnection connection, NameSet? names, bool written = f { // Taken out of the spare slot, so a hook that sets up another // command on this thread builds its own list. - // A call that only reads output parameters added none. List send = _spareList ?? new(_params?.Count ?? 0); _spareList = null; object? outerCommand = _preparing; diff --git a/Source/Core/NameSet.cs b/Source/Core/NameSet.cs index d54230e8..26795a07 100644 --- a/Source/Core/NameSet.cs +++ b/Source/Core/NameSet.cs @@ -121,16 +121,15 @@ Dictionary BuildEntries() /// The real name that the argument expression stands for, or when it matches none. /// /// - /// The answer is remembered. An ambiguity throws (see ) and is not remembered, so it throws on every call. + /// The answer is remembered. An ambiguity throws (see ) and is not remembered, so it throws on every call. /// /// The text of the argument, or the name of a member of an AddParams object. /// The procedure's name or the command text, for the message of an ambiguity. /// What matches, for the message of an ambiguity; names the argument. - /// The fix, for the message of an ambiguity; for AddParam("name", value). /// The real name, or when the expression matches none. /// The expression is not derivable. /// The expression fits more than one name equally well. - internal string? Match(string expression, string procedure, string? subject = null, string? fix = null) + internal string? Match(string expression, string procedure, string? subject = null) { if (_matches.TryGetValue(expression, out string? remembered)) return remembered; @@ -138,7 +137,7 @@ Dictionary BuildEntries() ImmutableArray candidates = ParameterNames.Describe(expression)?.Candidates ?? ParameterNames.Candidates(expression); // Two threads may both match and store: the answer is the same. - string? found = ParameterNames.MatchBareAs(candidates, Names, BareNames, expression, procedure, subject, fix); + string? found = ParameterNames.MatchBareAs(candidates, Names, BareNames, expression, procedure, subject); if (_matches.Count < MaxMatches) _matches[expression] = found; return found; diff --git a/Source/Core/OutputLayout.cs b/Source/Core/OutputLayout.cs index fd5f1f10..72ac2a89 100644 --- a/Source/Core/OutputLayout.cs +++ b/Source/Core/OutputLayout.cs @@ -186,12 +186,12 @@ public static bool IsDecimalShape(byte precision, byte scale) string text = typeName.Trim(); int open = text.IndexOf('('); - if (open < 0 || text[text.Length - 1] != ')') return null; + if (open < 0 || text[^1] != ')') return null; - string kind = text.Substring(0, open).Trim(); + string kind = text[..open].Trim(); if (!kind.Equals("decimal", StringComparison.OrdinalIgnoreCase) && !kind.Equals("numeric", StringComparison.OrdinalIgnoreCase)) return null; - string[] parts = text.Substring(open + 1, text.Length - open - 2).Split(','); + string[] parts = text[(open + 1)..^1].Split(','); return parts.Length == 2 && byte.TryParse(parts[0].Trim(), NumberStyles.None, CultureInfo.InvariantCulture, out byte precision) && byte.TryParse(parts[1].Trim(), NumberStyles.None, CultureInfo.InvariantCulture, out byte scale) @@ -426,8 +426,8 @@ enum OutputValueRefusal /// The type is a model, not a single value. NotScalar, - /// A decimal, whose precision and scale the named form cannot declare. - Decimal, + /// A decimal: the named form without a precision and scale refuses it, and the form that takes them accepts only this. + DecimalNeedsShape, /// The type has no database type. NoDbType, @@ -463,7 +463,7 @@ public static OutputLayout Get(string name) /// is not a . public static void ThrowUnlessDecimal(string name) { - if (Reason == OutputValueRefusal.Decimal) return; + if (Reason == OutputValueRefusal.DecimalNeedsShape) return; string shown = Shape.TypeName(typeof(T)); string fix = Reason switch @@ -477,7 +477,7 @@ public static void ThrowUnlessDecimal(string name) }; throw new InvalidOperationException( - $"Only a decimal output takes a precision and scale; {shown} needs none (date and time outputs keep full precision). {fix}"); + $"Only a decimal output takes a precision and scale; {shown} needs none. {fix}"); } /// @@ -489,7 +489,7 @@ public static void ThrowUnlessDecimal(string name) /// The layout; is checked by the caller, which has called . public static OutputLayout Shaped(string name, byte precision, byte scale) { - Debug.Assert(Reason == OutputValueRefusal.Decimal); + Debug.Assert(Reason == OutputValueRefusal.DecimalNeedsShape); string display = $"The output parameter '{name}'"; return new(new OutputMember(name, exact: true, name, new OutputWire(DbType.Decimal, 0, precision, scale), display)); } @@ -502,7 +502,7 @@ static string Message(string name, string display) OutputValueRefusal.NotScalar => $"ExecuteOutputAsync<{shown}>(\"{name}\") reads one value, but {shown} is a model, not a single value. " + $"Call ExecuteOutputAsync<{shown}>() without a name to read its members, or read '{name}' as a single-value type {OutputWire.SupportedTypes}.", - OutputValueRefusal.Decimal + OutputValueRefusal.DecimalNeedsShape => $"{display} is read as {shown}. A decimal output needs its precision and scale, or the server rounds it to a whole number. " + $"Use ExecuteOutputAsync(\"{name}\", 19, 4) or ExecuteOutputDecimalAsync(\"{name}\", 19, 4) with the column's precision and scale.", _ @@ -522,7 +522,7 @@ static string Message(string name, string display) if ((Nullable.GetUnderlyingType(type) ?? type) == typeof(decimal)) { - reason = OutputValueRefusal.Decimal; + reason = OutputValueRefusal.DecimalNeedsShape; return null; } diff --git a/Source/Core/ParameterNames.cs b/Source/Core/ParameterNames.cs index 6ad133fc..8fab9fad 100644 --- a/Source/Core/ParameterNames.cs +++ b/Source/Core/ParameterNames.cs @@ -14,7 +14,7 @@ namespace Open.Database.Extensions; /// A last member that carries a field prefix (m_author, s_author, _author) also offers its name without the prefix, right after the name as written. /// // A wrong name that silently binds is worse than an error that says to pass the name, so only plain member chains are derived. -// A candidate is matched to the real parameter names in four tiers, each candidate in its turn (see MatchBare). +// A candidate is matched to the real parameter names in four tiers, each candidate in its turn (see MatchBareAs): exact, ignoring case, ignoring case and underscores, then those after one common parameter prefix such as p_ is removed from the real name. static class ParameterNames { /// @@ -295,29 +295,19 @@ static bool ClosesAt(string s, int open, int close) /// (p_, in_, i_, prm_, par_ or v_ in any case, or a lone lower-case p before an upper-case letter): /// author finds @p_author and @pAuthor, but ages never finds @pages. /// - /// The candidates from . - /// The real names as the provider reports them (a leading @ is allowed). - /// The same names without a leading @. - /// The text of the argument, for the message of an ambiguity. - /// The procedure's name, for the message of an ambiguity. /// The real name as the provider reported it, or when no candidate matches any parameter. /// One candidate matches more than one parameter at the same tier. - internal static string? MatchBare(ImmutableArray candidates, ImmutableArray parameterNames, ImmutableArray bareNames, string expression, string procedure) - => MatchBareAs(candidates, parameterNames, bareNames, expression, procedure, null, null); - - /// /// The candidates from . /// The real names as the provider reports them (a leading @ is allowed). /// The same names without a leading @. /// 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. - /// The fix, for the message of an ambiguity; for AddParam("name", value). - internal static string? MatchBareAs(ImmutableArray candidates, ImmutableArray parameterNames, ImmutableArray bareNames, string expression, string procedure, string? subject, string? fix) + internal static string? MatchBareAs(ImmutableArray candidates, ImmutableArray parameterNames, ImmutableArray bareNames, string expression, string procedure, string? subject) { foreach (string candidate in candidates) { - if (Find(expression, procedure, candidate, parameterNames, bareNames, subject, fix) is { } found) return found; + if (Find(expression, procedure, candidate, parameterNames, bareNames, subject) is { } found) return found; } return null; @@ -337,7 +327,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, string? fix) + static string? Find(string expression, string procedure, string candidate, ImmutableArray parameterNames, ImmutableArray bareNames, string? subject) { // 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++) @@ -352,7 +342,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)}. {fix ?? "Name the parameter explicitly: AddParam(\"name\", value)."}"); + + $"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}.")}"); } found = real; @@ -472,7 +462,7 @@ internal enum ScanResult /// The candidates from . /// The marker as the text spells it, with its @, when . /// How the scan ended. - // The same answer as MatchBare over the tokens of SqlTextParameters.Parse (the same candidates in the same order, + // The same answer as MatchBareAs over the tokens of SqlTextParameters.Parse (the same candidates in the same order, // the same four tiers, a marker repeated in another case being one name, as first written), and allocates nothing. internal static ScanResult Scan(string text, ImmutableArray candidates, out ReadOnlySpan real) { diff --git a/Tests/Open.Database.Extensions.Core.Tests/AllocationQuickWinTests.cs b/Tests/Open.Database.Extensions.Core.Tests/AllocationQuickWinTests.cs index 389c95d5..52065eff 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/AllocationQuickWinTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/AllocationQuickWinTests.cs @@ -248,7 +248,7 @@ public static void ToDictionary_ANullMapping_ThrowsArgumentNull() Assert.Throws(() => record.ToDictionary((IEnumerable)null!)); } - // ---- ParameterNames.MatchBare: the @ of the real names is removed once per call, not once per name, candidate and tier ---- + // ---- ParameterNames.MatchBareAs: the @ of the real names is removed once per call, not once per name, candidate and tier ---- static readonly Type ParameterNamesType = typeof(DataRecordExtensions).Assembly.GetType("Open.Database.Extensions.ParameterNames", throwOnError: true)!; @@ -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?> MatchBare = ParameterNamesType - .GetMethod("MatchBare", BindingFlags.Static | BindingFlags.NonPublic)! - .CreateDelegate, ImmutableArray, ImmutableArray, string, string, string?>>(); + static readonly Func, ImmutableArray, ImmutableArray, string, string, string?, string?> MatchBare = ParameterNamesType + .GetMethod("MatchBareAs", BindingFlags.Static | BindingFlags.NonPublic)! + .CreateDelegate, ImmutableArray, ImmutableArray, 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"); + static string? Match(ImmutableArray candidates, ImmutableArray parameterNames) => MatchBare(candidates, parameterNames, BareNames(parameterNames), "argument", "dbo.procedure", null); static readonly ImmutableArray RealNames = [ diff --git a/Tests/Open.Database.Extensions.Core.Tests/ChainTrapOverloadTests.cs b/Tests/Open.Database.Extensions.Core.Tests/ChainTrapOverloadTests.cs index 915d8132..6a6bcb83 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/ChainTrapOverloadTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/ChainTrapOverloadTests.cs @@ -12,18 +12,23 @@ static MethodInfo Find(string name, params Type[] parameters) => typeof(ExpressiveCommand).GetMethod(name, parameters) ?? throw new InvalidOperationException($"{name} with {parameters.Length} parameters was not found."); - public static TheoryData Shapes => new() - { - { "AddParam", [typeof(string), typeof(ParameterDirection)], ["o", ParameterDirection.Output] }, - { "AddParamIf", [typeof(bool), typeof(string), typeof(ParameterDirection)], [true, "o", ParameterDirection.Output] }, - { "AddParam", [typeof(string), typeof(DbType)], ["x", DbType.Int32] }, - { "AddParamIf", [typeof(bool), typeof(string), typeof(DbType)], [true, "x", DbType.Int32] }, - }; + // The theory takes an index: a Type[] is not serializable, so a case holding one cannot be enumerated individually. + static readonly (string Name, Type[] Parameters, object?[] Arguments)[] Shapes = + [ + ("AddParam", [typeof(string), typeof(ParameterDirection)], ["o", ParameterDirection.Output]), + ("AddParamIf", [typeof(bool), typeof(string), typeof(ParameterDirection)], [true, "o", ParameterDirection.Output]), + ("AddParam", [typeof(string), typeof(DbType)], ["x", DbType.Int32]), + ("AddParamIf", [typeof(bool), typeof(string), typeof(DbType)], [true, "x", DbType.Int32]), + ]; [Theory] - [MemberData(nameof(Shapes))] - public static void TheShape_IsAnObsoleteError_AndThrowsWhenInvoked(string name, Type[] parameters, object?[] arguments) + [InlineData(0)] + [InlineData(1)] + [InlineData(2)] + [InlineData(3)] + public static void TheShape_IsAnObsoleteError_AndThrowsWhenInvoked(int shape) { + (string name, Type[] parameters, object?[] arguments) = Shapes[shape]; MethodInfo method = Find(name, parameters); ObsoleteAttribute obsolete = Assert.IsType(Assert.Single(method.GetCustomAttributes(typeof(ObsoleteAttribute), false))); diff --git a/Tests/Open.Database.Extensions.Core.Tests/OutputParameterLocalDbTests.cs b/Tests/Open.Database.Extensions.Core.Tests/OutputParameterLocalDbTests.cs index e2cb828c..93304e9b 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/OutputParameterLocalDbTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/OutputParameterLocalDbTests.cs @@ -372,10 +372,10 @@ public static async Task EachType_AsANamedValue_IsRead_ADecimalByItsPrecisionAnd Assert.Equal(1234.56m, await connection.StoredProcedure(name).ExecuteOutputAsync("total", 10, 2, Token)); Assert.Equal(0.5m, await connection.StoredProcedure(name).ExecuteOutputDecimalAsync("total_n", 10, 2, Token)); - var ex = Assert.Throws(() => connection.StoredProcedure(name).ExecuteOutputAsync("total", Token)); + var ex = Assert.Throws(() => { _ = connection.StoredProcedure(name).ExecuteOutputAsync("total", Token).AsTask(); }); Assert.Contains("The output parameter 'total' is read as Decimal", ex.Message); Assert.Contains("A decimal output needs its precision and scale, or the server rounds it to a whole number. Use ExecuteOutputAsync(\"total\", 19, 4) or ExecuteOutputDecimalAsync(\"total\", 19, 4)", ex.Message); - Assert.Throws(() => connection.StoredProcedure(name).ExecuteOutputAsync("total_n", Token)); + Assert.Throws(() => { _ = connection.StoredProcedure(name).ExecuteOutputAsync("total_n", Token).AsTask(); }); } // (5) NULL outputs: each nullable member and named value is null; each non-nullable value type throws ValueMappingException. @@ -474,8 +474,8 @@ public static async Task Cancel_BeforeAndDuring() using var before = new CancellationTokenSource(); before.Cancel(); - Assert.Throws(() => connection.StoredProcedure(name).ExecuteOutputAsync(before.Token)); - Assert.Throws(() => connection.StoredProcedure(name).ExecuteOutputAsync("views", before.Token)); + Assert.Throws(() => { _ = connection.StoredProcedure(name).ExecuteOutputAsync(before.Token).AsTask(); }); + Assert.Throws(() => { _ = connection.StoredProcedure(name).ExecuteOutputAsync("views", before.Token).AsTask(); }); using var during = CancellationTokenSource.CreateLinkedTokenSource(Token); during.CancelAfter(300); @@ -485,7 +485,9 @@ public static async Task Cancel_BeforeAndDuring() // SqlClient reports a command canceled while it runs with its own error ("A severe error occurred on the current command"), not an // OperationCanceledException; the call stops either way, and nothing is read. - Assert.True(ex is OperationCanceledException or SqlException, $"Expected a cancellation, got: {ex}"); + SqlException cut = Assert.IsType(ex); + Assert.Equal(0, cut.Number); + Assert.Contains("A severe error occurred on the current command", cut.Message); } // The decimal forms (owner Q9): ExecuteOutputAsync(name, precision, scale) and ExecuteOutputDecimalAsync keep 4 places of a @@ -514,16 +516,16 @@ public static async Task TheDecimalForms_ReadADecimal_ByItsPrecisionAndScale() Assert.Equal(3.0000m, await connection.StoredProcedure(name).AddParam("total", 1.5m).ExecuteOutputAsync("@total", 19, 4, Token)); Assert.Equal(3.0000m, await connection.StoredProcedure(name).AddParam("total", 1.5m).ExecuteOutputDecimalAsync("@total", 19, 4, Token)); - var range = Assert.Throws(() => connection.StoredProcedure(name).ExecuteOutputDecimalAsync("total", 4, 19, Token)); + var range = Assert.Throws(() => { _ = connection.StoredProcedure(name).ExecuteOutputDecimalAsync("total", 4, 19, Token).AsTask(); }); Assert.Contains("The scale of the decimal output parameter 'total' is 19, more than its precision of 4", range.Message); - Assert.Throws(() => connection.StoredProcedure(name).ExecuteOutputAsync("total", 0, 0, Token)); - var other = Assert.Throws(() => connection.StoredProcedure(name).ExecuteOutputAsync("total", 19, 4, Token)); + Assert.Throws(() => { _ = connection.StoredProcedure(name).ExecuteOutputAsync("total", 0, 0, Token).AsTask(); }); + var other = Assert.Throws(() => { _ = connection.StoredProcedure(name).ExecuteOutputAsync("total", 19, 4, Token).AsTask(); }); Assert.Contains("Only a decimal output takes a precision and scale; Int32 needs none", other.Message); - Assert.Throws(() => connection.StoredProcedure(name).ExecuteOutputAsync("total", 19, 4, Token)); + Assert.Throws(() => { _ = connection.StoredProcedure(name).ExecuteOutputAsync("total", 19, 4, Token).AsTask(); }); const string fix = "Use ExecuteOutputAsync(\"total\", 19, 4) or ExecuteOutputDecimalAsync(\"total\", 19, 4) with the column's precision and scale."; - Assert.Contains(fix, Assert.Throws(() => connection.StoredProcedure(name).ExecuteOutputAsync("total", Token)).Message); - Assert.Contains(fix, Assert.Throws(() => connection.StoredProcedure(name).ExecuteOutputAsync("total", Token)).Message); + Assert.Contains(fix, Assert.Throws(() => { _ = connection.StoredProcedure(name).ExecuteOutputAsync("total", Token).AsTask(); }).Message); + Assert.Contains(fix, Assert.Throws(() => { _ = connection.StoredProcedure(name).ExecuteOutputAsync("total", Token).AsTask(); }).Message); } public sealed record PostClock(TimeSpan Span, DateTimeOffset At, DateTime Stamp); @@ -573,6 +575,35 @@ public static async Task OtherTypes_ReadBackExactly_AndACharIsPadded() Assert.Equal("ab ", await connection.StoredProcedure(name).ExecuteOutputAsync("code", Token)); } + public sealed record PostGrade(char Grade); + + // A char member, and ExecuteOutputAsync(name), over a char(1) output. + [Fact] + public static async Task ACharOutput_ReadsAsAChar_AsAModelMember_AndByName() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = Procedure("@grade char(1) = null output", "set @grade = 'B';"); + await using SqlConnection connection = await OpenAsync(); + string name = "dbo." + procedure.Name; + + Assert.Equal(new PostGrade('B'), await connection.StoredProcedure(name).ExecuteOutputAsync(Token)); + Assert.Equal('B', await connection.StoredProcedure(name).ExecuteOutputAsync("grade", Token)); + } + + // A char is one character: from a char(3) holding XYZ a char member and ExecuteOutputAsync read the first, X, with no error; a string reads all three. + [Fact] + public static async Task ACharOutput_FromAWiderColumn_IsTheFirstCharacter() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = Procedure("@grade char(3) = null output", "set @grade = 'XYZ';"); + await using SqlConnection connection = await OpenAsync(); + string name = "dbo." + procedure.Name; + + Assert.Equal(new PostGrade('X'), await connection.StoredProcedure(name).ExecuteOutputAsync(Token)); + Assert.Equal('X', await connection.StoredProcedure(name).ExecuteOutputAsync("grade", Token)); + Assert.Equal("XYZ", await connection.StoredProcedure(name).ExecuteOutputAsync("grade", Token)); + } + public sealed record PostLegacyTimes(DateTime Minute); // Legacy smalldatetime into DateTime, which is sent as datetime2: exact. diff --git a/Tests/Open.Database.Extensions.Core.Tests/OutputParameterTests.cs b/Tests/Open.Database.Extensions.Core.Tests/OutputParameterTests.cs index 2702ef6f..3d98e5f2 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/OutputParameterTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/OutputParameterTests.cs @@ -18,6 +18,9 @@ public static class OutputParameterTests public sealed record NewPost(int Id, DateTime CreatedUtc); + // The member that fails to convert comes first in declaration and parameter order, the undelivered one second. + public sealed record CreatedThenId(DateTime CreatedUtc, int Id); + public sealed record PostTexts(string Title, byte[] Thumbnail, char Grade); public sealed record OrderTotal([property: Column(TypeName = "decimal(10,2)")] decimal Total); @@ -53,7 +56,7 @@ public sealed record WithChars(char[] Code); public sealed class NoMembers { - public int Id => 1; + public static int Id => 1; } public sealed class NotMappedOnly @@ -342,11 +345,12 @@ public static async Task AnOutputThatNeverArrived_Throws_NeverReadsAsNull() [Fact] public static async Task NotDelivered_WinsOverAConversionFailure() { - // CreatedUtc arrives as something a DateTime cannot read; Id never arrives (CLR null). + // CreatedUtc, first in order, arrives as something a DateTime cannot read; Id, second, never arrives (CLR null). + // Had the conversion run in member order, it would have thrown first. var c = new OutputConnection(Fill(("CreatedUtc", "not a date"))); - var ex = await Assert.ThrowsAsync(async () => await c.StoredProcedure("dbo.AddPost").ExecuteOutputAsync(Token)); - Assert.Contains("NewPost.Id has no value after dbo.AddPost ran: the output parameter 'Id' was not delivered", ex.Message); + var ex = await Assert.ThrowsAsync(async () => await c.StoredProcedure("dbo.AddPost").ExecuteOutputAsync(Token)); + Assert.Contains("CreatedThenId.Id has no value after dbo.AddPost ran: the output parameter 'Id' was not delivered", ex.Message); } // DateOnly goes as Date and TimeOnly as Time, nullable forms too, and is read back by RowMap's conversion. @@ -392,11 +396,11 @@ public static void ASqlDateTime_GivesTheValueARowReadGives(int fractionTicks, in public static void APrecisionOnAModelType_PointsToTheModelForm_NotToTheNamedForm() { ThrowsAtTheCall( - c => c.StoredProcedure("p").ExecuteOutputAsync("id", 19, 4, Token), + c => c.StoredProcedure("p").ExecuteOutputAsync("id", 19, 4, Token).AsTask(), "Only a decimal output takes a precision and scale; NewPost needs none", "NewPost is a model; call ExecuteOutputAsync() without a name"); ThrowsAtTheCall( - c => c.StoredProcedure("p").ExecuteOutputAsync("code", 19, 4, Token), + c => c.StoredProcedure("p").ExecuteOutputAsync("code", 19, 4, Token).AsTask(), "IntPtr has no database type for an output"); } [Fact] @@ -412,11 +416,11 @@ public static async Task NullIsNull_InANullableMember_AndAnErrorInANonNullableOn // ---- what throws before anything runs ---------------------------------------------- // Each message names the member, parameter or type, says what is wrong, and gives the fix: the phrases are asserted. - static void ThrowsAtTheCall(Func call, params string[] phrases) + static void ThrowsAtTheCall(Func call, params string[] phrases) where TException : Exception { var c = new OutputConnection(); - var ex = Assert.Throws(() => call(c)); + var ex = Assert.Throws(() => { _ = call(c); }); foreach (string phrase in phrases) Assert.Contains(phrase, ex.Message); Assert.Null(c.Last); } @@ -425,36 +429,36 @@ static void ThrowsAtTheCall(Func call, par public static void AModelThatCannotBeRead_ThrowsAtTheCall() { ThrowsAtTheCall( - c => c.StoredProcedure("p").ExecuteOutputAsync(Token), + c => c.StoredProcedure("p").ExecuteOutputAsync(Token).AsTask(), "NoScale.Total is a decimal output without a declared precision and scale", "round its value to a whole number", "Add [Column(TypeName = \"decimal(p,s)\")] to NoScale.Total"); ThrowsAtTheCall( - c => c.StoredProcedure("p").ExecuteOutputAsync(Token), + c => c.StoredProcedure("p").ExecuteOutputAsync(Token).AsTask(), "BadScale.Total declares [Column(TypeName = \"decimal(10,12)\")], which is not decimal(p,s)", "Change it to the parameter's declared type"); ThrowsAtTheCall( - c => c.StoredProcedure("p").ExecuteOutputAsync(Token), + c => c.StoredProcedure("p").ExecuteOutputAsync(Token).AsTask(), "ExecuteOutputAsync() reads a model of output parameters, but Int32 is a single value", "Call ExecuteOutputAsync(name)"); ThrowsAtTheCall( - c => c.StoredProcedure("p").ExecuteOutputAsync(Token), + c => c.StoredProcedure("p").ExecuteOutputAsync(Token).AsTask(), "String is a single value", "Call ExecuteOutputAsync(name)"); ThrowsAtTheCall( - c => c.StoredProcedure("p").ExecuteOutputAsync(Token), + c => c.StoredProcedure("p").ExecuteOutputAsync(Token).AsTask(), "NoMembers has no member to read an output parameter into", "Give it a public settable property or a constructor parameter"); ThrowsAtTheCall( - c => c.StoredProcedure("p").ExecuteOutputAsync(Token), + c => c.StoredProcedure("p").ExecuteOutputAsync(Token).AsTask(), "WithChars.Code is Char[], which has no database type"); ThrowsAtTheCall( - c => c.StoredProcedure("p").ExecuteOutputAsync(Token), + c => c.StoredProcedure("p").ExecuteOutputAsync(Token).AsTask(), "TwoReturns.ReturnValue and TwoReturns.RETURNVALUE both read the return code", "Remove one, or give it [Column(\"name\")]"); // The error is kept: a second call throws the same. - ThrowsAtTheCall(c => c.StoredProcedure("p").ExecuteOutputAsync(Token), "NoScale.Total is a decimal"); + ThrowsAtTheCall(c => c.StoredProcedure("p").ExecuteOutputAsync(Token).AsTask(), "NoScale.Total is a decimal"); } [Fact] @@ -468,32 +472,30 @@ public static async Task ANotMappedMember_IsNotAnOutput() [Fact] public static void AReturnValueMember_OnATextCommand_ThrowsAtTheCall() - { - ThrowsAtTheCall( - c => c.Command("exec dbo.Touch @Count output").ExecuteOutputAsync(Token), + => ThrowsAtTheCall( + c => c.Command("exec dbo.Touch @Count output").ExecuteOutputAsync(Token).AsTask(), "Touched.ReturnValue reads a stored procedure's return code, but the command is not a stored procedure (it is Text)", - "Call the procedure as CommandType.StoredProcedure"); - } + "Set CommandType.StoredProcedure to call a procedure"); [Fact] public static void TheNamedForm_TakesOneValueOfAType_ThatNeedsNoDeclaration() { ThrowsAtTheCall( - c => c.StoredProcedure("p").ExecuteOutputAsync("id", Token), + c => c.StoredProcedure("p").ExecuteOutputAsync("id", Token).AsTask(), "ExecuteOutputAsync(\"id\") reads one value, but NewPost is a model", "Call ExecuteOutputAsync() without a name"); // A decimal needs its precision and scale: without them, the call throws and gives the two forms that take them. ThrowsAtTheCall( - c => c.StoredProcedure("p").ExecuteOutputAsync("total", Token), + c => c.StoredProcedure("p").ExecuteOutputAsync("total", Token).AsTask(), "The output parameter 'total' is read as Decimal", "A decimal output needs its precision and scale, or the server rounds it to a whole number. Use ExecuteOutputAsync(\"total\", 19, 4) or ExecuteOutputDecimalAsync(\"total\", 19, 4) with the column's precision and scale."); ThrowsAtTheCall( - c => c.StoredProcedure("p").ExecuteOutputAsync("total", Token), + c => c.StoredProcedure("p").ExecuteOutputAsync("total", Token).AsTask(), "The output parameter 'total' is read as Decimal", "ExecuteOutputDecimalAsync(\"total\", 19, 4)"); ThrowsAtTheCall( - c => c.StoredProcedure("p").ExecuteOutputAsync("code", Token), + c => c.StoredProcedure("p").ExecuteOutputAsync("code", Token).AsTask(), "The output parameter 'code' is read as IntPtr, which has no database type", "Read it as a type that has one"); } @@ -503,12 +505,12 @@ public static void TheNamedForm_TakesOneValueOfAType_ThatNeedsNoDeclaration() public static void TheNamedForms_RequireAName_First() { const string required = "A parameter name is required, for example ExecuteOutputAsync(\"total\")."; - ThrowsAtTheCall(c => c.StoredProcedure("p").ExecuteOutputAsync(null!, Token), required); - ThrowsAtTheCall(c => c.StoredProcedure("p").ExecuteOutputAsync(null!, Token), required); - ThrowsAtTheCall(c => c.StoredProcedure("p").ExecuteOutputAsync(" ", Token), required); - ThrowsAtTheCall(c => c.StoredProcedure("p").ExecuteOutputAsync("@", Token), required); - ThrowsAtTheCall(c => c.StoredProcedure("p").ExecuteOutputAsync(null!, 19, 4, Token), required); - ThrowsAtTheCall(c => c.StoredProcedure("p").ExecuteOutputDecimalAsync("@", 19, 4, Token), required); + ThrowsAtTheCall(c => c.StoredProcedure("p").ExecuteOutputAsync(null!, Token).AsTask(), required); + ThrowsAtTheCall(c => c.StoredProcedure("p").ExecuteOutputAsync(null!, Token).AsTask(), required); + ThrowsAtTheCall(c => c.StoredProcedure("p").ExecuteOutputAsync(" ", Token).AsTask(), required); + ThrowsAtTheCall(c => c.StoredProcedure("p").ExecuteOutputAsync("@", Token).AsTask(), required); + ThrowsAtTheCall(c => c.StoredProcedure("p").ExecuteOutputAsync(null!, 19, 4, Token).AsTask(), required); + ThrowsAtTheCall(c => c.StoredProcedure("p").ExecuteOutputDecimalAsync("@", 19, 4, Token).AsTask(), required); } // A model cannot hold the return code: ExecuteReturnAsync and a ReturnValue member of a model type throw at the call. @@ -516,10 +518,10 @@ public static void TheNamedForms_RequireAName_First() public static void TheReturnCode_IsOneInteger() { ThrowsAtTheCall( - c => c.StoredProcedure("p").ExecuteReturnAsync(Token), + c => c.StoredProcedure("p").ExecuteReturnAsync(Token).AsTask(), "The return code is one integer, so NewPost cannot hold it. Use int (or int?, long, an enum), or a ReturnValue member on the output model."); ThrowsAtTheCall( - c => c.StoredProcedure("p").ExecuteOutputAsync(Token), + c => c.StoredProcedure("p").ExecuteOutputAsync(Token).AsTask(), "ModelReturn.ReturnValue reads the return code, which is one integer, so NewPost cannot hold it. Change ModelReturn.ReturnValue to int"); } @@ -528,8 +530,8 @@ public static void ACanceledToken_ThrowsBeforeAnythingRuns() { using var canceled = new CancellationTokenSource(); canceled.Cancel(); - ThrowsAtTheCall(c => c.StoredProcedure("p").ExecuteOutputAsync(canceled.Token)); - ThrowsAtTheCall(c => c.StoredProcedure("p").UseCancellationToken(canceled.Token).ExecuteOutputAsync("id")); + ThrowsAtTheCall(c => c.StoredProcedure("p").ExecuteOutputAsync(canceled.Token).AsTask()); + ThrowsAtTheCall(c => c.StoredProcedure("p").UseCancellationToken(canceled.Token).ExecuteOutputAsync("id").AsTask()); } [Fact] @@ -578,21 +580,21 @@ public static async Task TheDecimalForms_SendThePrecisionAndScale_AndTDecidesNul public static void TheDecimalForms_RefuseAPrecisionOrScaleOutOfRange_OrAnotherType_AtTheCall() { ThrowsAtTheCall( - c => c.StoredProcedure("p").ExecuteOutputAsync("total", 0, 0, Token), + c => c.StoredProcedure("p").ExecuteOutputAsync("total", 0, 0, Token).AsTask(), "The precision of the decimal output parameter 'total' is 0, but it must be from 1 to 38", "For decimal(19,4), pass ExecuteOutputAsync(\"total\", 19, 4)"); ThrowsAtTheCall( - c => c.StoredProcedure("p").ExecuteOutputDecimalAsync("total", 39, 2, Token), + c => c.StoredProcedure("p").ExecuteOutputDecimalAsync("total", 39, 2, Token).AsTask(), "is 39, but it must be from 1 to 38"); ThrowsAtTheCall( - c => c.StoredProcedure("p").ExecuteOutputDecimalAsync("total", 10, 12, Token), + c => c.StoredProcedure("p").ExecuteOutputDecimalAsync("total", 10, 12, Token).AsTask(), "The scale of the decimal output parameter 'total' is 12, more than its precision of 10", "For decimal(19,4), pass ExecuteOutputAsync(\"total\", 19, 4)"); ThrowsAtTheCall( - c => c.StoredProcedure("p").ExecuteOutputAsync("count", 19, 4, Token), - "Only a decimal output takes a precision and scale; Int32 needs none (date and time outputs keep full precision). Use ExecuteOutputAsync(\"count\")."); + c => c.StoredProcedure("p").ExecuteOutputAsync("count", 19, 4, Token).AsTask(), + "Only a decimal output takes a precision and scale; Int32 needs none. Use ExecuteOutputAsync(\"count\")."); ThrowsAtTheCall( - c => c.StoredProcedure("p").ExecuteOutputAsync("created", 19, 4, Token), + c => c.StoredProcedure("p").ExecuteOutputAsync("created", 19, 4, Token).AsTask(), "Only a decimal output takes a precision and scale; DateTime needs none"); } diff --git a/Tests/Open.Database.Extensions.Core.Tests/ParameterNameAddParamsTests.cs b/Tests/Open.Database.Extensions.Core.Tests/ParameterNameAddParamsTests.cs index 1373d3cb..84615553 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?> MatchBare = Names - .GetMethod("MatchBare", BindingFlags.Static | BindingFlags.NonPublic)! - .CreateDelegate, ImmutableArray, ImmutableArray, string, string, string?>>(); + static readonly Func, ImmutableArray, ImmutableArray, string, string, string?, string?> MatchBare = Names + .GetMethod("MatchBareAs", BindingFlags.Static | BindingFlags.NonPublic)! + .CreateDelegate, ImmutableArray, ImmutableArray, 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); + => MatchBare(candidates, parameterNames, BareNames(parameterNames), expression, procedure, null); [Theory] [InlineData("x", "x")] diff --git a/Tests/Open.Database.Extensions.Core.Tests/SqlServerParameterTypeTests.cs b/Tests/Open.Database.Extensions.Core.Tests/SqlServerParameterTypeTests.cs index d5e8442a..7272cc56 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/SqlServerParameterTypeTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/SqlServerParameterTypeTests.cs @@ -51,7 +51,5 @@ public static void AValueIsStillAValue_AboveAllALiteralZero() [Fact] public static void ASqlDbTypeIsStillASqlDbType() - { - Assert.Equal("@x=5 Int", Sent(Legacy().AddParam("@x", 5, SqlDbType.Int))); - } + => Assert.Equal("@x=5 Int", Sent(Legacy().AddParam("@x", 5, SqlDbType.Int))); } diff --git a/docsite/articles/expressive-commands.md b/docsite/articles/expressive-commands.md index bec120a5..6d9bca6f 100644 --- a/docsite/articles/expressive-commands.md +++ b/docsite/articles/expressive-commands.md @@ -179,7 +179,7 @@ To get the id an insert generated, select it in the same command and read it wit [!code-csharp[](../samples/SqlServer.cs#sql_server_return)] -A result set and the return value are readable on the chain; output parameters are read with `ExecuteOutputAsync` (below). `AddParam` adds inputs only. To set a direction yourself, use `ExecuteAsync(command => ...)` with the raw `AddParameter`, `AddParameterType` and `AddReturnParameter` extensions on the command. +A result set and the return value are readable on the chain; output parameters are read with `ExecuteOutputAsync` (below). To set a direction yourself, use `ExecuteAsync(command => ...)` with the raw `AddParameter`, `AddParameterType` and `AddReturnParameter` extensions on the command. ### Output parameters @@ -205,6 +205,7 @@ There is no blocking form. Known limits: - An Output parameter sends NULL in, so the procedure's default for it is not used. - 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`. - 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. diff --git a/docsite/articles/release-notes.md b/docsite/articles/release-notes.md index c85728e2..75dd08fe 100644 --- a/docsite/articles/release-notes.md +++ b/docsite/articles/release-notes.md @@ -9,7 +9,7 @@ Version 11 is `11.0.0-rc.16`. For moving a 10.x codebase, read [Coming from earl - **Generated row readers for `DbQuery` too.** A plain `Map()` on a `DbQuery`, a `DbQuery` or a query bound with `Using` now gets its row reader written at build time, as on a command or a reader; before, it used the runtime map. The runtime map's conversions are therefore no longer applied there: see [Generated readers](mapping.md#generated-readers) for the differences and the switch. - **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. 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. +- **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: `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. diff --git a/docsite/articles/whats-new-11.md b/docsite/articles/whats-new-11.md index 57745614..c03394c5 100644 --- a/docsite/articles/whats-new-11.md +++ b/docsite/articles/whats-new-11.md @@ -129,7 +129,7 @@ See [Expressive commands](expressive-commands.md). - **Names from arguments.** `.AddParam(author)` takes the name from the variable and matches it to the stored procedure's real name. `AddParam("name", value)` always wins. - **A typed NULL** such as `AddParam("@id", (long?)null)` is sent with the database type of its overload. - **After a run, `Params` holds what you added,** under the names as added. Read the provider command's `Parameters` in `Execute(command => ...)` to see what was sent. -- **No direction on the chain.** `AddParam`, `AddParamIf` and `AddReturnParam` no longer take a `ParameterDirection`, so a parameter added on the chain is an input; `AddReturnParam` is gone. Calls that never passed a direction compile unchanged; `AddParam(name, direction)`, `AddParamIf(condition, name, direction)`, `AddParam(name, type)` and `AddParamIf(condition, name, type)` are now compile errors that say what to do instead. To set a direction, use `ExecuteAsync(command => ...)` with the raw `AddParameter`, `AddParameterType` and `AddReturnParameter` extensions. `Param` has no `direction` constructor parameter and no `Direction` property. +- **No direction on the chain.** `AddParam`, `AddParamIf` and `AddReturnParam` no longer take a `ParameterDirection`, so a parameter added on the chain is an input; `AddReturnParam` is gone. Calls that never passed a direction compile unchanged; `AddParam(name, direction)`, `AddParamIf(condition, name, direction)`, `AddParam(name, type)` and `AddParamIf(condition, name, type)` are now compile errors that say what to do instead. The forms that took a direction after the value, `AddParam(name, value, ParameterDirection)` and `AddParam(name, value, type, direction)` (the SQL Server forms with a database type and a direction too), fail to compile with the compiler's own argument error, without a message of their own: use the raw `AddParameter` inside `ExecuteAsync(command => ...)`, or read the output with `ExecuteOutputAsync`. To set a direction, use `ExecuteAsync(command => ...)` with the raw `AddParameter`, `AddParameterType` and `AddReturnParameter` extensions. `Param` has no `direction` constructor parameter and no `Direction` property. - **Output parameters into a model.** `ExecuteOutputAsync()` reads a command's output parameters and return code into a model by name (`ExecuteOutputAsync(name)` for one value): see [Output parameters](expressive-commands.md#output-parameters). See [Parameters](expressive-commands.md#name-a-parameter-from-its-argument). From f298dff40e0b610020d570013d732bc0df9ad1f7 Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Tue, 1 Dec 2026 21:02:39 -0800 Subject: [PATCH 08/20] Document that a char output reads one character. A char member or ExecuteOutputAsync declares the output with size 1, so a char(3) holding XYZ reads X without an error, as the model type asks; a string reads the whole value. Co-Authored-By: Claude Opus 5.5 --- docsite/articles/expressive-commands.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docsite/articles/expressive-commands.md b/docsite/articles/expressive-commands.md index 6d9bca6f..aadcfd05 100644 --- a/docsite/articles/expressive-commands.md +++ b/docsite/articles/expressive-commands.md @@ -196,7 +196,7 @@ NewPost created = await db.StoredProcedure("dbo.AddPost") - **Names.** A member finds its parameter as `AddParam(value)` does: through the four tiers when the names are known (a procedure's, or a text's `@name` markers, so `exec dbo.AddPost @id output` works too), else under its own name. `[Column("name")]` names the parameter exactly. A member that matches no parameter, or two members on one parameter, throw `InvalidOperationException` before the command runs. - **Direction.** A member whose parameter got a value (`AddParam`, `AddParams`) is sent as InputOutput; any other as Output. - **Return code.** A member named `ReturnValue` reads a stored procedure's return code. On a text command it throws, and so does a procedure that declares a parameter that name would also match: name that member with `[Column]`. -- **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 `decimal` needs `[Column(TypeName = "decimal(10,2)")]` (positional records: `[property: Column(...)]`); without it the call throws before it runs. +- **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. - **Not delivered.** An Output parameter still empty after the call means the response never completed: the call throws `InvalidOperationException`, never a NULL. From 8e2f961d199a43ae0c62a40295a05217110c34ad Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Tue, 1 Dec 2026 21:24:46 -0800 Subject: [PATCH 09/20] Docs: share the output-parameter text through Output.docs.xml. The ExecuteOutputAsync forms, ExecuteOutputDecimalAsync and ExecuteReturnAsync now pull their shared facts (what the task returns, the name rules, the decimal shape and why, the legacy datetime note, the not-delivered and after-the-run failures, the cancel sentence) from one docs.xml file, and the generic decimal shape form inherits the remarks of ExecuteOutputDecimalAsync. Keys for the capture members are added for the next part. Docs only: no behaviour, signature or message changes. Co-Authored-By: Claude Sonnet 5.5 --- Source/Core/ExpressiveCommandBase.Output.cs | 149 +++++++--------- Source/Core/ExpressiveCommandBase.cs | 5 +- Source/Core/Output.docs.xml | 187 ++++++++++++++++++++ 3 files changed, 249 insertions(+), 92 deletions(-) create mode 100644 Source/Core/Output.docs.xml diff --git a/Source/Core/ExpressiveCommandBase.Output.cs b/Source/Core/ExpressiveCommandBase.Output.cs index f7769804..4c561e17 100644 --- a/Source/Core/ExpressiveCommandBase.Output.cs +++ b/Source/Core/ExpressiveCommandBase.Output.cs @@ -30,35 +30,41 @@ public abstract partial class ExpressiveCommandBaseAddParam, AddParams) is sent as /// , any other as , which sends NULL: /// a procedure's default for that parameter is not used. - /// A parameter added with a null value is sent as InputOutput too, so a lost output cannot be told from a NULL: add no value for a pure output, only when the procedure reads it. - /// A member named ReturnValue reads a stored procedure's return code. (In the named forms, "ReturnValue" names a declared parameter: the return code is .) /// + /// /// - /// A is sent as ; a or array with size -1 (the whole value); - /// a needs [Column(TypeName = "decimal(p,s)")]; the declared scale also rounds a value sent in. - /// A member of a read from a legacy datetime can differ from a row's in the last digits of its fraction (.997 reads back as .9966667; see the article on expressive commands). + /// A member named ReturnValue reads a stored procedure's return code. + /// + /// + /// + /// + /// A or array is sent with size -1 (the whole value). + /// + /// + /// + /// A member declares them with [Column(TypeName = "decimal(p,s)")]. /// /// /// To read one value instead of a model, name it: . - /// A of a given precision and scale is read with - /// or . /// + /// /// /// The model the output parameters are read into. /// - /// - /// A task that completes when the command has executed and its output parameters have arrived; its result is the model. - /// + /// /// + /// /// Before anything runs: has no member to read, is a single value, has a member without its type name or a member of a type /// that has no database type, or reads the return code of a command that is not a stored procedure. /// Before the command executes: a member matches no parameter, two match one, or the procedure declares a parameter a ReturnValue member would also match. - /// After: the output parameters were not delivered (the response did not complete). + /// + /// /// - /// After the command has run, so its effects have happened: a value does not convert to its member, or is NULL and the member does not take it. - /// - /// The command's token or is canceled; one already canceled throws before a task is returned. + /// + /// A value does not convert to its member, or is NULL and the member does not take it. + /// /// + /// public ValueTask ExecuteOutputAsync( CancellationToken cancellationToken = default) { @@ -89,34 +95,32 @@ static async (cmd, _, run) => /// and reads one output parameter, converted to . /// /// - /// - /// names the parameter exactly, with or without its @ and in any case; "ReturnValue" names a declared parameter, - /// not the return code (that is ). - /// A value added under the same name makes it (a null value too: then a lost output cannot be told from a NULL, so add no value for a pure output, only when the procedure reads it). - /// + /// + /// + /// /// /// The value converts as Map<T>() converts a single column; NULL is only when takes it. - /// A needs its precision and scale, or the server rounds it to a whole number, so this form refuses it: use - /// or . + /// This form refuses a . /// + /// + /// /// /// The type of the value. - /// The name of the output parameter. + /// /// - /// - /// A task that completes when the command has executed and its output parameters are read; its result is the value. - /// - /// is . - /// is empty, white space or a bare @. + /// /// + /// /// Before anything runs: is not a single value, is a , or has no database type. /// Before the command executes: the names are known and none is . - /// After: the output parameter was not delivered (the response did not complete). + /// + /// /// - /// After the command has run, so its effects have happened: the value does not convert to , or is NULL and is a non-nullable value type. - /// - /// The command's token or is canceled; one already canceled throws before a task is returned. + /// + /// The value does not convert to , or is NULL and is a non-nullable value type. + /// /// + /// public ValueTask ExecuteOutputAsync( string name, CancellationToken cancellationToken = default) @@ -132,24 +136,7 @@ public ValueTask ExecuteOutputAsync( /// does, /// and reads one output parameter of the given precision and scale, converted to . /// - /// - /// - /// The parameter is sent as with and , as its SQL type - /// declares them (decimal(19,4): 19 and 4); without them the server rounds the value to a whole number. - /// The scale also rounds a value sent in. - /// - /// - /// Otherwise as : names the parameter exactly, - /// and a value added under the same name makes it (a null value too: then a lost output cannot be told from a NULL, so add no value for a pure output, only when the procedure reads it). "ReturnValue" names a declared parameter, not the return code (that is ). - /// NULL is in a of and an error in a . - /// - /// - /// This form lets decide how NULL is handled and is checked when it is called: any other throws. - /// always returns a of - /// and is checked by the compiler. A model member declares the same with [Column(TypeName = "decimal(p,s)")] - /// (). - /// - /// + /// /// /// /// decimal total = await connection @@ -159,27 +146,22 @@ public ValueTask ExecuteOutputAsync( /// /// /// , or a of it. - /// The name of the output parameter. - /// The number of digits its SQL type declares, from 1 to 38. - /// The number of those digits after the decimal point, from 0 to . + /// + /// /// - /// - /// A task that completes when the command has executed and its output parameters are read; its result is the value. - /// - /// is . - /// is empty, white space or a bare @. - /// - /// Before anything runs: is 0 or more than 38, or is more than . - /// + /// /// + /// /// Before anything runs: is not a (only a decimal takes a precision and scale). /// Before the command executes: the names are known and none is . - /// After: the output parameter was not delivered (the response did not complete). + /// + /// /// - /// After the command has run, so its effects have happened: the value does not convert to , or is NULL and is . - /// - /// The command's token or is canceled; one already canceled throws before a task is returned. + /// + /// The value does not convert to , or is NULL and is . + /// /// + /// public ValueTask ExecuteOutputAsync( string name, byte precision, @@ -241,15 +223,11 @@ static async ValueTask NotNullAsync(string name, ValueTask va /// and reads one output parameter of the given precision and scale. /// /// - /// - /// The parameter is sent with and , as its SQL type declares them - /// (decimal(19,4): 19 and 4); without them the server rounds the value to a whole number. - /// - /// - /// This form always returns a of (NULL is ) and is checked by the compiler. - /// lets its type decide how NULL is handled and is checked when it is called. - /// Otherwise the two are the same, and as . - /// + /// + /// + /// + /// + /// /// /// /// @@ -259,26 +237,21 @@ static async ValueTask NotNullAsync(string name, ValueTask va /// .ExecuteOutputDecimalAsync("total", 19, 4); /// /// - /// The name of the output parameter. - /// The number of digits its SQL type declares, from 1 to 38. - /// The number of those digits after the decimal point, from 0 to . + /// + /// /// - /// - /// A task that completes when the command has executed and its output parameters are read; its result is the value, or for NULL. - /// - /// is . - /// is empty, white space or a bare @. - /// - /// Before anything runs: is 0 or more than 38, or is more than . - /// + /// /// + /// /// Before the command executes: the names are known and none is . - /// After: the output parameter was not delivered (the response did not complete). + /// + /// /// - /// After the command has run, so its effects have happened: the value does not convert to a . - /// - /// The command's token or is canceled; one already canceled throws before a task is returned. + /// + /// The value does not convert to a . + /// /// + /// public ValueTask ExecuteOutputDecimalAsync( string name, byte precision, diff --git a/Source/Core/ExpressiveCommandBase.cs b/Source/Core/ExpressiveCommandBase.cs index 2bc577b2..b0037a4d 100644 --- a/Source/Core/ExpressiveCommandBase.cs +++ b/Source/Core/ExpressiveCommandBase.cs @@ -1851,10 +1851,7 @@ ValueTask IExecuteReader.ExecuteReaderAsync(Func /// /// /// - /// - /// The command's token or is already - /// canceled; thrown before anything runs. - /// + /// public ValueTask ExecuteReturnAsync( CancellationToken cancellationToken = default) { diff --git a/Source/Core/Output.docs.xml b/Source/Core/Output.docs.xml new file mode 100644 index 00000000..8afaef8c --- /dev/null +++ b/Source/Core/Output.docs.xml @@ -0,0 +1,187 @@ + + + + + + + A task that completes when the command has executed and its output parameters are read; its result is the model. + + + + + + A task that completes when the command has executed and its output parameters are read; its result is the value. + + + + + + A task that completes when the command has executed and its output parameters are read; its result is the value, or for NULL. + + + + + + The name of the output parameter. + is . + is empty, white space or a bare @. + + + + + names the parameter exactly, with or without its @ and in any case. + A value added under the same name makes it . + + + + + + A parameter added with a null value is sent as too, + so a lost output cannot be told from a NULL: add no value for a pure output, only when the procedure reads it. + + + + + + A named form never reads the return code: "ReturnValue" there names a declared parameter, + and reads the return code. + + + + + + + A output parameter needs its precision and scale, as its SQL type declares them + (decimal(19,4): 19 and 4): it is sent as with them, and without them the server rounds the value to a whole number. + The scale also rounds a value sent in. + + + + + + Read a of a given precision and scale with + + or . + + + + + + lets T decide how NULL is handled + ( in a of , an error in a ) + and is checked when it is called: any other T throws. + always returns a of + (NULL is ) and is checked by the compiler. + Otherwise the two are the same. + A model member declares the same with [Column(TypeName = "decimal(p,s)")] + (). + + + + + The number of digits its SQL type declares, from 1 to 38. + The number of those digits after the decimal point, from 0 to . + + Before anything runs: is 0 or more than 38, or is more than . + + + + + + A is sent as . + One read from a legacy datetime can differ from a row's in the last digits of its fraction + (.997 reads back as .9966667; see the article on expressive commands). + + + + + + + After the command has run: the output parameters were not delivered (the response did not complete). + + + + + + It is thrown after the command has run, so its effects have happened. + + + + + + The command's token or is canceled; one already canceled throws before a task is returned. + + + + + + + The capture is awaited, or turned into a task, before its terminal was called: + call the terminal (for example ToListAsync) first, then await the capture. + + + + + + A synchronous terminal (ToList, ExecuteNonQuery, a synchronous enumeration) is called on a chain that carries a capture: + captures need an async terminal. It throws before the run, so nothing is armed. + + + + + + The chain, or a copy of it, runs a second time: a chain that carries a capture runs once. + It throws before a connection opens; build a new chain to run again. + + + + + + The capture is awaited while the stream it belongs to is still open, in the loop that reads it: + await the capture after the loop. AsTask is allowed there, to hand the capture to code that runs after the loop. + + + + + + The capture is a default value (a default declaration, never the out of a capture call): + it belongs to no call, so awaiting it throws. + + + + + + Two captures own the same outputs: the same name twice, a named capture together with a model capture, + or two sources of the return code. Name each output once. + + + + + + It returns the type it is called on, with the capture attached, and is available on a command, + after Map (including the views that skip or take rows), and on a bound definition of a mapped query + (after Using or AddParam). + The capture belongs to that one chain value, never to the definition. + + + From bb0d4369229f53d0390d95a5424ef5b55342af3f Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Tue, 1 Dec 2026 21:27:46 -0800 Subject: [PATCH 10/20] Samples for output parameters. Adds compiled samples (docsite/samples/OutputParameters.cs) for ExecuteOutputAsync into a model with a ReturnValue member, one named value, decimal outputs, and raw output and return parameters inside ExecuteAsync. The expressive-commands article shows them in place of the inline block. Co-Authored-By: Claude Sonnet 5.5 --- docsite/articles/expressive-commands.md | 16 ++-- docsite/samples/OutputParameters.cs | 107 ++++++++++++++++++++++++ 2 files changed, 116 insertions(+), 7 deletions(-) create mode 100644 docsite/samples/OutputParameters.cs diff --git a/docsite/articles/expressive-commands.md b/docsite/articles/expressive-commands.md index aadcfd05..59b37785 100644 --- a/docsite/articles/expressive-commands.md +++ b/docsite/articles/expressive-commands.md @@ -181,17 +181,13 @@ To get the id an insert generated, select it in the same command and read it wit A result set and the return value are readable on the chain; output parameters are read with `ExecuteOutputAsync` (below). To set a direction yourself, use `ExecuteAsync(command => ...)` with the raw `AddParameter`, `AddParameterType` and `AddReturnParameter` extensions on the command. +[!code-csharp[](../samples/OutputParameters.cs#sql_server_output_raw)] + ### Output parameters `ExecuteOutputAsync()` runs the command and reads its output parameters, and its return code, into one model. Each member `Map()` would read is an output parameter, and the model is built by the same rules (records, constructors, `required`, conversions, `[NullPolicy]`): -```csharp -record NewPost(int Id, DateTime CreatedUtc); // @id OUTPUT, @created_utc OUTPUT - -NewPost created = await db.StoredProcedure("dbo.AddPost") - .AddParam(title) - .ExecuteOutputAsync(cancellationToken); -``` +[!code-csharp[](../samples/OutputParameters.cs#sql_server_output_model)] - **Names.** A member finds its parameter as `AddParam(value)` does: through the four tiers when the names are known (a procedure's, or a text's `@name` markers, so `exec dbo.AddPost @id output` works too), else under its own name. `[Column("name")]` names the parameter exactly. A member that matches no parameter, or two members on one parameter, throw `InvalidOperationException` before the command runs. - **Direction.** A member whose parameter got a value (`AddParam`, `AddParams`) is sent as InputOutput; any other as Output. @@ -200,6 +196,12 @@ NewPost created = await db.StoredProcedure("dbo.AddPost") - **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. - **Not delivered.** An Output parameter still empty after the call means the response never completed: the call throws `InvalidOperationException`, never a NULL. +One value, and a decimal with its precision and scale: + +[!code-csharp[](../samples/OutputParameters.cs#sql_server_output_named)] + +[!code-csharp[](../samples/OutputParameters.cs#sql_server_output_decimal)] + There is no blocking form. Known limits: - An Output parameter sends NULL in, so the procedure's default for it is not used. diff --git a/docsite/samples/OutputParameters.cs b/docsite/samples/OutputParameters.cs new file mode 100644 index 00000000..c7e4a6b8 --- /dev/null +++ b/docsite/samples/OutputParameters.cs @@ -0,0 +1,107 @@ +using System.ComponentModel.DataAnnotations.Schema; +using System.Data; +using Open.Database.Extensions; + +namespace Samples; + +// Compile-only: this needs a SQL Server, so Program.cs never calls it. +public static class OutputParameters +{ + #region sql_server_output_model + // The procedure declares @id and @created_utc as OUTPUT and ends with a RETURN code. + // ReturnValue reads the return code; every other member is an output parameter. + public record AddPostResult(int Id, DateTime CreatedUtc, int ReturnValue); + + public static async Task Model( + string title, + CancellationToken cancellationToken) + { + var connectionFactory = new SqlConnectionFactory(@"Server=(localdb)\MSSQLLocalDB;Database=Blog;Integrated Security=true"); + + AddPostResult created = await connectionFactory + .StoredProcedure("[dbo].[AddPost]") + .AddParam(title) + .ExecuteOutputAsync(cancellationToken); + + return created; + } + #endregion + + public static async Task Named( + string title, + CancellationToken cancellationToken) + { + var connectionFactory = new SqlConnectionFactory(@"Server=(localdb)\MSSQLLocalDB;Database=Blog;Integrated Security=true"); + + #region sql_server_output_named + // One output parameter, read by its name. + int id = await connectionFactory + .StoredProcedure("[dbo].[AddPost]") + .AddParam(title) + .ExecuteOutputAsync("id", cancellationToken); + #endregion + + return id; + } + + #region sql_server_output_decimal + // A decimal output needs its precision and scale: decimal(19,4). + public record Totals( + int Count, + [property: Column(TypeName = "decimal(19,4)")] decimal Total); + + public static async Task Decimals( + CancellationToken cancellationToken) + { + var connectionFactory = new SqlConnectionFactory(@"Server=(localdb)\MSSQLLocalDB;Database=Blog;Integrated Security=true"); + + Totals totals = await connectionFactory + .StoredProcedure("[dbo].[CountPosts]") + .ExecuteOutputAsync(cancellationToken); + + decimal total = await connectionFactory + .StoredProcedure("[dbo].[CountPosts]") + .ExecuteOutputAsync("total", 19, 4, cancellationToken); + + // The same, returning null when the procedure sets the output to NULL. + decimal? maybe = await connectionFactory + .StoredProcedure("[dbo].[CountPosts]") + .ExecuteOutputDecimalAsync("total", 19, 4, cancellationToken); + + _ = maybe; + _ = totals; + return total; + } + #endregion + + public static async Task Raw( + string title, + CancellationToken cancellationToken) + { + var connectionFactory = new SqlConnectionFactory(@"Server=(localdb)\MSSQLLocalDB;Database=Blog;Integrated Security=true"); + + #region sql_server_output_raw + // To set a direction yourself, work on the raw command. + int id = 0; + int returned = 0; + await connectionFactory + .StoredProcedure("[dbo].[AddPost]") + .ExecuteAsync(async command => + { + command.AddParameter("title", title); + IDbDataParameter output = command.AddParameter( + "id", null, DbType.Int32, ParameterDirection.Output); + IDbDataParameter returnCode = command.AddReturnParameter(); + + await command.ExecuteNonQueryAsync(cancellationToken); + + // Read the values after the command has run. + id = (int)output.Value!; + returned = (int)returnCode.Value!; + }); + #endregion + + _ = returned; + return id; + } +} From 627677c23efac4516f033d61979de960f6f00e88 Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Tue, 1 Dec 2026 21:32:16 -0800 Subject: [PATCH 11/20] Docs: complete the shared output text and tidy the samples. The named ExecuteOutputAsync form states the DateTime2 note; the decimal forms say the value converts as Map() does; the decimal [Column] fact has one wording. The decimal sample shows the model only; the single-value decimal calls sit in the named sample. Co-Authored-By: Claude Sonnet 5.5 --- Source/Core/ExpressiveCommandBase.Output.cs | 6 ++-- Source/Core/Output.docs.xml | 9 +++-- docsite/samples/OutputParameters.cs | 38 ++++++++++----------- 3 files changed, 29 insertions(+), 24 deletions(-) diff --git a/Source/Core/ExpressiveCommandBase.Output.cs b/Source/Core/ExpressiveCommandBase.Output.cs index 4c561e17..55c5e4cb 100644 --- a/Source/Core/ExpressiveCommandBase.Output.cs +++ b/Source/Core/ExpressiveCommandBase.Output.cs @@ -41,9 +41,7 @@ public abstract partial class ExpressiveCommandBase or array is sent with size -1 (the whole value). /// /// - /// - /// A member declares them with [Column(TypeName = "decimal(p,s)")]. - /// + /// /// /// To read one value instead of a model, name it: . /// @@ -98,6 +96,7 @@ static async (cmd, _, run) => /// /// /// + /// /// /// The value converts as Map<T>() converts a single column; NULL is only when takes it. /// This form refuses a . @@ -228,6 +227,7 @@ static async ValueTask NotNullAsync(string name, ValueTask va /// /// /// + /// /// /// /// diff --git a/Source/Core/Output.docs.xml b/Source/Core/Output.docs.xml index 8afaef8c..e97684d9 100644 --- a/Source/Core/Output.docs.xml +++ b/Source/Core/Output.docs.xml @@ -87,8 +87,13 @@ and is checked when it is called: any other T throws. always returns a of (NULL is ) and is checked by the compiler. - Otherwise the two are the same. - A model member declares the same with [Column(TypeName = "decimal(p,s)")] + Otherwise the two are the same, and the value converts as Map<T>() converts a single column. + + + + + + A member of a model declares them with [Column(TypeName = "decimal(p,s)")] (). diff --git a/docsite/samples/OutputParameters.cs b/docsite/samples/OutputParameters.cs index c7e4a6b8..5d7d697c 100644 --- a/docsite/samples/OutputParameters.cs +++ b/docsite/samples/OutputParameters.cs @@ -7,6 +7,8 @@ namespace Samples; // Compile-only: this needs a SQL Server, so Program.cs never calls it. public static class OutputParameters { + static readonly SqlConnectionFactory Blog = new(@"Server=(localdb)\MSSQLLocalDB;Database=Blog;Integrated Security=true"); + #region sql_server_output_model // The procedure declares @id and @created_utc as OUTPUT and ends with a RETURN code. // ReturnValue reads the return code; every other member is an output parameter. @@ -16,9 +18,7 @@ public static async Task Model( string title, CancellationToken cancellationToken) { - var connectionFactory = new SqlConnectionFactory(@"Server=(localdb)\MSSQLLocalDB;Database=Blog;Integrated Security=true"); - - AddPostResult created = await connectionFactory + AddPostResult created = await Blog .StoredProcedure("[dbo].[AddPost]") .AddParam(title) .ExecuteOutputAsync(cancellationToken); @@ -39,8 +39,21 @@ public static async Task Named( .StoredProcedure("[dbo].[AddPost]") .AddParam(title) .ExecuteOutputAsync("id", cancellationToken); + + // One decimal output needs its precision and scale. + decimal total = await connectionFactory + .StoredProcedure("[dbo].[CountPosts]") + .ExecuteOutputAsync("total", 19, 4, cancellationToken); + + // The same, returning null when the procedure sets the output to NULL. + decimal? maybe = await connectionFactory + .StoredProcedure("[dbo].[CountPosts]") + .ExecuteOutputDecimalAsync("total", 19, 4, cancellationToken); #endregion + _ = total; + _ = maybe; + return id; } @@ -50,27 +63,14 @@ public record Totals( int Count, [property: Column(TypeName = "decimal(19,4)")] decimal Total); - public static async Task Decimals( + public static async Task Decimals( CancellationToken cancellationToken) { - var connectionFactory = new SqlConnectionFactory(@"Server=(localdb)\MSSQLLocalDB;Database=Blog;Integrated Security=true"); - - Totals totals = await connectionFactory + Totals totals = await Blog .StoredProcedure("[dbo].[CountPosts]") .ExecuteOutputAsync(cancellationToken); - decimal total = await connectionFactory - .StoredProcedure("[dbo].[CountPosts]") - .ExecuteOutputAsync("total", 19, 4, cancellationToken); - - // The same, returning null when the procedure sets the output to NULL. - decimal? maybe = await connectionFactory - .StoredProcedure("[dbo].[CountPosts]") - .ExecuteOutputDecimalAsync("total", 19, 4, cancellationToken); - - _ = maybe; - _ = totals; - return total; + return totals; } #endregion From e2aaa76424e46cad65b045e2bcf3a60491485e70 Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Tue, 1 Dec 2026 21:32:47 -0800 Subject: [PATCH 12/20] Samples: one connection factory across the output snippets. The named and raw snippets used a local factory while the model and decimal snippets used the shared one; all four now read the same name. Co-Authored-By: Claude Opus 5.5 --- docsite/samples/OutputParameters.cs | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/docsite/samples/OutputParameters.cs b/docsite/samples/OutputParameters.cs index 5d7d697c..15ab74cb 100644 --- a/docsite/samples/OutputParameters.cs +++ b/docsite/samples/OutputParameters.cs @@ -31,22 +31,20 @@ public static async Task Named( string title, CancellationToken cancellationToken) { - var connectionFactory = new SqlConnectionFactory(@"Server=(localdb)\MSSQLLocalDB;Database=Blog;Integrated Security=true"); - #region sql_server_output_named // One output parameter, read by its name. - int id = await connectionFactory + int id = await Blog .StoredProcedure("[dbo].[AddPost]") .AddParam(title) .ExecuteOutputAsync("id", cancellationToken); // One decimal output needs its precision and scale. - decimal total = await connectionFactory + decimal total = await Blog .StoredProcedure("[dbo].[CountPosts]") .ExecuteOutputAsync("total", 19, 4, cancellationToken); // The same, returning null when the procedure sets the output to NULL. - decimal? maybe = await connectionFactory + decimal? maybe = await Blog .StoredProcedure("[dbo].[CountPosts]") .ExecuteOutputDecimalAsync("total", 19, 4, cancellationToken); #endregion @@ -78,13 +76,11 @@ public static async Task Raw( string title, CancellationToken cancellationToken) { - var connectionFactory = new SqlConnectionFactory(@"Server=(localdb)\MSSQLLocalDB;Database=Blog;Integrated Security=true"); - #region sql_server_output_raw // To set a direction yourself, work on the raw command. int id = 0; int returned = 0; - await connectionFactory + await Blog .StoredProcedure("[dbo].[AddPost]") .ExecuteAsync(async command => { From 8a3c6fcd4bfbc42efe49bb91991c7d3f2d7bbe20 Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Wed, 2 Dec 2026 05:35:49 -0800 Subject: [PATCH 13/20] Captures: read output parameters beside rows (C1) 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. Each gives a DbCapture as an out argument; the query's async terminal fills it after the reader is closed, and a stream fills it when its loop ends, a break included. - DbCapture: a readonly struct with GetAwaiter, ConfigureAwait and AsTask only; its GetResult throws while the capture is pending, never blocks. Awaiting before the terminal, inside the stream's own loop, or a default value throws with the fix. - One run: the claim is a compare-exchange on the set's first source, so Map() shares the command's capture and the first run wins; a second run throws. - The command's run passes the captures' layout as an OutputRun, so the parameters are added exactly as ExecuteOutputAsync adds them. - Refused, with the capture completed by the refusal: a synchronous terminal (arms nothing), ExecuteAsync(command => ...), ExecuteOutputAsync beside a capture, ExecuteReturnAsync beside CaptureReturn, CancelOnEarlyStop(), a query from a DbQuery definition or from another IExecuteReader (C2 adds the definition forms). - Streams and the pooled buffer: an early stop by the consumer no longer cancels a captured read (DirectStream, StallStream, ChunkProducer; StreamTarget refuses a publish once disposed), so the outputs arrive. A cancel of the caller's still cancels it. - Every exit completes every armed capture: value, fault, cancel with the caller's token, or "not delivered". Tests: CaptureTests (fake provider), 38 tests. Co-Authored-By: Claude Opus 5.5 --- Source/Core/Capture.cs | 997 ++++++++++++++++++ Source/Core/CapturedStream.cs | 123 +++ Source/Core/ChunkProducer.cs | 26 +- Source/Core/ChunkStream.cs | 26 +- Source/Core/DbCapture.cs | 219 ++++ Source/Core/DirectStream.cs | 13 +- Source/Core/ExpressiveCommandBase.Capture.cs | 367 +++++++ Source/Core/ExpressiveCommandBase.Output.cs | 81 +- Source/Core/ExpressiveCommandBase.cs | 79 +- Source/Core/ExpressiveDbCommandBase.cs | 8 +- Source/Core/MappedQuery.Capture.cs | 376 +++++++ Source/Core/MappedQuery.cs | 209 +++- Source/Core/Output.docs.xml | 148 ++- Source/Core/OutputLayout.cs | 352 ++++++- Source/Core/PublicAPI.Unshipped.txt | 40 + Source/Core/StallStream.cs | 37 +- .../CaptureTests.cs | 949 +++++++++++++++++ 17 files changed, 3891 insertions(+), 159 deletions(-) create mode 100644 Source/Core/Capture.cs create mode 100644 Source/Core/CapturedStream.cs create mode 100644 Source/Core/DbCapture.cs create mode 100644 Source/Core/ExpressiveCommandBase.Capture.cs create mode 100644 Source/Core/MappedQuery.Capture.cs create mode 100644 Tests/Open.Database.Extensions.Core.Tests/CaptureTests.cs diff --git a/Source/Core/Capture.cs b/Source/Core/Capture.cs new file mode 100644 index 00000000..1fc8eb9d --- /dev/null +++ b/Source/Core/Capture.cs @@ -0,0 +1,997 @@ +namespace Open.Database.Extensions; + +// The captures (CaptureOutput, CaptureOutputDecimal, CaptureReturn) of a +// command or a mapped query, and the run that fills them. +// +// A capture call makes one source (a TaskCompletionSource the run completes) +// and attaches it to the chain as a new, immutable CaptureSet: the sources so +// far plus the new one, appended. The command holds its set in one field; a +// mapped query holds its own in MappedQueryCore, and a query without one runs +// on its command, which uses the command's set: Map() shares the command's +// capture, and the first run by either route takes it. +// +// The claim (the arm) is a compare-exchange on the set's first source. A set +// only ever grows at its end, so two chain values that share a capture share +// that first source, and one run wins whatever route it takes; the loser throws +// the second-run message and touches nothing. The claim makes a CaptureRun: the +// state of the one run that fills the sources. +// +// The run is ExpressiveCommandBase.ExecuteCapturedAsync. It passes a +// CapturedCall, which is an OutputRun of the set's combined layout, as the +// state of the command's own run, so the build step adds the captures' +// parameters exactly as it does for ExecuteOutputAsync (matching, the wire +// rules, the InputOutput merge, the messages). The sources are completed when +// the command's function returns, after the reader is closed: once for the +// whole set, before the terminal's own task completes. +/// +/// What a capture reads. +/// +enum CaptureKind : byte +{ + /// An output model: CaptureOutput(out + /// DbCapture<TOut>). + Model, + + /// One output parameter by name: + /// CaptureOutput<TValue>(name, …) and + /// CaptureOutputDecimal. + Named, + + /// The return code: CaptureReturn<TValue>. + Return, +} + +/// +/// One capture, without its type: what it reads, and its state. +/// +interface ICaptureSource +{ + /// Gets the capture for the messages, such as + /// CaptureOutput<PageInfo>. + string Display { get; } + + /// Gets what the capture reads. + CaptureKind Kind { get; } + + /// Gets the parameter's name of a named capture, or + /// . + string? Name { get; } + + /// Gets the type the capture reads into, for the + /// messages. + string Model { get; } + + /// Gets the values the capture adds to the call, in + /// order. + ImmutableArray Members { get; } + + /// Gets whether the capture reads the return code + /// (CaptureReturn, or a model with a ReturnValue + /// member). + bool ReadsReturn { get; } + + /// Gets whether the capture is complete. + bool IsCompleted { get; } + + /// Moves the capture from not started to armed. + /// if this call armed it; + /// if it was armed before. + bool TryArm(); + + /// Arms the capture, if it is not armed yet. + void Arm(); + + /// Marks the capture as belonging to a stream whose enumerator is + /// open, or no longer. + /// while the enumerator is + /// open. + void SetStreamOpen(bool open); + + /// Completes the capture from the values of the call, once the + /// response is complete. + /// The call. + /// The index of the capture's first value in the + /// call. + void Deliver(OutputRun call, int start); + + /// Faults the capture, if it is not complete. + /// The exception. + /// if this call completed it. + bool TrySetException(Exception exception); + + /// Cancels the capture, if it is not complete. + /// The token that was canceled. + /// if this call completed it. + bool TrySetCanceled(CancellationToken cancellationToken); + + /// Marks a fault of the capture as seen, so it is not reported + /// again as unobserved. + void Observe(); +} + +/// +/// One capture: the task the run completes, and the state the awaiters check. +/// +/// The type of the value. +/// The capture for the messages. +/// What the capture reads. +abstract class CaptureSource(string display, CaptureKind kind) + : TaskCompletionSource( + TaskCreationOptions.RunContinuationsAsynchronously), + ICaptureSource +{ + const int NotStarted = 0; + const int Armed = 1; + const int StreamOpen = 2; + + // Only moves forward from NotStarted; StreamOpen and Armed alternate while + // a stream's enumerator is open. + int _state; + + public string Display { get; } = display; + + public CaptureKind Kind { get; } = kind; + + public virtual string? Name => null; + + public string Model => Shape.TypeName(typeof(T)); + + public abstract ImmutableArray Members { get; } + + public virtual bool ReadsReturn => Kind == CaptureKind.Return; + + public bool IsCompleted => Task.IsCompleted; + + public bool TryArm() + => Interlocked.CompareExchange(ref _state, Armed, NotStarted) + == NotStarted; + + public void Arm() + => Interlocked.CompareExchange(ref _state, Armed, NotStarted); + + public void SetStreamOpen(bool open) + => Volatile.Write(ref _state, open ? StreamOpen : Armed); + + public void Observe() + => _ = Task.Exception; + + public void Deliver(OutputRun call, int start) + { + // The conversion happens once, here; its failure is the capture's, + // never the terminal's. + T value; + try + { + value = Read(call, start); + } + catch (Exception ex) + { + TrySetException(ex); + return; + } + + TrySetResult(value); + } + + /// Reads the capture's value from the call. + /// The call, its values delivered. + /// The index of the capture's first value. + /// The value. + protected abstract T Read(OutputRun call, int start); + + /// + /// Gets the task of a capture that may be awaited now: refuses one whose + /// terminal was not called, and, when it is awaited, + /// one whose stream is still open. + /// + /// for GetAwaiter and + /// ConfigureAwait; for AsTask, which + /// a stream's loop may hand on. + /// The task. + /// The terminal was not called, + /// or the stream is still open. + public Task Started(bool awaiting) + { + int state = Volatile.Read(ref _state); + if (state == NotStarted) + { + throw new InvalidOperationException( + CaptureMessages.NotStarted(Display)); + } + + Task task = Task; + if (awaiting && state == StreamOpen && !task.IsCompleted) + { + throw new InvalidOperationException( + CaptureMessages.StreamOpen(Display)); + } + + return task; + } +} + +/// +/// A capture of an output model. +/// +/// The model type. +/// The model's layout. +sealed class ModelCapture(OutputLayout layout) + : CaptureSource( + $"CaptureOutput<{Shape.TypeName(typeof(TOut))}>", + CaptureKind.Model) +{ + // The members named for the messages as members of this capture. + public override ImmutableArray Members { get; } + = Named(layout); + + public override bool ReadsReturn => layout.HasReturnValue; + + static ImmutableArray Named(OutputLayout layout) + { + string capture = $"CaptureOutput<{Shape.TypeName(typeof(TOut))}>"; + var members = ImmutableArray.CreateBuilder( + layout.Members.Length); + foreach (OutputMember member in layout.Members) + { + members.Add(new OutputMember( + member, + $"{member.Display} of {capture}", + OutputForm.Capture)); + } + + return members.MoveToImmutable(); + } + + // As OutputRun.Map, over this capture's own values. + protected override TOut Read(OutputRun call, int start) + { + var row = new object?[layout.Labels.Length]; + for (int i = 0; i < layout.Members.Length; i++) + { + row[layout.Cells[i]] = call.Value(start + i); + } + return RowMap.Default.ArrayMapper(layout.Labels)(row); + } +} + +/// +/// A capture of one output parameter by name. +/// +/// The type of the value. +/// The layout of the one value. +/// The parameter's name. +/// The capture for the messages. +sealed class NamedCapture( + OutputLayout layout, + string name, + string display) + : CaptureSource(display, CaptureKind.Named) +{ + public override string? Name => name; + + public override ImmutableArray Members => layout.Members; + + // As OutputRun.Single; a decimal (not decimal?) refuses NULL with the + // message of the named form. + protected override TValue Read(OutputRun call, int start) + { + object? value = call.Value(start); + if (typeof(TValue) == typeof(decimal) && value is DBNull) + { + throw OutputArguments.DecimalNull(name, OutputForm.Capture); + } + + return RowMap.ConvertScalar(value); + } +} + +/// +/// A capture of the return code. +/// +/// The type of the value. +sealed class ReturnCapture() + : CaptureSource( + $"CaptureReturn<{Shape.TypeName(typeof(TValue))}>", + CaptureKind.Return) +{ + public override ImmutableArray Members { get; } + = [new OutputMember( + OutputLayout.ReturnValue, + $"CaptureReturn<{Shape.TypeName(typeof(TValue))}>", + named: true)]; + + // As ExecuteReturnAsync(). + protected override TValue Read(OutputRun call, int start) + => RowMap.ConvertScalar(call.Value(start)); +} + +/// +/// The captures a chain carries: what attaches them (), +/// or one run that fills them (). +/// +abstract class CaptureHolder +{ + /// Gets the captures. + public abstract CaptureSet Set { get; } + + /// Takes the captures for the run that is starting: claims them, + /// or enters the run that already did. + /// The token that governs the call. + /// The run. + /// The captures were used by an + /// earlier run. + public abstract CaptureRun Start(CancellationToken cancellationToken); + + /// Refuses the call: claims the captures (or throws that they were + /// used) and completes every one with the exception. + /// The exception the call throws. + /// The token, for a refusal that is a + /// cancel. + /// , to throw. + /// The captures were used by an + /// earlier run. + public abstract Exception Refuse( + Exception exception, + CancellationToken cancellationToken = default); + + /// Makes the exception of a synchronous terminal, which claims + /// nothing. + /// The exception. + public InvalidOperationException SyncRefused() + => new(CaptureMessages.Sync(Set)); +} + +/// +/// The captures attached to a chain value: immutable, so a copy made before a +/// capture has none. +/// +sealed class CaptureSet : CaptureHolder +{ + CaptureSet(ICaptureSource[] sources, bool onQuery) + { + Sources = sources; + OnQuery = onQuery; + Displays = sources.Length == 1 + ? sources[0].Display + : string.Join(" and ", sources.Select(static s => s.Display)); + + // One layout for the call, the captures' values one after another. + var members = ImmutableArray.CreateBuilder(); + Starts = new int[sources.Length]; + for (int i = 0; i < sources.Length; i++) + { + Starts[i] = members.Count; + members.AddRange(sources[i].Members); + ReadsReturn |= sources[i].ReadsReturn; + } + + Layout = new OutputLayout( + Displays, + members.ToImmutable(), + new int[members.Count], + []); + } + + /// The captures, in the order they were attached. + public readonly ICaptureSource[] Sources; + + /// The index of each capture's first value in + /// . + public readonly int[] Starts; + + /// Every value the captures read, as one call reads + /// them. + public readonly OutputLayout Layout; + + /// Whether a capture was attached on a mapped query (the messages + /// say "query"), not on the command. + public readonly bool OnQuery; + + /// Whether a capture reads the return code. + public readonly bool ReadsReturn; + + /// The captures for the messages. + public readonly string Displays; + + public override CaptureSet Set => this; + + /// Gets the word the messages use for the chain: "query" or + /// "command". + public string Noun => OnQuery ? "query" : "command"; + + /// + /// Returns the captures with one more, after checking that it reads nothing + /// another one reads. + /// + /// The captures so far, or + /// . + /// 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. + public static CaptureSet With( + CaptureSet? set, + ICaptureSource source, + bool onQuery, + bool isProcedure) + { + if (source.ReadsReturn && !isProcedure) + { + throw new InvalidOperationException( + CaptureMessages.NotProcedure(source)); + } + + if (set is null) return new([source], onQuery); + + string noun = onQuery ? "query" : "command"; + foreach (ICaptureSource other in set.Sources) + ThrowIfSameOwner(other, source, noun); + + return new([.. set.Sources, source], onQuery || set.OnQuery); + } + + // One owner per output and per return code: a model reads every output, so + // it shares them with no other capture. + static void ThrowIfSameOwner( + ICaptureSource first, + ICaptureSource second, + string noun) + { + if (first.Kind == CaptureKind.Model || second.Kind == CaptureKind.Model) + { + if (first.Kind != CaptureKind.Return + && second.Kind != CaptureKind.Return) + { + throw new InvalidOperationException( + $"This {noun} reads its output parameters twice: " + + $"{first.Display} and {second.Display}. " + + "Use one of them: one model capture, " + + "or named captures only."); + } + } + else if (first.Kind == CaptureKind.Named + && second.Kind == CaptureKind.Named + && DbQueryBinding.SameName(first.Name!, second.Name!)) + { + throw new InvalidOperationException( + $"This {noun} reads output parameter " + + $"@{first.Name!.TrimStart('@')} twice: " + + $"{first.Display} and {second.Display}. " + + "Capture each parameter once."); + } + + if (!first.ReadsReturn || !second.ReadsReturn) return; + + ICaptureSource model = first.Kind == CaptureKind.Model ? first : second; + ICaptureSource other = ReferenceEquals(model, first) ? second : first; + throw new InvalidOperationException(model.Kind == CaptureKind.Model + ? $"This {noun} reads its return code twice: " + + $"{other.Display} and the ReturnValue member of {model.Model}. " + + "Remove one, " + + "or rename the member with [Column] if it is a declared " + + "parameter." + : $"This {noun} reads its return code twice: " + + $"{first.Display} and {second.Display}. Remove one."); + } + + /// + /// Claims the captures for one run: the arm, once. + /// + /// The token that governs the call. + /// The run. + /// The captures were used by an + /// earlier run. + public CaptureRun Claim(CancellationToken cancellationToken) + { + var run = new CaptureRun(this); + run.Owners(cancellationToken); + run.Claim(); + return run; + } + + public override CaptureRun Start(CancellationToken cancellationToken) + => Claim(cancellationToken); + + public override Exception Refuse( + Exception exception, + CancellationToken cancellationToken = default) + { + Claim(cancellationToken).Fail(exception); + return exception; + } + + /// Makes the exception for a capture that reads the return code of + /// a command that is not a stored procedure. + /// The exception. + public InvalidOperationException NotProcedure() + { + foreach (ICaptureSource source in Sources) + { + if (source.ReadsReturn) + { + return new(CaptureMessages.NotProcedure(source)); + } + } + + return new(CaptureMessages.NotProcedure(Sources[0])); + } + + /// Gets the capture that reads the return code, or + /// . + public ICaptureSource? ReturnReader + { + get + { + foreach (ICaptureSource source in Sources) + { + if (source.ReadsReturn) return source; + } + + return null; + } + } +} + +/// +/// The one run that fills a set of captures: it holds what the run learns and +/// completes every capture, once. +/// +/// The captures. +sealed class CaptureRun(CaptureSet set) : CaptureHolder +{ + int _claimed; + int _entered; + int _stopped; + + // The tokens whose cancel is the caller's: a cancel by one of them + // completes the captures as canceled. A stream's own stop token is not one + // of them. + CancellationToken _first; + CancellationToken _second; + CancellationToken _third; + + public override CaptureSet Set => set; + + /// Sets the tokens whose cancel is the caller's. + /// The terminal's token. + /// The enumeration's token, for a stream. + /// The command's own token, for a stream. + public void Owners( + CancellationToken first, + CancellationToken second = default, + CancellationToken third = default) + { + _first = first; + _second = second; + _third = third; + } + + /// Adds the enumeration's token, which a stream learns at + /// GetAsyncEnumerator. + /// The enumeration's token. + public void Enumerating(CancellationToken enumeration) + => _second = enumeration; + + /// Gets whether a token of the caller is canceled. + public bool OwnerCanceled + => _first.IsCancellationRequested + || _second.IsCancellationRequested + || _third.IsCancellationRequested; + + CancellationToken CanceledOwner() + => _first.IsCancellationRequested ? _first + : _second.IsCancellationRequested ? _second + : _third; + + /// Gets or sets whether the consumer stopped early (a + /// break, a dispose), which delivers. + public bool ConsumerStopped + { + get => Volatile.Read(ref _stopped) != 0; + set => Volatile.Write(ref _stopped, value ? 1 : 0); + } + + /// Gets whether the run stopped because the consumer stopped, and + /// not because a token of the caller was canceled. + public bool StoppedByConsumer + => ConsumerStopped && !OwnerCanceled; + + /// Gets whether the command's run has started. + public bool Entered + => Volatile.Read(ref _entered) != 0; + + /// + /// The claim: arms the first capture with a compare-exchange, then the + /// others. + /// + /// The captures were used by an + /// earlier run; nothing is touched. + public void Claim() + { + ICaptureSource[] sources = set.Sources; + if (Interlocked.Exchange(ref _claimed, 1) != 0 || !sources[0].TryArm()) + throw new InvalidOperationException(CaptureMessages.SecondRun(set)); + + for (int i = 1; i < sources.Length; i++) sources[i].Arm(); + } + + public override CaptureRun Start(CancellationToken cancellationToken) + { + // A stream or a buffer claimed these at its call; the command's run + // enters once. + if (Volatile.Read(ref _claimed) == 0 + || Interlocked.Exchange(ref _entered, 1) != 0) + { + throw new InvalidOperationException(CaptureMessages.SecondRun(set)); + } + + return this; + } + + public override Exception Refuse( + Exception exception, + CancellationToken cancellationToken = default) + { + Fail(exception); + return exception; + } + + /// Marks every capture as belonging to a stream whose enumerator + /// is open, or no longer. + /// while the enumerator is + /// open. + public void SetStreamOpen(bool open) + { + foreach (ICaptureSource source in set.Sources) + { + source.SetStreamOpen(open); + } + } + + /// + /// Completes the captures from the call, once the response is complete. + /// + /// The call. + public void Deliver(OutputRun call) + { + // Before any conversion: a value that never arrived means the response + // did not complete, for the whole set. + int count = set.Layout.Members.Length; + for (int i = 0; i < count; i++) + { + if (call.Delivered(i)) continue; + + foreach (ICaptureSource source in set.Sources) + { + source.TrySetException(new InvalidOperationException( + CaptureMessages.NotDelivered(source))); + } + + return; + } + + for (int i = 0; i < set.Sources.Length; i++) + set.Sources[i].Deliver(call, set.Starts[i]); + } + + /// + /// Completes every capture that is not complete with the run's failure: + /// canceled when a token of the caller is, else faulted. + /// + /// The failure, which the terminal throws too, so + /// it is marked as seen. + public void Fail(Exception exception) + { + CancellationToken canceled = exception is OperationCanceledException + && OwnerCanceled + ? CanceledOwner() + : default; + + foreach (ICaptureSource source in set.Sources) + { + bool completed = canceled.IsCancellationRequested + ? source.TrySetCanceled(canceled) + : source.TrySetException(exception); + + if (completed) source.Observe(); + } + } + + /// + /// Completes any capture the run left pending. It never should: the run + /// completes them all. + /// + public void Backstop() + { + foreach (ICaptureSource source in set.Sources) + { + if (!source.IsCompleted) + { + source.TrySetException(new InvalidOperationException( + CaptureMessages.Internal(source))); + } + } + } + + /// + /// Completes the captures of a stream or a buffer whose run ended (or never + /// started) without completing them. + /// + /// The read's error, or . + public void Settle(Exception? error) + { + if (error is not null) Fail(error); + if (Entered) + { + Backstop(); + return; + } + + // The command never ran: canceled when a token of the caller is, else + // the query never ran. + CancellationToken canceled = CanceledOwner(); + foreach (ICaptureSource source in set.Sources) + { + if (source.IsCompleted) continue; + + if (canceled.IsCancellationRequested) + { + source.TrySetCanceled(canceled); + } + else + { + source.TrySetException(new InvalidOperationException( + CaptureMessages.NotRun(source))); + } + } + } +} + +/// +/// The ways to make a capture: each checks its arguments and its type at the +/// call, before anything is attached. +/// +static class Captures +{ + /// Makes the capture of an output model. + /// The model type. + /// The capture. + /// + /// cannot be read from output parameters. + public static CaptureSource Model() + => new ModelCapture(OutputLayout.Get(OutputForm.Capture)); + + /// Makes the capture of one output parameter by name. + /// The type of the value. + /// The parameter's name. + /// The capture. + public static CaptureSource Named(string name) + { + OutputArguments.ThrowIfNoName(name, OutputForm.Capture); + OutputLayout layout = OutputValue.Get(name, OutputForm.Capture); + return new NamedCapture( + layout, + name, + layout.Members[0].Display); + } + + /// Makes the capture of one decimal output parameter, read as + /// . + /// , or a + /// of it. + /// The parameter's name. + /// The precision. + /// The scale. + /// The capture. + public static CaptureSource Shaped( + string name, + byte precision, + byte scale) + { + OutputArguments.ThrowIfNoName(name, OutputForm.Capture); + OutputValue.ThrowUnlessDecimal(name, OutputForm.Capture); + return Decimal( + name, + precision, + scale, + $"CaptureOutput<{Shape.TypeName(typeof(TValue))}>" + + $"(\"{name}\", {precision}, {scale})"); + } + + /// Makes the capture of one decimal output parameter, read as a + /// of . + /// The parameter's name. + /// The precision. + /// The scale. + /// The capture. + public static CaptureSource Decimal( + string name, + byte precision, + byte scale) + { + OutputArguments.ThrowIfNoName(name, OutputForm.Capture); + return Decimal( + name, + precision, + scale, + $"CaptureOutputDecimal(\"{name}\", {precision}, {scale})"); + } + + // The one implementation of both decimal forms. + static NamedCapture Decimal( + string name, + byte precision, + byte scale, + string display) + { + OutputArguments.ThrowIfBadShape( + name, + precision, + scale, + OutputForm.Capture); + return new NamedCapture( + OutputValue.Shaped(name, precision, scale, display), + name, + display); + } + + /// Makes the capture of the return code. + /// The type of the value. + /// The capture. + /// + /// + /// is a model. + public static CaptureSource Return() + { + if (!ReturnCode.IsValue) + { + throw new InvalidOperationException( + CaptureMessages.ReturnModel(Shape.TypeName(typeof(TValue)))); + } + + return new ReturnCapture(); + } +} + +/// +/// The messages of the captures: each names the capture, says what is wrong and +/// what to do. +/// +static class CaptureMessages +{ + public static string NotStarted(string display) + => $"{display} has not started: " + + "the query it belongs to has not been run, " + + "so awaiting it would wait forever. " + + "Call the query's terminal first (for example ToListAsync, " + + "ExecuteNonQueryAsync or start the await foreach), " + + "then await the capture."; + + public static string NotComplete(string display) + => $"{display} is not complete yet, and blocking on it can deadlock. " + + "Use await on the capture; " + + "it completes when the query's results have been read to the end."; + + public static string Default(string type) + => $"This DbCapture<{type}> was never assigned. " + + "Declare it as the out argument of CaptureOutput(out …) " + + "or CaptureReturn(out …) on a query, " + + "then run that query before awaiting it."; + + public static string StreamOpen(string display) + => $"{display} completes when the stream has been read to the end, " + + "so awaiting it inside the loop would wait forever. " + + "Await it after the loop, or pass AsTask() " + + "on to code that runs after the loop."; + + public static string Sync(CaptureSet set) + => $"This {set.Noun} has {set.Displays}, " + + "and captures only work with async terminals. " + + $"Use the async form of this call (for example {(set.OnQuery + ? "ToListAsync instead of ToList" + : "ExecuteNonQueryAsync instead of ExecuteNonQuery")}), " + + "or remove the capture."; + + public static string SecondRun(CaptureSet set) + { + string was = set.Sources.Length == 1 ? "was" : "were"; + return set.OnQuery + ? $"{set.Displays} {was} already used by an earlier run of this " + + "query. " + + "A query with a capture runs once; build the query again, " + + "with a new capture, to run it again." + : $"{set.Displays} {was} already used by an earlier run of this " + + "command. " + + "Build the command again, with a new capture, " + + "to run it again."; + } + + public static string ExecuteAsync(CaptureSet set) + => $"{set.Displays} cannot be filled by ExecuteAsync(command => ...), " + + "because your code runs the command. " + + "Read the parameters from the command inside your function, " + + "or use a terminal such as ExecuteNonQueryAsync."; + + public static string OutputBeside(CaptureSet set, string call) + => "This command reads its output parameters twice: " + + $"{set.Displays} and {call}. " + + "Read the outputs with the capture or with ExecuteOutputAsync, " + + "not both."; + + public static string ReturnBeside(ICaptureSource source) + => "This command reads its return code twice: " + + $"{source.Display} and ExecuteReturnAsync. " + + "Remove one: await the capture, " + + "or remove the capture and use what ExecuteReturnAsync returns."; + + public static string CancelOnEarlyStop(CaptureSet set) + => $"{set.Displays} cannot be used with CancelOnEarlyStop(): " + + "a canceled command does not give its output parameters. " + + "Remove CancelOnEarlyStop(), or remove the capture."; + + public static string NotProcedure(ICaptureSource source) + => source.Kind == CaptureKind.Return + ? $"{source.Display} needs a stored procedure: " + + "a text command has no return code, " + + "and the provider would report 0. " + + "Call the procedure by name with StoredProcedure(…), " + + "or remove the capture." + : $"{source.Display} reads the return code into the ReturnValue " + + $"member of {source.Model}, " + + "which needs a stored procedure: " + + "a text command has no return code, " + + "and the provider would report 0. " + + "Call the procedure by name with StoredProcedure(…), " + + "or give the member [Column(\"name\")] to read an output " + + "parameter instead."; + + public static string NotDelivered(ICaptureSource source) + => (source.Kind == CaptureKind.Return + ? $"The return code of {source.Display} was never delivered" + : $"The output parameters of {source.Display} were never delivered") + + ": the response ended without them (a later statement failed, " + + "or the call was cut short). The procedure may still have run. " + + "Read the results to the end without stopping early, " + + "check the procedure for an error raised after its result sets, " + + "and treat the call as possibly committed."; + + public static string NotRun(ICaptureSource source) + => $"{source.Display} has no value: " + + "the stream was disposed before it read anything, " + + "so the query never ran. " + + "Enumerate the stream (await foreach) to the end, " + + "then await the capture."; + + public static string Internal(ICaptureSource source) + => $"{source.Display} was armed, " + + "but its run ended without completing it, " + + "which is a defect in this library. " + + "Run the query again with a new capture, and report the defect."; + + public static string ReturnModel(string type) + => "The return code is one integer, " + + $"so CaptureReturn<{type}> cannot hold it. " + + "Use CaptureReturn (or int?, long, an enum), " + + "or a ReturnValue member on the output model."; + + public static string NotFromDefinition(ICaptureSource source) + => $"{source.Display} needs a query built from an expressive command " + + "(connection.Command(…).Map()); " + + "a query from a DbQuery definition gets captures in a later release " + + "candidate. " + + "Build it from a command, " + + "or read the outputs with ExecuteOutputAsync."; + + public static string NotFromCommand(ICaptureSource source, Type reader) + => $"{source.Display} needs a query built from an expressive command " + + "(connection.Command(…).Map()), " + + "which adds the output parameters; " + + $"this query reads from {reader.Name}, which cannot. " + + "Build it from an expressive command, " + + "or read the outputs with ExecuteOutputAsync."; +} diff --git a/Source/Core/CapturedStream.cs b/Source/Core/CapturedStream.cs new file mode 100644 index 00000000..167d25d0 --- /dev/null +++ b/Source/Core/CapturedStream.cs @@ -0,0 +1,123 @@ +namespace Open.Database.Extensions; + +// A stream that fills captures (see Capture.cs). +// Its GetAsyncEnumerator is the claim (the arm), so a second enumeration, or +// a run of the command by another route, gets the second-run message. +// While its enumerator is open the captures may not be awaited: the loop +// that reads the stream would wait on itself. +// +// A consumer that stops early (a break, or a dispose before the last row) +// is told apart from a cancel of the caller: the read is not cancelled, the +// reader is closed, and closing it reads the rest of the response, the +// output parameters included, so the run delivers the captures. +// The inner stream's dispose waits for its read, so the captures are +// complete when this dispose returns. +/// +/// The stream of a query that fills captures. +/// +/// The type of the items. +/// The stream that reads the rows, over the run. +/// The run, claimed by +/// . +sealed class CapturedStream( + IAsyncEnumerable inner, + CaptureRun run) + : IAsyncEnumerable, IAsyncEnumerator +{ + IAsyncEnumerator? _inner; + Exception? _error; + int _taken; + int _disposed; + bool _ended; + + public TItem Current + => _inner!.Current; + + public IAsyncEnumerator GetAsyncEnumerator( + CancellationToken cancellationToken = default) + { + // A second enumeration gets the inner stream's own refusal. + if (Interlocked.Exchange(ref _taken, 1) != 0) + return inner.GetAsyncEnumerator(cancellationToken); + + run.Claim(); + run.Enumerating(cancellationToken); + run.SetStreamOpen(true); + try + { + _inner = inner.GetAsyncEnumerator(cancellationToken); + } + catch (Exception ex) + { + run.SetStreamOpen(false); + run.Settle(ex); + throw; + } + + return this; + } + + public ValueTask MoveNextAsync() + { + ValueTask next; + try + { + next = _inner!.MoveNextAsync(); + } + catch (Exception ex) + { + _error ??= ex; + throw; + } + + if (!next.IsCompletedSuccessfully) return AwaitNext(next); + + bool more = next.Result; + if (!more) _ended = true; + + return new(more); + } + + async ValueTask AwaitNext(ValueTask next) + { + try + { + bool more = await next.ConfigureAwait(false); + if (!more) _ended = true; + + return more; + } + catch (Exception ex) + { + // The run completes the captures with its own failure; this is + // for a read that never reached the command (see Settle). + _error ??= ex; + throw; + } + } + + public async ValueTask DisposeAsync() + { + if (Interlocked.Exchange(ref _disposed, 1) != 0) return; + + // Stopped before the end, by the consumer: the run delivers. + if (!_ended && _error is null && !run.OwnerCanceled) + run.ConsumerStopped = true; + + try + { + if (_inner is not null) + await _inner.DisposeAsync().ConfigureAwait(false); + } + catch (Exception ex) + { + _error ??= ex; + throw; + } + finally + { + run.SetStreamOpen(false); + run.Settle(_error); + } + } +} diff --git a/Source/Core/ChunkProducer.cs b/Source/Core/ChunkProducer.cs index 23eaa604..f4064937 100644 --- a/Source/Core/ChunkProducer.cs +++ b/Source/Core/ChunkProducer.cs @@ -165,6 +165,9 @@ public Task Start() Volatile.Write(ref _ended, 1); target.Finish(new OperationCanceledException(caller)); _linked.Dispose(); + + // The command never runs: a capture is completed as canceled. + query.CapturedRun?.Settle(null); return Task.CompletedTask; } @@ -183,9 +186,10 @@ public Task Start() TaskScheduler.Current) .Unwrap(); } - catch + catch (Exception ex) { _linked.Dispose(); + query.CapturedRun?.Settle(ex); throw; } } @@ -201,6 +205,17 @@ public void Cancel() { if (Volatile.Read(ref _ended) != 0) return; + // A captured read that the consumer stopped is not cancelled: a + // cancelled command gives no output parameters. The target refuses + // the next chunk instead, and the run delivers the captures once the + // reader is closed. A cancel of the caller's (an enumeration token + // this source is not linked to) still cancels the read. + if (query.CapturedRun is { OwnerCanceled: false } run) + { + run.ConsumerStopped = true; + return; + } + try { _linked.Cancel(); } catch { } } @@ -254,6 +269,10 @@ await query finally { _linked.Dispose(); + + // The run completed its captures; this completes any a read + // that never reached the command left pending. + query.CapturedRun?.Settle(error); } } @@ -310,6 +329,11 @@ void Advance() if (!target.Publish(full)) { full.Release(); + + // Refused: the owner disposed the target, which can come + // before its Cancel. A captured run delivers on this stop. + if (query.CapturedRun is { } run) run.ConsumerStopped = true; + throw new OperationCanceledException(); } } diff --git a/Source/Core/ChunkStream.cs b/Source/Core/ChunkStream.cs index 0fd91b9f..6492a930 100644 --- a/Source/Core/ChunkStream.cs +++ b/Source/Core/ChunkStream.cs @@ -83,11 +83,14 @@ namespace Open.Database.Extensions.Core; // the producer swallows a cancel only while its target says it is // disposed; otherwise a cancel that the stream caused would reach the // consumer as an error. -// - StreamTarget never refuses a publish (an unbounded -// channel with one writer always accepts), so every published array is in -// the channel or with the consumer; nothing is returned until the producer -// has ended, and the drain (after it) releases what the consumer did not -// take. +// - StreamTarget refuses a publish only once it is disposed (an +// unbounded channel with one writer always accepts), and the producer +// then releases the refused chunk itself. +// A captured read is not cancelled by the dispose (the cancel would lose +// the output parameters): the refusal is what stops it, at the next chunk. +// Every array the target took is in the channel or with the consumer; +// nothing is returned until the producer has ended, and the drain (after +// it) releases what the consumer did not take. // - The producer's first step runs on a thread of the current scheduler (see // ChunkProducer). // @@ -180,10 +183,10 @@ async IAsyncEnumerator> Read( target.Dispose(); producer.Cancel(); - // The producer cannot fault on this path (Publish is never - // refused here, so it never releases anything itself), but - // the drain is in a finally anyway: every array goes back - // whatever the wait does. + // The producer never faults (it reports every failure to the + // target, a release of a refused chunk included), but the + // drain is in a finally anyway: every array goes back whatever + // the wait does. try { await producerTask.ConfigureAwait(false); } finally { target.Drain(); } } @@ -225,8 +228,11 @@ bool IChunkTarget.IsDisposed int IChunkTarget.CapacityOf(int index) => _first << Math.Min(index, _lastDoubling); + // Refused once disposed: a captured read, which the dispose does not + // cancel, stops at the next chunk. bool IChunkTarget.Publish(ArrayLease chunk) - => _channel.Writer.TryWrite(chunk); + => Volatile.Read(ref _disposed) == 0 + && _channel.Writer.TryWrite(chunk); void IChunkTarget.Finish(Exception? error) => _channel.Writer.TryComplete(error); diff --git a/Source/Core/DbCapture.cs b/Source/Core/DbCapture.cs new file mode 100644 index 00000000..a2237a32 --- /dev/null +++ b/Source/Core/DbCapture.cs @@ -0,0 +1,219 @@ +namespace Open.Database.Extensions; + +// A readonly struct with one reference field: copies are the same capture. The +// awaiters are custom so that GetResult on a pending capture throws instead of +// blocking (the BCL TaskAwaiter blocks), and each member checks the source for +// null first, so a default value says it was never assigned. +/// +/// A value that a query's run fills after its rows: an output model, one output +/// parameter, or the return code. +/// It is the argument of a capture call; await it after +/// the query's terminal. +/// +/// +/// +/// +/// +/// The type of the value. +public readonly struct DbCapture +{ + internal DbCapture(CaptureSource source) + => Source = source; + + // Null in a default value, which every member refuses. + CaptureSource Source + => field ?? throw Unassigned(); + + CaptureSource Started(bool awaiting) + { + CaptureSource source = Source; + _ = source.Started(awaiting); + return source; + } + + static InvalidOperationException Unassigned() + => new(CaptureMessages.Default(Shape.TypeName(typeof(T)))); + + /// + /// Gets the awaiter that uses. + /// + /// The awaiter. + /// + /// + /// + /// + /// + public Awaiter GetAwaiter() + => new(Started(awaiting: true)); + + /// + /// Configures how an of the capture continues. + /// + /// to + /// continue on the captured context; otherwise, + /// . + /// An awaitable for the capture. + /// + /// + /// + /// + /// + public ConfiguredAwaitable ConfigureAwait(bool continueOnCapturedContext) + => new(Started(awaiting: true), continueOnCapturedContext); + + /// + /// Gets the capture as a task, to hand on to code that awaits it later. + /// + /// + /// It is the capture's one task: every call returns the same instance. + /// It is allowed while the capture's stream is still open, so the loop that + /// reads the stream can hand it to code that runs after the loop. + /// Await the task: its blocks until the + /// capture completes. + /// + /// The task, which completes with the capture. + /// + /// + /// + /// + public Task AsTask() + => Source.Started(awaiting: false); + + /// + /// The awaiter of a capture. + /// + /// + /// throws while the capture is not complete, + /// instead of blocking. + /// + public readonly struct Awaiter : ICriticalNotifyCompletion + { + readonly CaptureSource? _source; + + internal Awaiter(CaptureSource source) + => _source = source; + + Task Task + => (_source ?? throw Unassigned()).Task; + + /// + /// Gets whether the capture is complete. + /// + /// if the capture is complete; otherwise, + /// . + public bool IsCompleted + => Task.IsCompleted; + + /// + /// Gets the value of the complete capture, or throws its exception. + /// + /// The value. + /// + /// + /// + public T GetResult() + => DbCapture.GetResult(_source ?? throw Unassigned()); + + /// + public void OnCompleted(Action continuation) + => Task.GetAwaiter().OnCompleted(continuation); + + /// + public void UnsafeOnCompleted(Action continuation) + => Task.GetAwaiter().UnsafeOnCompleted(continuation); + } + + /// + /// What returns: an awaitable for the + /// capture. + /// + public readonly struct ConfiguredAwaitable + { + readonly CaptureSource? _source; + readonly bool _continueOnCapturedContext; + + internal ConfiguredAwaitable( + CaptureSource source, + bool continueOnCapturedContext) + { + _source = source; + _continueOnCapturedContext = continueOnCapturedContext; + } + + /// + /// Gets the awaiter that uses. + /// + /// The awaiter. + public ConfiguredAwaiter GetAwaiter() + => new(_source, _continueOnCapturedContext); + } + + /// + /// The awaiter of . + /// + /// + /// throws while the capture is not complete, + /// instead of blocking. + /// + public readonly struct ConfiguredAwaiter : ICriticalNotifyCompletion + { + readonly CaptureSource? _source; + readonly bool _continueOnCapturedContext; + + internal ConfiguredAwaiter( + CaptureSource? source, + bool continueOnCapturedContext) + { + _source = source; + _continueOnCapturedContext = continueOnCapturedContext; + } + + Task Task + => (_source ?? throw Unassigned()).Task; + + /// + public bool IsCompleted + => Task.IsCompleted; + + /// + public T GetResult() + => DbCapture.GetResult(_source ?? throw Unassigned()); + + /// + public void OnCompleted(Action continuation) + => Task.ConfigureAwait(_continueOnCapturedContext) + .GetAwaiter() + .OnCompleted(continuation); + + /// + public void UnsafeOnCompleted(Action continuation) + => Task.ConfigureAwait(_continueOnCapturedContext) + .GetAwaiter() + .UnsafeOnCompleted(continuation); + } + + // Never blocks: a pending capture throws. A complete one returns its value + // or rethrows its own exception. + static T GetResult(CaptureSource source) + { + Task task = source.Task; + if (!task.IsCompleted) + { + throw new InvalidOperationException( + CaptureMessages.NotComplete(source.Display)); + } + + return task.GetAwaiter().GetResult(); + } +} diff --git a/Source/Core/DirectStream.cs b/Source/Core/DirectStream.cs index 2c21399b..154ce8b2 100644 --- a/Source/Core/DirectStream.cs +++ b/Source/Core/DirectStream.cs @@ -320,6 +320,9 @@ void Tick() StopTimer(); + // A capture fails with the expiry, not with the cancel that follows. + _query.CapturedRun?.Fail(ToException()); + // The token is canceled first, then the read is woken with the exception, so it unwinds and cleans up, closing the reader and the connection. // With CancelOnEarlyStop(), the unwinding read cancels the command (see ReaderAbandon). try { _read!.Cancel(); } @@ -337,8 +340,14 @@ async ValueTask DisposeCoreAsync() StopTimer(); - try { _read!.Cancel(); } - catch { } + // A captured read is not cancelled: a cancelled command gives no + // output parameters. The wake below ends it, and the run delivers + // the captures once the reader is closed. + if (_query.CapturedRun is null) + { + try { _read!.Cancel(); } + catch { } + } // The read is parked: wake it with a cancel, so it unwinds, and cleans up, here. // If the watchdog got there first it did the waking; if the consumer was mid-pull the read sees the state and unwinds itself. diff --git a/Source/Core/ExpressiveCommandBase.Capture.cs b/Source/Core/ExpressiveCommandBase.Capture.cs new file mode 100644 index 00000000..4afd3c58 --- /dev/null +++ b/Source/Core/ExpressiveCommandBase.Capture.cs @@ -0,0 +1,367 @@ +using System.Diagnostics; + +namespace Open.Database.Extensions; + +/// +/// A command or the call of a command that a mapped query can hand its captures +/// to. +/// +/// +/// Implemented by the expressive commands only, which add the output +/// parameters; a mapped query over any other source refuses a capture at the +/// capture call. +/// +interface ICaptureRunner +{ + /// Gets the captures attached to the command, or + /// . + CaptureSet? Captures { get; } + + /// Gets whether the command is a stored procedure, which has a + /// return code. + bool IsProcedure { get; } + + /// Executes a reader on the command, filling the given + /// captures. + /// The type of the state. + /// The type of the result. + /// The captures: a set to claim, or a run a stream + /// or a buffer has claimed. + /// The state. + /// The function that reads the rows. + /// The behavior the reader is asked for. + /// The token that governs the call. + /// A task that produces the result of + /// . + ValueTask ExecuteReaderAsync( + CaptureHolder captures, + TState state, + Func> transform, + CommandBehavior behavior, + CancellationToken cancellationToken); +} + +// The captures of a command, and the run that fills the captures of a command +// or of a mapped query over it. A call without a capture pays one null check +// where it starts: ExecuteCoreAsync, ExecuteCore, ExecuteAsync, +// ExecuteReturnAsync. +public abstract partial class ExpressiveCommandBase< + TConnection, + TCommand, + TReader, + TDbType, + TThis> + : ICaptureRunner + where TConnection : class, IDbConnection + where TCommand : class, IDbCommand + where TReader : class, IDataReader + where TDbType : struct + where TThis : ExpressiveCommandBase< + TConnection, + TCommand, + TReader, + TDbType, + TThis> +{ + /// + /// The captures attached to this command, or . + /// + /// + /// A capture call replaces it with a new set (the command is mutable, as + /// AddParam is); a query made by Map runs on the + /// command and so uses it too, and the first run, by either route, claims + /// it. + /// + CaptureSet? _captures; + + /// + /// Reads the command's output parameters into a + /// when the next terminal runs it. + /// + /// + /// + public TThis CaptureOutput(out DbCapture output) + { + CaptureSource source = Captures.Model(); + Attach(source); + output = new(source); + return (TThis)this; + } + + /// + /// Reads one output parameter, converted to , + /// when the next terminal runs the command. + /// + /// + /// + public TThis CaptureOutput(string name, out DbCapture value) + { + CaptureSource source = Captures.Named(name); + Attach(source); + value = new(source); + return (TThis)this; + } + + /// + /// Reads one output parameter of the given precision + /// and scale, converted to , when the next + /// terminal runs the command. + /// + /// + /// + public TThis CaptureOutput( + string name, + byte precision, + byte scale, + out DbCapture value) + { + CaptureSource source = Captures.Shaped( + name, + precision, + scale); + Attach(source); + value = new(source); + return (TThis)this; + } + + /// + /// Reads one output parameter of the given precision + /// and scale when the next terminal runs the command. + /// + /// + /// + public TThis CaptureOutputDecimal( + string name, + byte precision, + byte scale, + out DbCapture value) + { + CaptureSource source = Captures.Decimal( + name, + precision, + scale); + Attach(source); + value = new(source); + return (TThis)this; + } + + /// + /// Reads the stored procedure's return code, converted to + /// , when the next terminal runs the command. + /// + /// + /// + public TThis CaptureReturn(out DbCapture returnCode) + { + CaptureSource source = Captures.Return(); + Attach(source); + returnCode = new(source); + return (TThis)this; + } + + void Attach(ICaptureSource source) + => _captures = CaptureSet.With( + _captures, + source, + onQuery: false, + Type == CommandType.StoredProcedure); + + CaptureSet? ICaptureRunner.Captures + => _captures; + + bool ICaptureRunner.IsProcedure + => Type == CommandType.StoredProcedure; + + ValueTask ICaptureRunner.ExecuteReaderAsync( + CaptureHolder captures, + TState state, + Func> transform, + CommandBehavior behavior, + CancellationToken cancellationToken) + => ExecuteReaderCoreAsync( + state, + transform, + behavior, + cancellationToken, + captures); + + /// + /// Runs a function on the command for a call that fills captures. + /// + /// + /// Its first statement is the claim (the arm), reached synchronously from + /// every async terminal. + /// The state of the command's own run is a + /// , so the build step adds the + /// captures' parameters, + /// and the captures are completed when the function returns, after the + /// reader is closed. + /// Every exit completes every capture: a failure faults them (or cancels + /// them, for the caller's cancel), and the backstop in the + /// completes any the run missed. + /// + /// The type of the state of the + /// terminal. + /// The type of the result. + /// The captures: a set to claim, or a run a stream + /// or a buffer has claimed. + /// The state of the terminal. + /// The function of the terminal. + /// The token that governs the call. + /// A task that produces the result of + /// . + async ValueTask ExecuteCapturedAsync( + CaptureHolder captures, + TState state, + Func> func, + CancellationToken cancellationToken) + { + CaptureRun run = captures.Start(cancellationToken); + try + { + Debug.Assert( + typeof(TState) != typeof(OutputRun), + "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. + if (run.Set.ReadsReturn && Type != CommandType.StoredProcedure) + { + throw run.Set.NotProcedure(); + } + + return await ExecutePlainAsync( + new CapturedCall(run, state, func), + CapturedCall.Invoke, + cancellationToken) + .ConfigureAwait(false); + } + catch (Exception ex) + { + run.Fail(ex); + throw; + } + finally + { + run.Backstop(); + } + } + + /// + /// A call that fills captures: the captures' output parameters, and the + /// terminal's own state and function. + /// + /// The type of the state of the + /// terminal. + /// The type of the result. + sealed class CapturedCall( + CaptureRun run, + TState state, + Func> func) + : OutputRun(run.Set.Layout) + { + readonly CaptureRun _run = run; + readonly TState _state = state; + readonly Func> + _func = func; + + /// The function the command's run calls: the terminal's + /// function, then the captures. + public static readonly + Func> + Invoke = InvokeAsync; + + static async ValueTask InvokeAsync( + TCommand command, + ConnectionState prior, + OutputRun output) + { + var call = (CapturedCall)output; + TResult result; + try + { + result = await call._func(command, prior, call._state) + .ConfigureAwait(false); + } + catch (OperationCanceledException) + when (call._run.StoppedByConsumer) + { + // The consumer stopped early (a break, a dispose): the reader + // is closed, and closing it read the rest of the response, the + // outputs included. The stream's own stop is not the caller's + // failure. + call._run.Deliver(call); + throw; + } + + call._run.Deliver(call); + return result; + } + } + + /// + /// Refuses ExecuteOutputAsync on a command that carries a capture: + /// two readers of one parameter set. + /// + /// The ExecuteOutputAsync form, for the + /// message. + /// The command carries a + /// capture; the capture is completed with the same exception. + void RefuseBesideCaptures(string call) + { + if (_captures is { } captures) + { + throw captures.Refuse( + new InvalidOperationException( + CaptureMessages.OutputBeside(captures, call))); + } + } + + /// + /// Throws when the command's token or the call's is canceled; a capture on + /// the command is completed as canceled. + /// + /// The token passed to the terminal. + /// A token is + /// canceled. + void ThrowIfCanceled(CancellationToken callToken) + { + CancellationToken canceled = CancellationToken.IsCancellationRequested + ? CancellationToken + : callToken; + if (!canceled.IsCancellationRequested) return; + + var exception = new OperationCanceledException(canceled); + if (_captures is { } captures) + { + throw captures.Refuse(exception, canceled); + } + + throw exception; + } + + /// + /// Makes the exception of a missing argument of an asynchronous terminal; a + /// capture on the command is faulted with it. + /// + /// The argument's name. + /// The exception, to throw. + private protected Exception NullArgument(string name) + { + var exception = new ArgumentNullException(name); + return _captures is { } captures + ? captures.Refuse(exception) + : exception; + } +} diff --git a/Source/Core/ExpressiveCommandBase.Output.cs b/Source/Core/ExpressiveCommandBase.Output.cs index 55c5e4cb..fbec6c23 100644 --- a/Source/Core/ExpressiveCommandBase.Output.cs +++ b/Source/Core/ExpressiveCommandBase.Output.cs @@ -69,6 +69,10 @@ public ValueTask ExecuteOutputAsync( OutputLayout layout = OutputLayout.Get(); if (layout.HasReturnValue) ThrowUnlessProcedure(layout); + // Before the cancel: a capture on the command is completed by the + // refusal. + RefuseBesideCaptures($"ExecuteOutputAsync<{layout.Model}>()"); + // Thrown synchronously, not through the returned task. CancellationToken.ThrowIfCancellationRequested(); cancellationToken.ThrowIfCancellationRequested(); @@ -209,12 +213,7 @@ static ValueTask Same(ValueTask value) /// The value is NULL. static async ValueTask NotNullAsync(string name, ValueTask value) => await value.ConfigureAwait(false) - ?? throw new ValueMappingException( - $"The decimal output parameter '{name}' is NULL, which a decimal cannot hold. " - + $"Read it as decimal? (ExecuteOutputAsync(\"{name}\", precision, scale)) or with ExecuteOutputDecimalAsync(\"{name}\", precision, scale), which return null for NULL.", - name, - name, - typeof(decimal)); + ?? throw OutputArguments.DecimalNull(name, OutputForm.Execute); /// /// Asynchronously executes the command, as @@ -265,38 +264,23 @@ static async ValueTask NotNullAsync(string name, ValueTask va return RunNamedAsync(OutputValue.Shaped(name, precision, scale), cancellationToken); } - // One rule with [Column(TypeName = "decimal(p,s)")]: OutputWire.IsDecimalShape. - static void ThrowIfBadShape(string name, byte precision, byte scale) - { - if (OutputWire.IsDecimalShape(precision, scale)) return; - - if (precision is 0 or > 38) - { - throw new ArgumentOutOfRangeException( - nameof(precision), - precision, - $"The precision of the decimal output parameter '{name}' is {precision}, but it must be from 1 to 38: the number of digits its SQL type declares. " - + $"For decimal(19,4), pass ExecuteOutputAsync(\"{name}\", 19, 4)."); - } - - throw new ArgumentOutOfRangeException( - nameof(scale), - scale, - $"The scale of the decimal output parameter '{name}' is {scale}, more than its precision of {precision}: the scale counts the digits after the decimal point, out of the precision. " - + $"For decimal(19,4), pass ExecuteOutputAsync(\"{name}\", 19, 4)."); - } - - const string NameRequired = "A parameter name is required, for example ExecuteOutputAsync(\"total\")."; - // First in each named form: a model type with a null name binds here (ExecuteOutputAsync(null) compiles). static void ThrowIfNoName(string name) - { - if (name is null) throw new ArgumentNullException(nameof(name), NameRequired); - if (string.IsNullOrWhiteSpace(name) || name.Trim() == "@") throw new ArgumentException(NameRequired, nameof(name)); - } + => OutputArguments.ThrowIfNoName(name, OutputForm.Execute); + + static void ThrowIfBadShape(string name, byte precision, byte scale) + => OutputArguments.ThrowIfBadShape( + name, + precision, + scale, + OutputForm.Execute); ValueTask RunNamedAsync(OutputLayout layout, CancellationToken cancellationToken) { + // Before the cancel: a capture on the command is completed by the + // refusal. + RefuseBesideCaptures($"ExecuteOutputAsync(\"{layout.Model}\")"); + // Thrown synchronously, not through the returned task. CancellationToken.ThrowIfCancellationRequested(); cancellationToken.ThrowIfCancellationRequested(); @@ -406,7 +390,14 @@ void ResolveOutputs(OutputRun run, NameSet? names) if (member.IsReturnValue) { // Only a stored procedure gets here (checked at the call): no declared parameter may also answer to the name. - if (known && real!.Match(OutputLayout.ReturnValue, Command, member.Display) is { } declared) + // CaptureReturn asks for the return code itself, not by a + // member's name, so nothing can be mistaken for it. + if (!member.Named + && known + && real!.Match( + OutputLayout.ReturnValue, + Command, + member.Display) is { } declared) { throw new InvalidOperationException( $"{member.Display} reads the return code, but {where} also declares the parameter '{declared}', which the name {OutputLayout.ReturnValue} matches, so it is unclear which one to read. " @@ -423,7 +414,7 @@ void ResolveOutputs(OutputRun run, NameSet? names) } resolved[i] = (member.Exact ? real!.Find(member.Name)?.Real : real!.Match(member.Name, Command, member.Display)) - ?? throw NoOutputMatch(member, layout, real.Names, where); + ?? throw NoOutputMatch(member, real.Names, where); } // Two members that resolve to one parameter would read the same value under two meanings. @@ -443,15 +434,27 @@ void ResolveOutputs(OutputRun run, NameSet? names) run.Names = resolved; } - static InvalidOperationException NoOutputMatch(OutputMember member, OutputLayout layout, ImmutableArray real, string where) + static InvalidOperationException NoOutputMatch( + OutputMember member, + ImmutableArray real, + string where) { string declared = string.Join(", ", real); - if (layout.IsNamed) + if (member.Named) { // A decimal reaches here through the form that takes a precision and scale; any other type through the plain named form. + bool capture = member.Form == OutputForm.Capture; string call = member.Wire!.Type == DbType.Decimal - ? "Pass one of those names to ExecuteOutputAsync(name, precision, scale) or ExecuteOutputDecimalAsync(name, precision, scale)" - : "Pass one of those names to ExecuteOutputAsync(name)"; + ? capture + ? "Pass one of those names to CaptureOutput(name, " + + "precision, scale, out …) or CaptureOutputDecimal(name, " + + "precision, scale, out …)" + : "Pass one of those names to " + + "ExecuteOutputAsync(name, precision, scale) " + + "or ExecuteOutputDecimalAsync(name, precision, scale)" + : capture + ? "Pass one of those names to CaptureOutput(name, out …)" + : "Pass one of those names to ExecuteOutputAsync(name)"; return new( $"{member.Display} is not a parameter of {where}, which declares: {declared}. " diff --git a/Source/Core/ExpressiveCommandBase.cs b/Source/Core/ExpressiveCommandBase.cs index b0037a4d..b2aa9207 100644 --- a/Source/Core/ExpressiveCommandBase.cs +++ b/Source/Core/ExpressiveCommandBase.cs @@ -1170,6 +1170,10 @@ InvalidOperationException NoMatch(string expression, ImmutableArray real /// The result of . private protected TResult ExecuteCore(TState state, Func func) { + // Captures are async only: refused before anything runs, and nothing is + // claimed. + if (_captures is { } captures) throw captures.SyncRefused(); + if (_poolOrConnection is TConnection single) return ExecuteDirect(single, state, func); @@ -1232,6 +1236,36 @@ private protected ValueTask ExecuteCombinedAsync( private protected ValueTask ExecuteCoreAsync(TState state, Func> func) => ExecuteCoreAsync(state, func, CancellationToken); + /// + /// Runs a function on a command built on a connection from the source, + /// asynchronously, filling the captures of the call if it has any. + /// + /// + /// Without a capture this is the plain run (one null check); with one, the + /// captured run, whose first statement claims it. + /// + /// The type of the state passed to the + /// function. + /// The type of the result. + /// The state to pass to the function. + /// The function to run. + /// The token that governs the call. + /// The captures of a mapped query (its own, or a run + /// its stream or buffer claimed), or for the + /// command's own. + /// A task that represents the asynchronous operation; its result + /// is the result of . + // Not async: the plain run keeps its own state machine, so a call without a + // capture allocates nothing more. + private protected ValueTask ExecuteCoreAsync( + TState state, + Func> func, + CancellationToken cancellationToken, + CaptureHolder? captures = null) + => (captures ?? _captures) is { } holder + ? ExecuteCapturedAsync(holder, state, func, cancellationToken) + : ExecutePlainAsync(state, func, cancellationToken); + /// /// Runs a function on a command built on a connection from the source, /// asynchronously. @@ -1250,7 +1284,10 @@ private protected ValueTask ExecuteCoreAsync(TState st /// /// is already canceled. /// - private protected async ValueTask ExecuteCoreAsync(TState state, Func> func, CancellationToken cancellationToken) + async ValueTask ExecutePlainAsync( + TState state, + Func> func, + CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // Since cancelled awaited tasks throw, we will follow the same pattern here. @@ -1422,6 +1459,14 @@ public virtual ValueTask ExecuteAsync(Func handler) if (handler is null) throw new ArgumentNullException(nameof(handler)); Contract.EndContractBlock(); + // Your code runs the command, so nothing can fill a capture: refused, + // and the capture completed with the refusal. + if (_captures is { } captures) + { + throw captures.Refuse(new InvalidOperationException( + CaptureMessages.ExecuteAsync(captures))); + } + CancellationToken.ThrowIfCancellationRequested(); // Thrown synchronously, not through the returned task. // Completes a ValueTask as a plain ValueTask without allocating when it has already finished. @@ -1438,6 +1483,13 @@ public virtual ValueTask ExecuteAsync(Func> transfo if (transform is null) throw new ArgumentNullException(nameof(transform)); Contract.EndContractBlock(); + // As above. + if (_captures is { } captures) + { + throw captures.Refuse(new InvalidOperationException( + CaptureMessages.ExecuteAsync(captures))); + } + CancellationToken.ThrowIfCancellationRequested(); // Thrown synchronously, not through the returned task. return ExecuteCoreAsync(transform, static (cmd, _, f) => f(cmd)); @@ -1575,7 +1627,12 @@ ValueTask IExecuteReader.ExecuteReaderAsync( CommandBehavior behavior) => ExecuteReaderAsync(handler, behavior, default); - ValueTask ExecuteReaderCoreAsync(TState state, Func> transform, CommandBehavior behavior, CancellationToken cancellationToken) + ValueTask ExecuteReaderCoreAsync( + TState state, + Func> transform, + CommandBehavior behavior, + CancellationToken cancellationToken, + CaptureHolder? captures = null) => ExecuteCoreAsync((state, transform, behavior: WithAccess(behavior), cancellationToken), static async (cmd, prior, s) => { ReaderAbandon.ArmFor(s.transform, cmd); @@ -1593,7 +1650,7 @@ ValueTask ExecuteReaderCoreAsync(TState state, Func internal void ExecuteReader(Action handler, CommandBehavior behavior = CommandBehavior.Default) @@ -1855,10 +1912,20 @@ ValueTask IExecuteReader.ExecuteReaderAsync(Func public ValueTask ExecuteReturnAsync( CancellationToken cancellationToken = default) { + // A capture of the return code and this would read it twice: refused, + // and the capture completed with the refusal. + if (_captures?.ReturnReader is { } returnReader) + { + throw _captures.Refuse( + new InvalidOperationException( + CaptureMessages.ReturnBeside(returnReader)), + cancellationToken); + } + // Thrown synchronously, not through the returned task: - // both tokens are checked before anything is linked. - CancellationToken.ThrowIfCancellationRequested(); - cancellationToken.ThrowIfCancellationRequested(); + // both tokens are checked before anything is linked (a capture on the + // command is completed as canceled). + ThrowIfCanceled(cancellationToken); return ExecuteCombinedAsync(cancellationToken, static async (cmd, _, token) => { diff --git a/Source/Core/ExpressiveDbCommandBase.cs b/Source/Core/ExpressiveDbCommandBase.cs index 1a9aa6cb..11389fa0 100644 --- a/Source/Core/ExpressiveDbCommandBase.cs +++ b/Source/Core/ExpressiveDbCommandBase.cs @@ -1,4 +1,4 @@ -namespace Open.Database.Extensions; +namespace Open.Database.Extensions; /// /// Represents the base class of the expressive commands that execute on a @@ -180,7 +180,8 @@ public async ValueTask ExecuteScalarAsync( Func transform, CancellationToken cancellationToken = default) { - if (transform is null) throw new ArgumentNullException(nameof(transform)); + // A capture on the command is faulted with it. + if (transform is null) throw NullArgument(nameof(transform)); Contract.EndContractBlock(); return transform( @@ -221,7 +222,8 @@ public async ValueTask ExecuteScalarAsync( Func> transform, CancellationToken cancellationToken = default) { - if (transform is null) throw new ArgumentNullException(nameof(transform)); + // A capture on the command is faulted with it. + if (transform is null) throw NullArgument(nameof(transform)); Contract.EndContractBlock(); return await transform( diff --git a/Source/Core/MappedQuery.Capture.cs b/Source/Core/MappedQuery.Capture.cs new file mode 100644 index 00000000..38d8de0e --- /dev/null +++ b/Source/Core/MappedQuery.Capture.cs @@ -0,0 +1,376 @@ +namespace Open.Database.Extensions; + +// The captures of a mapped query (see Capture.cs). A query holds its own +// captures in MappedQueryCore, appended to its command's; a query without its +// own runs on its command, which fills the command's. Every builder carries +// them, and they are part of the equality by reference. The async run hands +// them to the command (ICaptureRunner); a synchronous run refuses them. +readonly partial struct MappedQueryCore +{ + /// + /// Gets the captures a run of this query fills: its own, or else its + /// command's. + /// + /// The captures, or . + // For the streams, the buffer and CancelOnEarlyStop() only: a direct + // terminal without its own captures runs on the command, which checks its + // own. + CaptureHolder? Captured() + => _captures ?? (_command as ICaptureRunner)?.Captures; + + /// + /// Gets the run a stream or a buffer claimed, or . + /// + public CaptureRun? CapturedRun + => _captures as CaptureRun; + + /// + /// Returns the query with one more capture. + /// + /// 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 + /// capture that reads what another one reads. + /// The query does not read from an + /// expressive command. + public MappedQueryCore WithCapture(ICaptureSource source) + { + EnsureCommand(); + if (_call.IsBound) + { + throw new NotSupportedException( + CaptureMessages.NotFromDefinition(source)); + } + if (_command is not ICaptureRunner runner) + { + throw new NotSupportedException( + CaptureMessages.NotFromCommand(source, _command!.GetType())); + } + + // Appended to the command's, so the query and the command share the + // first capture, and one run claims them. + CaptureSet captures = CaptureSet.With( + _captures as CaptureSet ?? runner.Captures, + source, + onQuery: true, + runner.IsProcedure); + return new( + _command, + _call, + _source, + _skip, + _take, + _singleResult, + _asyncReads, + _cancelOnEarlyStop, + _sequentialAccess, + Config, + captures); + } + + /// + /// Returns the query over the run a stream or a buffer claimed; never + /// handed to a caller. + /// + /// The run. + /// The query for the stream or the buffer to read. + MappedQueryCore WithRun(CaptureRun run) + => new( + _command, + _call, + _source, + _skip, + _take, + _singleResult, + _asyncReads, + _cancelOnEarlyStop, + _sequentialAccess, + Config, + run); + + /// + /// Makes the run of a stream, claimed later by its + /// GetAsyncEnumerator. + /// + /// The captures. + /// The caller's token. + /// The run, not claimed yet. + CaptureRun StreamRun( + CaptureSet captures, + CancellationToken cancellationToken) + { + var run = new CaptureRun(captures); + run.Owners(cancellationToken, default, _command!.CancellationToken); + return run; + } + + /// + /// Starts a pooled buffer that fills captures: claimed at the call, since + /// the buffer starts its read at the call. + /// + /// The captures. + /// The caller's token. + /// The buffer, already reading. + PooledBuffer CapturedBuffer( + CaptureSet captures, + CancellationToken cancellationToken) + { + CaptureRun run = captures.Claim(cancellationToken); + run.Owners(cancellationToken, default, _command!.CancellationToken); + try + { + return new(WithRun(run), Config, cancellationToken); + } + catch (Exception ex) + { + // The read did not start (a scheduler that refused it): the + // captures are completed with its failure. + run.Fail(ex); + throw; + } + } +} + +public readonly partial record struct MappedQuery +{ + /// + /// Reads the command's output parameters into a + /// when the query's terminal runs. + /// + /// + /// + public MappedQuery CaptureOutput(out DbCapture output) + { + CaptureSource source = Captures.Model(); + MappedQuery captured = new(_core.WithCapture(source)); + output = new(source); + return captured; + } + + /// + /// Reads one output parameter, converted to , + /// when the query's terminal runs. + /// + /// + /// + public MappedQuery CaptureOutput( + string name, + out DbCapture value) + { + CaptureSource source = Captures.Named(name); + MappedQuery captured = new(_core.WithCapture(source)); + value = new(source); + return captured; + } + + /// + /// Reads one output parameter of the given precision + /// and scale, converted to , when the query's + /// terminal runs. + /// + /// + /// + public MappedQuery CaptureOutput( + string name, + byte precision, + byte scale, + out DbCapture value) + { + CaptureSource source = Captures.Shaped( + name, + precision, + scale); + MappedQuery captured = new(_core.WithCapture(source)); + value = new(source); + return captured; + } + + /// + /// Reads one output parameter of the given precision + /// and scale when the query's terminal runs. + /// + /// + /// + public MappedQuery CaptureOutputDecimal( + string name, + byte precision, + byte scale, + out DbCapture value) + { + CaptureSource source = Captures.Decimal( + name, + precision, + scale); + MappedQuery captured = new(_core.WithCapture(source)); + value = new(source); + return captured; + } + + /// + /// Reads the stored procedure's return code, converted to + /// , when the query's terminal runs. + /// + /// + /// + public MappedQuery CaptureReturn( + out DbCapture returnCode) + { + CaptureSource source = Captures.Return(); + MappedQuery captured = new(_core.WithCapture(source)); + returnCode = new(source); + return captured; + } +} + +public readonly partial record struct MappedQueryWithSkip +{ + /// + public MappedQueryWithSkip CaptureOutput( + out DbCapture output) + { + CaptureSource source = Captures.Model(); + MappedQueryWithSkip captured = new(_core.WithCapture(source)); + output = new(source); + return captured; + } + + /// + public MappedQueryWithSkip CaptureOutput( + string name, + out DbCapture value) + { + CaptureSource source = Captures.Named(name); + MappedQueryWithSkip captured = new(_core.WithCapture(source)); + value = new(source); + return captured; + } + + /// + public MappedQueryWithSkip CaptureOutput( + string name, + byte precision, + byte scale, + out DbCapture value) + { + CaptureSource source = Captures.Shaped( + name, + precision, + scale); + MappedQueryWithSkip captured = new(_core.WithCapture(source)); + value = new(source); + return captured; + } + + /// + public MappedQueryWithSkip CaptureOutputDecimal( + string name, + byte precision, + byte scale, + out DbCapture value) + { + CaptureSource source = Captures.Decimal( + name, + precision, + scale); + MappedQueryWithSkip captured = new(_core.WithCapture(source)); + value = new(source); + return captured; + } + + /// + public MappedQueryWithSkip CaptureReturn( + out DbCapture returnCode) + { + CaptureSource source = Captures.Return(); + MappedQueryWithSkip captured = new(_core.WithCapture(source)); + returnCode = new(source); + return captured; + } +} + +public readonly partial record struct MappedQueryWithTake +{ + /// + public MappedQueryWithTake CaptureOutput( + out DbCapture output) + { + CaptureSource source = Captures.Model(); + MappedQueryWithTake captured = new(_core.WithCapture(source)); + output = new(source); + return captured; + } + + /// + public MappedQueryWithTake CaptureOutput( + string name, + out DbCapture value) + { + CaptureSource source = Captures.Named(name); + MappedQueryWithTake captured = new(_core.WithCapture(source)); + value = new(source); + return captured; + } + + /// + public MappedQueryWithTake CaptureOutput( + string name, + byte precision, + byte scale, + out DbCapture value) + { + CaptureSource source = Captures.Shaped( + name, + precision, + scale); + MappedQueryWithTake captured = new(_core.WithCapture(source)); + value = new(source); + return captured; + } + + /// + public MappedQueryWithTake CaptureOutputDecimal( + string name, + byte precision, + byte scale, + out DbCapture value) + { + CaptureSource source = Captures.Decimal( + name, + precision, + scale); + MappedQueryWithTake captured = new(_core.WithCapture(source)); + value = new(source); + return captured; + } + + /// + public MappedQueryWithTake CaptureReturn( + out DbCapture returnCode) + { + CaptureSource source = Captures.Return(); + MappedQueryWithTake captured = new(_core.WithCapture(source)); + returnCode = new(source); + return captured; + } +} diff --git a/Source/Core/MappedQuery.cs b/Source/Core/MappedQuery.cs index ad191eb8..77a4fe2b 100644 --- a/Source/Core/MappedQuery.cs +++ b/Source/Core/MappedQuery.cs @@ -150,7 +150,10 @@ public static MappedQuery Map( /// to cancel the command when a terminal stops before the last row; otherwise, . /// to ask the reader for ; otherwise, . /// The pool, the clear rule, the chunk sizes and the bin the pooling terminals use. -readonly struct MappedQueryCore( +/// The captures attached on the query, a run its stream +/// or buffer claimed, or (a query without its own runs +/// on its command, which uses the command's). +readonly partial struct MappedQueryCore( IExecuteReader? command, DbQueryCall call, IRowSource source, @@ -160,7 +163,8 @@ readonly struct MappedQueryCore( bool asyncReads, bool cancelOnEarlyStop, bool sequentialAccess, - ChunkConfig config) + ChunkConfig config, + CaptureHolder? captures = null) : IEquatable> { readonly IRowSource _source = source; @@ -170,6 +174,8 @@ readonly struct MappedQueryCore( readonly bool _asyncReads = asyncReads; // AsyncReads() was called: the rows of an async terminal are read with ReadAsync (the default is Read). readonly bool _cancelOnEarlyStop = cancelOnEarlyStop; // CancelOnEarlyStop() was called: see ReaderAbandon. readonly bool _sequentialAccess = sequentialAccess; // SequentialAccess() was called on the query. + // See MappedQuery.Capture.cs; part of the equality, by reference. + readonly CaptureHolder? _captures = captures; /// /// The command, or for a default value. @@ -245,7 +251,8 @@ public bool Equals(MappedQueryCore other) && _asyncReads == other._asyncReads && _cancelOnEarlyStop == other._cancelOnEarlyStop && _sequentialAccess == other._sequentialAccess - && ReferenceEquals(Config, other.Config); + && ReferenceEquals(Config, other.Config) + && ReferenceEquals(_captures, other._captures); public override bool Equals(object? obj) => obj is MappedQueryCore other && Equals(other); @@ -263,7 +270,10 @@ public override int GetHashCode() + (_cancelOnEarlyStop ? 4 : 0) + (_singleResult ? 2 : 0) + (_asyncReads ? 1 : 0) - + RuntimeHelpers.GetHashCode(Config); // Reference equality, null for a default value. + // Reference equality, null for a default value. + + RuntimeHelpers.GetHashCode(Config) + // Reference equality, null without a capture. + + RuntimeHelpers.GetHashCode(_captures) * 7; } } @@ -276,13 +286,65 @@ CommandBehavior Behavior => (_singleResult ? CommandBehavior.SingleResult : CommandBehavior.Default) | (_sequentialAccess ? CommandBehavior.SequentialAccess : CommandBehavior.Default); - public MappedQueryCore WithSingleResult() => Checked(new(_command, _call, _source, _skip, _take, true, _asyncReads, _cancelOnEarlyStop, _sequentialAccess, Config)); + public MappedQueryCore WithSingleResult() + => Checked( + new( + _command, + _call, + _source, + _skip, + _take, + true, + _asyncReads, + _cancelOnEarlyStop, + _sequentialAccess, + Config, + _captures)); - public MappedQueryCore WithAsyncReads() => Checked(new(_command, _call, _source, _skip, _take, _singleResult, true, _cancelOnEarlyStop, _sequentialAccess, Config)); + public MappedQueryCore WithAsyncReads() + => Checked( + new( + _command, + _call, + _source, + _skip, + _take, + _singleResult, + true, + _cancelOnEarlyStop, + _sequentialAccess, + Config, + _captures)); - public MappedQueryCore WithCancelOnEarlyStop() => Checked(new(_command, _call, _source, _skip, _take, _singleResult, _asyncReads, true, _sequentialAccess, Config)); + public MappedQueryCore WithCancelOnEarlyStop() + => Checked( + new( + _command, + _call, + _source, + _skip, + _take, + _singleResult, + _asyncReads, + true, + _sequentialAccess, + Config, + _captures)); - public MappedQueryCore WithSequentialAccess() => Checked(new(_command, _call, _source, _skip, _take, _singleResult, _asyncReads, _cancelOnEarlyStop, true, Config)); + public MappedQueryCore WithSequentialAccess() + => Checked( + new( + _command, + _call, + _source, + _skip, + _take, + _singleResult, + _asyncReads, + _cancelOnEarlyStop, + true, + Config, + _captures)); /// /// Gets the configuration the query was given. @@ -319,11 +381,38 @@ public MappedQueryCore WithPool(ArrayPool pool, bool clearOnReturn) /// The configuration to use. /// A copy of the query that uses . public MappedQueryCore WithConfig(ChunkConfig config) - => Checked(new(_command, _call, _source, _skip, _take, _singleResult, _asyncReads, _cancelOnEarlyStop, _sequentialAccess, config)); + => Checked( + new( + _command, + _call, + _source, + _skip, + _take, + _singleResult, + _asyncReads, + _cancelOnEarlyStop, + _sequentialAccess, + config, + _captures)); /// Returns the same query over another call. + /// The query carries a capture, + /// which only a command can fill. public MappedQueryCore WithCall(DbQueryCall call) - => new(null, call, _source, _skip, _take, _singleResult, _asyncReads, _cancelOnEarlyStop, _sequentialAccess, Config); + => _captures is null + ? new( + null, + call, + _source, + _skip, + _take, + _singleResult, + _asyncReads, + _cancelOnEarlyStop, + _sequentialAccess, + Config) + : throw new InvalidOperationException( + CaptureMessages.NotFromDefinition(_captures.Set.Sources[0])); public MappedQueryCore WithSkip(int count) => count >= 0 @@ -337,7 +426,8 @@ public MappedQueryCore WithSkip(int count) _asyncReads, _cancelOnEarlyStop, _sequentialAccess, - Config)) + Config, + _captures)) : throw new ArgumentOutOfRangeException(nameof(count), count, "Cannot be negative."); /// @@ -360,7 +450,8 @@ public MappedQueryCore WithTake(int count) _asyncReads, _cancelOnEarlyStop, _sequentialAccess, - Config)) + Config, + _captures)) : throw new ArgumentOutOfRangeException(nameof(count), count, "Cannot be negative."); /// @@ -468,16 +559,29 @@ ValueTask ExecuteAsync(TState state, FuncRuns the reader function on the call, held as it is, or on the command. + // Captures are async only: a synchronous run is refused before anything + // runs, and nothing is claimed. TResult ExecuteReader(TState state, Func transform, CommandBehavior behavior) - => _call.IsBound - ? _call.Run(state, transform, behavior) - : Command.AsSync().ExecuteReader(state, transform, behavior); + => _captures is not null + ? throw _captures.SyncRefused() + : _call.IsBound + ? _call.Run(state, transform, behavior) + : Command.AsSync().ExecuteReader(state, transform, behavior); /// Runs the asynchronous reader function on the call, held as it is, or on the command. + // With captures, the command fills them (only a command can be given them: + // see WithCapture). ValueTask ExecuteReaderAsync(TState state, Func> transform, CommandBehavior behavior, CancellationToken token) - => _call.IsBound - ? _call.RunAsync(state, transform, behavior, token) - : Command.ExecuteReaderAsync(state, transform, behavior, token); + => _captures is not null + ? ((ICaptureRunner)_command!).ExecuteReaderAsync( + _captures, + state, + transform, + behavior, + token) + : _call.IsBound + ? _call.RunAsync(state, transform, behavior, token) + : Command.ExecuteReaderAsync(state, transform, behavior, token); /// /// Runs an execution that opted in with CancelOnEarlyStop(). @@ -496,6 +600,16 @@ async ValueTask ExecuteAbandonableAsync(TState state, { using (linked) { + // A canceled command does not give its output parameters: refused, + // and every capture completed with the refusal. + if (Captured() is { } captures) + { + throw captures.Refuse( + new InvalidOperationException( + CaptureMessages.CancelOnEarlyStop(captures.Set)), + token); + } + return _call.IsBound || Command is ICommandHandOut ? await ExecuteReaderAsync((state, transform, readThrough, token), abandon.ReadAsync, behavior, token).ConfigureAwait(false) : throw ReaderAbandon.NoCommand(); @@ -996,25 +1110,45 @@ public PooledBuffer ToPooledBuffer( CancellationToken cancellationToken) { EnsureCommand(); - return new(this, Config, cancellationToken); + return Captured() is CaptureSet captures + ? CapturedBuffer(captures, cancellationToken) + : new(this, Config, cancellationToken); } public IAsyncEnumerable> ToPooledBufferStream( CancellationToken cancellationToken) { EnsureCommand(); - return new ChunkStream(this, Config, cancellationToken); + if (Captured() is not CaptureSet captures) + { + return new ChunkStream(this, Config, cancellationToken); + } + + CaptureRun run = StreamRun(captures, cancellationToken); + return new CapturedStream>( + new ChunkStream(WithRun(run), Config, cancellationToken), + run); } public IAsyncEnumerable ToPooledStream( CancellationToken cancellationToken) { EnsureCommand(); + CaptureRun? run = Captured() is CaptureSet captures + ? StreamRun(captures, cancellationToken) + : null; + // The stream carries the caller's token; the token Flatten takes is // the enumeration's own (WithCancellation), so none is passed here. - return Flatten( - new ChunkStream(this, Config, cancellationToken), + IAsyncEnumerable rows = Flatten( + new ChunkStream( + run is null ? this : WithRun(run), + Config, + cancellationToken), CancellationToken.None); + + // Captured: the claim is at the flattened stream's GetAsyncEnumerator. + return run is null ? rows : new CapturedStream(rows, run); } /// @@ -1071,9 +1205,28 @@ IAsyncEnumerable StreamCore( } EnsureCommand(); - return bufferSize == 0 - ? new DirectStream(this, stallTimeout, cancellationToken) - : new StallStream(this, stallTimeout, bufferSize, cancellationToken); + if (Captured() is not CaptureSet captures) + { + return bufferSize == 0 + ? new DirectStream(this, stallTimeout, cancellationToken) + : new StallStream( + this, + stallTimeout, + bufferSize, + cancellationToken); + } + + CaptureRun run = StreamRun(captures, cancellationToken); + MappedQueryCore claimed = WithRun(run); + return new CapturedStream( + bufferSize == 0 + ? new DirectStream(claimed, stallTimeout, cancellationToken) + : new StallStream( + claimed, + stallTimeout, + bufferSize, + cancellationToken), + run); } /// @@ -1105,7 +1258,7 @@ static async IAsyncEnumerable Flatten( /// A deferred, type-locked query over any . Terminals are methods here. /// -public readonly record struct MappedQuery +public readonly partial record struct MappedQuery : IMappedQuery { readonly MappedQueryCore _core; @@ -1746,7 +1899,7 @@ public IAsyncEnumerable ToPooledStream( /// A with a pending skip; can still be limited with . /// -public readonly record struct MappedQueryWithSkip +public readonly partial record struct MappedQueryWithSkip : IMappedQuery { readonly MappedQueryCore _core; @@ -1888,7 +2041,7 @@ public IAsyncEnumerable ToPooledStream( /// A with a take (and any preceding skip), ready for a terminal. /// -public readonly record struct MappedQueryWithTake +public readonly partial record struct MappedQueryWithTake : IMappedQuery { readonly MappedQueryCore _core; diff --git a/Source/Core/Output.docs.xml b/Source/Core/Output.docs.xml index e97684d9..7e3bd906 100644 --- a/Source/Core/Output.docs.xml +++ b/Source/Core/Output.docs.xml @@ -134,59 +134,151 @@ - - - The capture is awaited, or turned into a task, before its terminal was called: - call the terminal (for example ToListAsync) first, then await the capture. - + + + The output model: a class or struct whose members name the output parameters, + as for ExecuteOutputAsync<TOut>(). + + The capture: await it after the terminal. + + 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). + + + + + 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 @. + + At the call: is not a single value, or is a , + which needs its precision and scale (use the form that takes them); + or another capture reads the same parameter. + + + + + , which throws on NULL, or a of it, which reads NULL as . + The 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. + is . + is empty, white space or a bare @. + + is 0 or more than 38, or is more than . + + + At the call: is not or a of it; + or another capture reads the same parameter. + + + + + 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 . + is . + is empty, white space or a bare @. + + is 0 or more than 38, or is more than . + + At the call: another capture reads the same parameter. + + + + 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; + or another capture reads the return code. + + + + + The command, which carries the capture; its next async terminal fills it. + + + 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. + + + 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 copy of the query that carries the capture; its async terminal fills it. + + + The capture belongs to the copy, which also shares any capture on its command, and is complete when the terminal's task is. + A 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. + + + A query that carries a capture runs once, with an async terminal only: + a synchronous terminal and CancelOnEarlyStop() throw, and so does a second run. + It is available on a query built from an expressive command (Map, and the views that skip or take rows); + one from a DbQuery definition throws. + + + The query is not built from an expressive command. + + + - A synchronous terminal (ToList, ExecuteNonQuery, a synchronous enumeration) is called on a chain that carries a capture: - captures need an async terminal. It throws before the run, so nothing is armed. + Call the terminal first, then await the capture: var rows = await query.ToListAsync(); int total = await capture;. + Awaiting it before the terminal was called throws, and so does awaiting it in the loop of the stream it belongs to. + A default value belongs to no call, and every member throws. - + - The chain, or a copy of it, runs a second time: a chain that carries a capture runs once. - It throws before a connection opens; build a new chain to run again. + It completes once, with the run: with the value; faulted with the run's error or the conversion's + (the terminal's own result is unaffected by a conversion error); canceled when the caller's token is; + or faulted when the outputs were not delivered (the response did not complete). - + - The capture is awaited while the stream it belongs to is still open, in the loop that reads it: - await the capture after the loop. AsTask is allowed there, to hand the capture to code that runs after the loop. + The capture is not complete: its GetResult never blocks. Use . - + - The capture is a default value (a default declaration, never the out of a capture call): - it belongs to no call, so awaiting it throws. + The capture is awaited, or turned into a task, before its terminal was called: + call the terminal (for example ToListAsync) first, then await the capture. - + - Two captures own the same outputs: the same name twice, a named capture together with a model capture, - or two sources of the return code. Name each output once. + The capture is awaited while the stream it belongs to is still open, in the loop that reads it: + await the capture after the loop. AsTask is allowed there, to hand the capture to code that runs after the loop. - + - It returns the type it is called on, with the capture attached, and is available on a command, - after Map (including the views that skip or take rows), and on a bound definition of a mapped query - (after Using or AddParam). - The capture belongs to that one chain value, never to the definition. + The capture is a default value (a default declaration, never the out of a capture call): + it belongs to no call, so every member throws. diff --git a/Source/Core/OutputLayout.cs b/Source/Core/OutputLayout.cs index 72ac2a89..b5dfb68b 100644 --- a/Source/Core/OutputLayout.cs +++ b/Source/Core/OutputLayout.cs @@ -16,26 +16,68 @@ sealed class OutputMember /// 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'. - public OutputMember(string name, bool exact, string label, OutputWire wire, string display) + /// for the one value of a named + /// form, which the caller named. + /// The members the call comes from, for the fixes the + /// messages give. + public OutputMember( + string name, + bool exact, + string label, + OutputWire wire, + string display, + bool named = false, + OutputForm form = OutputForm.Execute) { Name = name; Exact = exact; Label = label; Wire = wire; Display = display; + Named = named; + Form = form; } /// Initializes the member that reads the return code. /// The member's name. /// The member for the messages: Model.Member. - public OutputMember(string label, string display) + /// for CaptureReturn, + /// which asks for the return code itself rather than through a member's + /// name. + public OutputMember(string label, string display, bool named = false) { Name = label; Label = label; Display = display; IsReturnValue = true; + Named = named; + Form = named ? OutputForm.Capture : OutputForm.Execute; } + /// Copies a member under another name for the messages. + /// The member. + /// The name for the messages. + /// The members the call comes from. + public OutputMember(OutputMember member, string display, OutputForm form) + { + Name = member.Name; + Exact = member.Exact; + Label = member.Label; + IsReturnValue = member.IsReturnValue; + Wire = member.Wire; + Named = member.Named; + Display = display; + Form = form; + } + + /// Whether the caller named this value itself: the one value of a + /// named form, or the return code of CaptureReturn. + public readonly bool Named; + + /// The members the call comes from: ExecuteOutputAsync, or + /// a capture. + public readonly OutputForm Form; + /// The member's name, its [Column] name, or the name the caller gave. public readonly string Name; @@ -55,6 +97,21 @@ public OutputMember(string label, string display) public readonly OutputWire? Wire; } +/// +/// The members a call that reads output parameters comes from, so a message +/// names the member the caller wrote. +/// +enum OutputForm : byte +{ + /// ExecuteOutputAsync and + /// ExecuteOutputDecimalAsync. + Execute, + + /// CaptureOutput, CaptureOutputDecimal and + /// CaptureReturn. + Capture, +} + /// /// Why a type cannot be sent as an output parameter. /// @@ -228,14 +285,12 @@ public OutputLayout(string model, ImmutableArray members, int[] ce /// The value. public OutputLayout(OutputMember member) : this(member.Name, [member], [0], [member.Label]) - => IsNamed = true; + { + } /// The model's type name, or the parameter's name in the named form, for the messages. public readonly string Model; - /// Whether this is the named form: one value under the name the caller gave. - public readonly bool IsNamed; - /// The members. public readonly ImmutableArray Members; @@ -261,34 +316,60 @@ static class OutputLayout // Never throws: a type that cannot be read holds its error, so the static initializer cannot fail with it. static readonly OutputLayout? Layout = Build(out Error); + // Null for the two refusals whose text names the call (a single value, no + // members): Get words them for the form. static readonly string? Error; /// /// Gets the layout. /// + /// The members the call comes from, for the message of a + /// refusal. /// The layout. /// cannot be mapped, or cannot be read from output parameters. /// A of cannot be honoured. - public static OutputLayout Get() + public static OutputLayout Get(OutputForm form = OutputForm.Execute) { // A single value is told to use the named form, not why it cannot be mapped as a row. if (!IsScalar) RowMap.ThrowIfUnmappable(); - return Layout ?? throw new InvalidOperationException(Error); + return Layout + ?? throw new InvalidOperationException(Error ?? Refusal(form)); } static readonly bool IsScalar = Shape.IsScalar(typeof(TOut)); + static string Refusal(OutputForm form) + { + string model = Shape.TypeName(typeof(TOut)); + bool capture = form == OutputForm.Capture; + string call = capture + ? $"CaptureOutput(out DbCapture<{model}>)" + : $"ExecuteOutputAsync<{model}>()"; + if (IsScalar) + { + string named = capture + ? $"CaptureOutput<{model}>(name, out …)" + : $"ExecuteOutputAsync<{model}>(name)"; + return $"{call} reads a model of output parameters, " + + $"but {model} is a single value with no members to match to " + + "parameters. " + + $"Call {named} with the parameter's name, " + + "or read into a model with one member per parameter."; + } + + return $"{model} has no member to read an output parameter into, " + + $"so {call} has nothing to match. " + + "Give it a public settable property or a constructor parameter " + + "for each output parameter (members with [NotMapped] do not " + + "count)."; + } + static OutputLayout? Build(out string? error) { error = null; Type type = typeof(TOut); string model = Shape.TypeName(type); - if (Shape.IsScalar(type)) - { - error = $"ExecuteOutputAsync<{model}>() reads a model of output parameters, but {model} is a single value with no members to match to parameters. " - + $"Call ExecuteOutputAsync<{model}>(name) with the parameter's name, or read into a model with one member per parameter."; - return null; - } + if (Shape.IsScalar(type)) return null; ImmutableArray slots = RowMap.MappedSlots; var members = ImmutableArray.CreateBuilder(slots.Length); @@ -317,12 +398,7 @@ public static OutputLayout Get() orders.Add(slot.Order); } - if (members.Count == 0) - { - error = $"{model} has no member to read an output parameter into, so ExecuteOutputAsync<{model}>() has nothing to match. " - + "Give it a public settable property or a constructor parameter for each output parameter (members with [NotMapped] do not count)."; - return null; - } + if (members.Count == 0) return null; // A member that declares its ordinal ([Column(Order = n)]) gets that cell, the others the first free ones in order; a gap gets no label. int width = members.Count; @@ -447,33 +523,64 @@ static class OutputValue /// Gets the layout of one call of the named form. /// /// The parameter's name. + /// The members the call comes from: the display of the + /// value and the fixes of the messages. /// The layout. /// cannot be read as one output parameter. - public static OutputLayout Get(string name) + public static OutputLayout Get( + string name, + OutputForm form = OutputForm.Execute) { - string display = $"The output parameter '{name}'"; - OutputWire wire = Wire ?? throw new InvalidOperationException(Message(name, display)); - return new(new OutputMember(name, exact: true, name, wire, display)); + string display = form == OutputForm.Capture + ? $"CaptureOutput<{Shape.TypeName(typeof(T))}>(\"{name}\")" + : $"The output parameter '{name}'"; + OutputWire wire = Wire ?? throw new InvalidOperationException( + Message(name, display, form)); + return new( + new OutputMember( + name, + exact: true, + name, + wire, + display, + named: true, + form)); } /// /// Throws unless is a or a of it: only a decimal takes a precision and scale. /// /// The parameter's name. + /// The members the call comes from, for the fix. /// is not a . - public static void ThrowUnlessDecimal(string name) + public static void ThrowUnlessDecimal( + string name, + OutputForm form = OutputForm.Execute) { if (Reason == OutputValueRefusal.DecimalNeedsShape) return; string shown = Shape.TypeName(typeof(T)); + bool capture = form == OutputForm.Capture; string fix = Reason switch { // A model has no single value to read: the named form refuses it too. OutputValueRefusal.NotScalar - => $"{shown} is a model; call ExecuteOutputAsync<{shown}>() without a name to read its members, giving each decimal member [Column(TypeName = \"decimal(p,s)\")].", + => capture + ? $"{shown} is a model; " + + $"call CaptureOutput(out DbCapture<{shown}>) " + + "without a name to read its members, " + + "giving each decimal member [Column(TypeName = " + + "\"decimal(p,s)\")]." + : $"{shown} is a model; " + + $"call ExecuteOutputAsync<{shown}>() " + + "without a name to read its members, " + + "giving each decimal member [Column(TypeName = " + + "\"decimal(p,s)\")].", OutputValueRefusal.NoDbType => $"{shown} has no database type for an output; read it as a type that has one, {OutputWire.SupportedTypes}.", - _ => $"Use ExecuteOutputAsync<{shown}>(\"{name}\").", + _ => capture + ? $"Use CaptureOutput<{shown}>(\"{name}\", out …)." + : $"Use ExecuteOutputAsync<{shown}>(\"{name}\").", }; throw new InvalidOperationException( @@ -486,25 +593,67 @@ public static void ThrowUnlessDecimal(string name) /// The parameter's name. /// The precision, checked by the caller. /// The scale, checked by the caller. + /// The value for the messages, or + /// for the one of ExecuteOutputAsync. /// The layout; is checked by the caller, which has called . - public static OutputLayout Shaped(string name, byte precision, byte scale) + public static OutputLayout Shaped( + string name, + byte precision, + byte scale, + string? display = null) { Debug.Assert(Reason == OutputValueRefusal.DecimalNeedsShape); - string display = $"The output parameter '{name}'"; - return new(new OutputMember(name, exact: true, name, new OutputWire(DbType.Decimal, 0, precision, scale), display)); + OutputForm form = display is null + ? OutputForm.Execute + : OutputForm.Capture; + display ??= $"The output parameter '{name}'"; + return new( + new OutputMember( + name, + exact: true, + name, + new OutputWire(DbType.Decimal, 0, precision, scale), + display, + named: true, + form)); } - static string Message(string name, string display) + static string Message(string name, string display, OutputForm form) { string shown = Shape.TypeName(typeof(T)); + bool capture = form == OutputForm.Capture; return Reason switch { OutputValueRefusal.NotScalar - => $"ExecuteOutputAsync<{shown}>(\"{name}\") reads one value, but {shown} is a model, not a single value. " - + $"Call ExecuteOutputAsync<{shown}>() without a name to read its members, or read '{name}' as a single-value type {OutputWire.SupportedTypes}.", + => capture + ? $"CaptureOutput<{shown}>(\"{name}\", out …) " + + $"reads one value, but {shown} is a model, " + + "not a single value. " + + $"Call CaptureOutput(out DbCapture<{shown}>) " + + "without a name to read its members, " + + $"or read '{name}' as a single-value type " + + $"{OutputWire.SupportedTypes}." + : $"ExecuteOutputAsync<{shown}>(\"{name}\") " + + $"reads one value, but {shown} is a model, " + + "not a single value. " + + $"Call ExecuteOutputAsync<{shown}>() " + + "without a name to read its members, " + + $"or read '{name}' as a single-value type " + + $"{OutputWire.SupportedTypes}.", OutputValueRefusal.DecimalNeedsShape - => $"{display} is read as {shown}. A decimal output needs its precision and scale, or the server rounds it to a whole number. " - + $"Use ExecuteOutputAsync(\"{name}\", 19, 4) or ExecuteOutputDecimalAsync(\"{name}\", 19, 4) with the column's precision and scale.", + => capture + ? $"{display} is read as {shown}. " + + "A decimal output needs its precision and scale, " + + "or the server rounds it to a whole number. " + + $"Use CaptureOutput(\"{name}\", 19, 4, out …) " + + $"or CaptureOutputDecimal(\"{name}\", 19, 4, out …) " + + "with the column's precision and scale." + : $"{display} is read as {shown}. " + + "A decimal output needs its precision and scale, " + + "or the server rounds it to a whole number. " + + $"Use ExecuteOutputAsync(\"{name}\", 19, 4) " + + $"or ExecuteOutputDecimalAsync(\"{name}\", 19, 4) " + + "with the column's precision and scale.", _ => $"{display} is read as {shown}, which has no database type, so it cannot be sent as an output parameter. " + $"Read it as a type that has one, {OutputWire.SupportedTypes}.", @@ -540,7 +689,10 @@ static string Message(string name, string display) /// one command may run on several threads at once. /// /// What the call reads. -sealed class OutputRun(OutputLayout layout) +// Not sealed: a run that fills captures is one +// (ExpressiveCommandBase.Capture.cs), so the build step adds its parameters by +// the same path. +class OutputRun(OutputLayout layout) { /// What the call reads. public readonly OutputLayout Layout = layout; @@ -569,7 +721,7 @@ sealed class OutputRun(OutputLayout layout) public object? Value(int index) { object? value = Parameters![index]!.Value; - if (value is null && Pure![index]) + if (!Delivered(index)) { OutputMember member = Layout.Members[index]; string which = member.IsReturnValue ? "the return code was" : $"the output parameter '{Names![index]}' was"; @@ -581,6 +733,16 @@ sealed class OutputRun(OutputLayout layout) return value; } + /// + /// Whether a member's value arrived: a pure output (or the return code) + /// still after the call never did. + /// + /// The member. + /// when the value never arrived; + /// otherwise, . + public bool Delivered(int index) + => Parameters![index]!.Value is not null || !Pure![index]; + /// /// Builds the model from the values, once the response is complete. /// @@ -612,7 +774,9 @@ public TOut Map() /// The type. static class ReturnCode { - static readonly bool IsScalar = Holds(typeof(T)); + /// Whether can hold the return code: a + /// single value, or . + public static bool IsValue { get; } = Holds(typeof(T)); /// /// Whether a type can hold the return code: a single value, or . @@ -628,7 +792,7 @@ public static bool Holds(Type type) /// is not a single value. public static void ThrowUnlessScalar() { - if (IsScalar) return; + if (IsValue) return; throw new InvalidOperationException(Message(Shape.TypeName(typeof(T)))); } @@ -641,3 +805,113 @@ public static void ThrowUnlessScalar() public static string Message(string shown) => $"The return code is one integer, so {shown} cannot hold it. Use int (or int?, long, an enum), or a ReturnValue member on the output model."; } + +/// +/// The checks of the arguments the named forms take, and their messages, for +/// ExecuteOutputAsync and the captures alike. +/// +static class OutputArguments +{ + /// + /// Throws unless a name is given: , empty, white + /// space and a bare @ are not names. + /// + /// The parameter's name. + /// The members the call comes from, for the example in + /// the message. + /// is + /// . + /// is empty, + /// white space or a bare @. + public static void ThrowIfNoName(string name, OutputForm form) + { + if (name is null) + { + throw new ArgumentNullException(nameof(name), NameRequired(form)); + } + if (string.IsNullOrWhiteSpace(name) || name.Trim() == "@") + { + throw new ArgumentException(NameRequired(form), nameof(name)); + } + } + + static string NameRequired(OutputForm form) + => form == OutputForm.Capture + ? "A parameter name is required, " + + "for example CaptureOutput(\"total\", out …)." + : "A parameter name is required, " + + "for example ExecuteOutputAsync(\"total\")."; + + // One rule with [Column(TypeName = "decimal(p,s)")]: + // OutputWire.IsDecimalShape. + /// + /// Throws unless a precision and scale are a decimal's. + /// + /// The parameter's name. + /// The precision. + /// The scale. + /// The members the call comes from, for the example in + /// the message. + /// The precision is 0 or more + /// than 38, or the scale is more than the precision. + public static void ThrowIfBadShape( + string name, + byte precision, + byte scale, + OutputForm form) + { + if (OutputWire.IsDecimalShape(precision, scale)) return; + + string example = form == OutputForm.Capture + ? $"For decimal(19,4), pass CaptureOutput(\"{name}\", 19, " + + "4, out …)." + : "For decimal(19,4), " + + $"pass ExecuteOutputAsync(\"{name}\", 19, 4)."; + + if (precision is 0 or > 38) + { + throw new ArgumentOutOfRangeException( + nameof(precision), + precision, + $"The precision of the decimal output parameter '{name}' is " + + $"{precision}, but it must be from 1 to 38: " + + "the number of digits its SQL type declares. " + + example); + } + + throw new ArgumentOutOfRangeException( + nameof(scale), + scale, + $"The scale of the decimal output parameter '{name}' is {scale}, " + + $"more than its precision of {precision}: " + + "the scale counts the digits after the decimal point, " + + "out of the precision. " + + example); + } + + /// + /// Makes the exception for a decimal output that is NULL where a + /// reads it. + /// + /// The parameter's name. + /// The members the call comes from, for the fix. + /// The exception. + public static ValueMappingException DecimalNull( + string name, + OutputForm form) + => new( + $"The decimal output parameter '{name}' is NULL, " + + "which a decimal cannot hold. " + + (form == OutputForm.Capture + ? $"Read it as decimal? (CaptureOutput(\"{name}\", " + + "precision, scale, out …)) " + + $"or with CaptureOutputDecimal(\"{name}\", precision, scale, " + + "out …), which give null for NULL." + : "Read it as decimal? " + + $"(ExecuteOutputAsync(\"{name}\", precision, " + + $"scale)) or with ExecuteOutputDecimalAsync(\"{name}\", " + + "precision, scale), which return null for NULL."), + name, + name, + typeof(decimal)); +} diff --git a/Source/Core/PublicAPI.Unshipped.txt b/Source/Core/PublicAPI.Unshipped.txt index 665707e4..4f0f062b 100644 --- a/Source/Core/PublicAPI.Unshipped.txt +++ b/Source/Core/PublicAPI.Unshipped.txt @@ -76,3 +76,43 @@ Open.Database.Extensions.ExpressiveCommandBase.AddParamIf(bool condition, string! name, TDbType type) -> TThis! static Open.Database.Extensions.DataReaderExtensions.ToArrayAsync(this System.Data.Common.DbDataReader! reader, System.Func>! transform, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask static Open.Database.Extensions.DataReaderExtensions.ToImmutableArrayAsync(this System.Data.Common.DbDataReader! reader, System.Func>! transform, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask> +Open.Database.Extensions.DbCapture +Open.Database.Extensions.DbCapture.DbCapture() -> void +Open.Database.Extensions.DbCapture.AsTask() -> System.Threading.Tasks.Task! +Open.Database.Extensions.DbCapture.ConfigureAwait(bool continueOnCapturedContext) -> Open.Database.Extensions.DbCapture.ConfiguredAwaitable +Open.Database.Extensions.DbCapture.GetAwaiter() -> Open.Database.Extensions.DbCapture.Awaiter +Open.Database.Extensions.DbCapture.Awaiter +Open.Database.Extensions.DbCapture.Awaiter.Awaiter() -> void +Open.Database.Extensions.DbCapture.Awaiter.GetResult() -> T +Open.Database.Extensions.DbCapture.Awaiter.IsCompleted.get -> bool +Open.Database.Extensions.DbCapture.Awaiter.OnCompleted(System.Action! continuation) -> void +Open.Database.Extensions.DbCapture.Awaiter.UnsafeOnCompleted(System.Action! continuation) -> void +Open.Database.Extensions.DbCapture.ConfiguredAwaitable +Open.Database.Extensions.DbCapture.ConfiguredAwaitable.ConfiguredAwaitable() -> void +Open.Database.Extensions.DbCapture.ConfiguredAwaitable.GetAwaiter() -> Open.Database.Extensions.DbCapture.ConfiguredAwaiter +Open.Database.Extensions.DbCapture.ConfiguredAwaiter +Open.Database.Extensions.DbCapture.ConfiguredAwaiter.ConfiguredAwaiter() -> void +Open.Database.Extensions.DbCapture.ConfiguredAwaiter.GetResult() -> T +Open.Database.Extensions.DbCapture.ConfiguredAwaiter.IsCompleted.get -> bool +Open.Database.Extensions.DbCapture.ConfiguredAwaiter.OnCompleted(System.Action! continuation) -> void +Open.Database.Extensions.DbCapture.ConfiguredAwaiter.UnsafeOnCompleted(System.Action! continuation) -> void +Open.Database.Extensions.ExpressiveCommandBase.CaptureOutput(out Open.Database.Extensions.DbCapture output) -> TThis! +Open.Database.Extensions.ExpressiveCommandBase.CaptureOutput(string! name, out Open.Database.Extensions.DbCapture value) -> TThis! +Open.Database.Extensions.ExpressiveCommandBase.CaptureOutput(string! name, byte precision, byte scale, out Open.Database.Extensions.DbCapture value) -> TThis! +Open.Database.Extensions.ExpressiveCommandBase.CaptureOutputDecimal(string! name, byte precision, byte scale, out Open.Database.Extensions.DbCapture value) -> TThis! +Open.Database.Extensions.ExpressiveCommandBase.CaptureReturn(out Open.Database.Extensions.DbCapture returnCode) -> TThis! +Open.Database.Extensions.MappedQuery.CaptureOutput(out Open.Database.Extensions.DbCapture output) -> Open.Database.Extensions.MappedQuery +Open.Database.Extensions.MappedQuery.CaptureOutput(string! name, out Open.Database.Extensions.DbCapture value) -> Open.Database.Extensions.MappedQuery +Open.Database.Extensions.MappedQuery.CaptureOutput(string! name, byte precision, byte scale, out Open.Database.Extensions.DbCapture value) -> Open.Database.Extensions.MappedQuery +Open.Database.Extensions.MappedQuery.CaptureOutputDecimal(string! name, byte precision, byte scale, out Open.Database.Extensions.DbCapture value) -> Open.Database.Extensions.MappedQuery +Open.Database.Extensions.MappedQuery.CaptureReturn(out Open.Database.Extensions.DbCapture returnCode) -> Open.Database.Extensions.MappedQuery +Open.Database.Extensions.MappedQueryWithSkip.CaptureOutput(out Open.Database.Extensions.DbCapture output) -> Open.Database.Extensions.MappedQueryWithSkip +Open.Database.Extensions.MappedQueryWithSkip.CaptureOutput(string! name, out Open.Database.Extensions.DbCapture value) -> Open.Database.Extensions.MappedQueryWithSkip +Open.Database.Extensions.MappedQueryWithSkip.CaptureOutput(string! name, byte precision, byte scale, out Open.Database.Extensions.DbCapture value) -> Open.Database.Extensions.MappedQueryWithSkip +Open.Database.Extensions.MappedQueryWithSkip.CaptureOutputDecimal(string! name, byte precision, byte scale, out Open.Database.Extensions.DbCapture value) -> Open.Database.Extensions.MappedQueryWithSkip +Open.Database.Extensions.MappedQueryWithSkip.CaptureReturn(out Open.Database.Extensions.DbCapture returnCode) -> Open.Database.Extensions.MappedQueryWithSkip +Open.Database.Extensions.MappedQueryWithTake.CaptureOutput(out Open.Database.Extensions.DbCapture output) -> Open.Database.Extensions.MappedQueryWithTake +Open.Database.Extensions.MappedQueryWithTake.CaptureOutput(string! name, out Open.Database.Extensions.DbCapture value) -> Open.Database.Extensions.MappedQueryWithTake +Open.Database.Extensions.MappedQueryWithTake.CaptureOutput(string! name, byte precision, byte scale, out Open.Database.Extensions.DbCapture value) -> Open.Database.Extensions.MappedQueryWithTake +Open.Database.Extensions.MappedQueryWithTake.CaptureOutputDecimal(string! name, byte precision, byte scale, out Open.Database.Extensions.DbCapture value) -> Open.Database.Extensions.MappedQueryWithTake +Open.Database.Extensions.MappedQueryWithTake.CaptureReturn(out Open.Database.Extensions.DbCapture returnCode) -> Open.Database.Extensions.MappedQueryWithTake diff --git a/Source/Core/StallStream.cs b/Source/Core/StallStream.cs index 832a2d84..d1ac3502 100644 --- a/Source/Core/StallStream.cs +++ b/Source/Core/StallStream.cs @@ -66,6 +66,11 @@ internal sealed class StallStream : IAsyncEnumerable, IStallSignal // The enumeration's own state, set when it starts. ChannelWriter? _writer; CancellationTokenSource? _read; + + // Captured only: the consumer's stop, linked to _read. It ends the + // hand-off waits instead of a cancel of _read, which would cancel the + // command, and a cancelled command gives no output parameters. + CancellationTokenSource? _stop; CancellationTokenSource? _wait; CancellationToken _enumeration; ReaderAbandon? _abandon; @@ -127,7 +132,17 @@ async IAsyncEnumerator Read(CancellationToken cancellationToken) _enumeration = cancellationToken; _writer = channel.Writer; _read = CancellationTokenSource.CreateLinkedTokenSource(_caller, cancellationToken); - if (_finite) _wait = CancellationTokenSource.CreateLinkedTokenSource(_read.Token); + if (_query.CapturedRun is not null) + { + _stop = CancellationTokenSource.CreateLinkedTokenSource( + _read.Token); + } + + if (_finite) + { + _wait = CancellationTokenSource.CreateLinkedTokenSource( + HandOffToken); + } Task producer = StartProducer(channel.Writer); try @@ -158,7 +173,7 @@ async IAsyncEnumerator Read(CancellationToken cancellationToken) finally { Volatile.Write(ref _disposed, 1); - try { _read.Cancel(); } + try { (_stop ?? _read).Cancel(); } catch { } // The producer never faults: it catches everything and completes the channel with it. @@ -166,6 +181,7 @@ async IAsyncEnumerator Read(CancellationToken cancellationToken) finally { _wait?.Dispose(); + _stop?.Dispose(); _read.Dispose(); } } @@ -187,6 +203,7 @@ Task StartProducer(ChannelWriter writer) catch { _wait?.Dispose(); + _stop?.Dispose(); _read!.Dispose(); throw; } @@ -232,10 +249,23 @@ async ValueTask PumpAsync(IAsyncEnumerable rows, CancellationToken token) await HandOffAsync(row, token).ConfigureAwait(false); } + // The token of the hand-off waits: the consumer's stop when captured, + // else the read's own. + CancellationToken HandOffToken + => (_stop ?? _read)!.Token; + async ValueTask HandOffAsync(T row, CancellationToken token) { ChannelWriter writer = _writer!; + // Captured: the consumer stopped, so nothing more is handed off. + // The run delivers the captures once the reader is closed. + if (_stop is { } stop) + { + stop.Token.ThrowIfCancellationRequested(); + token = stop.Token; + } + // Room in the channel: the consumer is keeping up and nothing waits. if (writer.TryWrite(row)) return; @@ -251,7 +281,8 @@ async ValueTask HandOffAsync(T row, CancellationToken token) { token.ThrowIfCancellationRequested(); _wait.Dispose(); - _wait = CancellationTokenSource.CreateLinkedTokenSource(_read!.Token); + _wait = CancellationTokenSource.CreateLinkedTokenSource( + HandOffToken); } // The wait is the stall. A cancel of the read ends it too, and is told apart from an expiry below. diff --git a/Tests/Open.Database.Extensions.Core.Tests/CaptureTests.cs b/Tests/Open.Database.Extensions.Core.Tests/CaptureTests.cs new file mode 100644 index 00000000..e39109f1 --- /dev/null +++ b/Tests/Open.Database.Extensions.Core.Tests/CaptureTests.cs @@ -0,0 +1,949 @@ +using Open.Database.Extensions.Benchmarks; +using System.ComponentModel.DataAnnotations.Schema; +using System.Data.Common; + +#nullable enable + +namespace Open.Database.Extensions.Tests; + +// The captures (CaptureOutput, CaptureOutputDecimal, CaptureReturn) on a +// command and on a mapped query, over a provider that records its +// parameters, fills the outputs when it executes, and can hold an execution +// at a gate: where each capture goes, what it reads, what throws at the call, +// and how it completes. +[ExcludeFromCodeCoverage] +public static class CaptureTests +{ + static CancellationToken Token + => TestContext.Current.CancellationToken; + + // ---- the models ------------------------------------------------------ + + public sealed record Row(int Id); + + public sealed record PageInfo(int Total, int Pages); + + public sealed record Touched(int Count, int ReturnValue); + + public sealed record Money( + [property: Column(TypeName = "decimal(10,2)")] decimal Total); + + // ---- the provider ---------------------------------------------------- + + sealed class CaptureConnection( + params (string Name, object? Value)[] outputs) + : DbConnection + { + public CaptureCommand? Last { get; private set; } + + public int Executed { get; set; } + + public int Rows { get; set; } = 3; + + // When set, an async execution waits for it before it runs. + public TaskCompletionSource? Gate { get; set; } + + public (string Name, object? Value)[] Outputs { get; } = outputs; + + [AllowNull] + public override string ConnectionString { get; set; } = "capture"; + public override string Database => "capture"; + public override string DataSource => "capture"; + public override string ServerVersion => "1.0"; + public override ConnectionState State => ConnectionState.Open; + public override void ChangeDatabase(string databaseName) { } + public override void Close() { } + public override void Open() { } + + protected override DbTransaction BeginDbTransaction( + IsolationLevel isolationLevel) + => throw new NotSupportedException(); + + protected override DbCommand CreateDbCommand() + => Last = new CaptureCommand(this); + } + + sealed class CaptureCommand(CaptureConnection connection) : DbCommand + { + readonly BenchParameterCollection _parameters = []; + + public IReadOnlyList All + => [.. _parameters.Cast()]; + + public DbParameter Named(string name) + => All.Single(p => p.ParameterName == name); + + [AllowNull] + public override string CommandText { get; set; } = ""; + public override int CommandTimeout { get; set; } + public override CommandType CommandType { get; set; } + public override bool DesignTimeVisible { get; set; } + public override UpdateRowSource UpdatedRowSource { get; set; } + + protected override DbConnection? DbConnection + { + get => connection; + set { } + } + + protected override DbParameterCollection DbParameterCollection + => _parameters; + + protected override DbTransaction? DbTransaction { get; set; } + public override void Cancel() { } + public override void Prepare() { } + + protected override DbParameter CreateDbParameter() + => new CaptureParameter(); + + public override int ExecuteNonQuery() + { + Run(); + return 1; + } + + public override object? ExecuteScalar() + { + Run(); + return 1; + } + + protected override DbDataReader ExecuteDbDataReader( + CommandBehavior behavior) + { + Run(); + var table = new DataTable(); + table.Columns.Add("Id", typeof(int)); + for (int i = 1; i <= connection.Rows; i++) table.Rows.Add(i); + return table.CreateDataReader(); + } + + protected override async Task ExecuteDbDataReaderAsync( + CommandBehavior behavior, + CancellationToken cancellationToken) + { + if (connection.Gate is { } gate) await gate.Task; + return ExecuteDbDataReader(behavior); + } + + public override async Task ExecuteNonQueryAsync( + CancellationToken cancellationToken) + { + if (connection.Gate is { } gate) await gate.Task; + return ExecuteNonQuery(); + } + + // Sets every output (and the return value, under "") from the values + // the connection was given, by name. + void Run() + { + connection.Executed++; + foreach (DbParameter p in All) + { + if (p.Direction == ParameterDirection.Input) continue; + + string key = p.Direction == ParameterDirection.ReturnValue + ? "" + : p.ParameterName; + foreach ((string name, object? value) in connection.Outputs) + { + if (name == key) p.Value = value; + } + } + } + } + + sealed class CaptureParameter : DbParameter + { + public override DbType DbType { get; set; } + + public override ParameterDirection Direction { get; set; } + = ParameterDirection.Input; + + public override bool IsNullable { get; set; } + [AllowNull] + public override string ParameterName { get; set; } = ""; + public override int Size { get; set; } + public override byte Precision { get; set; } + public override byte Scale { get; set; } + [AllowNull] + public override string SourceColumn { get; set; } = ""; + public override bool SourceColumnNullMapping { get; set; } + public override object? Value { get; set; } + public override void ResetDbType() { } + } + + static void Contains(Exception ex, params string[] phrases) + { + foreach (string phrase in phrases) Assert.Contains(phrase, ex.Message); + } + + // ---- the command ----------------------------------------------------- + + [Fact] + public static async Task OnACommand_TheNextTerminalFillsIt() + { + var c = new CaptureConnection(("total", 42)); + + int rows = await c + .StoredProcedure("p") + .CaptureOutput("total", out DbCapture total) + .ExecuteNonQueryAsync(Token); + + Assert.Equal(1, rows); + Assert.Equal(42, await total); + DbParameter p = c.Last!.Named("total"); + Assert.Equal(ParameterDirection.Output, p.Direction); + Assert.Equal(DbType.Int32, p.DbType); + } + + [Fact] + public static async Task AModel_AndTheReturnCode_OnOneCommand() + { + var c = new CaptureConnection(("Total", 7), ("Pages", 2), ("", 3)); + + await c + .StoredProcedure("p") + .CaptureOutput(out DbCapture page) + .CaptureReturn(out DbCapture code) + .ExecuteNonQueryAsync(Token); + + Assert.Equal(new PageInfo(7, 2), await page); + Assert.Equal(3, await code); + } + + [Fact] + public static async Task NamedCaptures_AndADecimal_OnOneCommand() + { + var c = new CaptureConnection(("count", 7L), ("amount", 12.5m)); + + await c + .StoredProcedure("p") + .CaptureOutput("count", out DbCapture count) + .CaptureOutputDecimal("amount", 10, 2, out DbCapture amount) + .ExecuteNonQueryAsync(Token); + + Assert.Equal(7, await count); + Assert.Equal(12.5m, await amount); + DbParameter p = c.Last!.Named("amount"); + Assert.Equal((10, 2), (p.Precision, p.Scale)); + } + + [Fact] + public static async Task AModelWithADecimalColumn_ReadsIt() + { + var c = new CaptureConnection(("Total", 3.25m)); + + await c + .StoredProcedure("p") + .CaptureOutput(out DbCapture money) + .ExecuteNonQueryAsync(Token); + + Assert.Equal(3.25m, (await money).Total); + DbParameter p = c.Last!.Named("Total"); + Assert.Equal((10, 2), (p.Precision, p.Scale)); + } + + [Fact] + public static async Task TheShapedForm_LetsTDecideNull() + { + var c = new CaptureConnection(("a", DBNull.Value), ("b", DBNull.Value)); + + await c + .StoredProcedure("p") + .CaptureOutput("a", 19, 4, out DbCapture a) + .CaptureOutput("b", 19, 4, out DbCapture b) + .ExecuteNonQueryAsync(Token); + + Assert.Null(await a); + + // A conversion failure is the capture's, never the terminal's. + await Assert.ThrowsAsync(async () => await b); + } + + [Fact] + public static async Task AddParam_AfterACapture_KeepsIt() + { + var c = new CaptureConnection(("total", 5)); + + await c + .StoredProcedure("p") + .CaptureOutput("total", out DbCapture total) + .AddParam("other", 1) + .ExecuteNonQueryAsync(Token); + + Assert.Equal(5, await total); + Assert.Equal(2, c.Last!.All.Count); + } + + [Fact] + public static async Task ACommandWithACapture_RunsOnce() + { + var c = new CaptureConnection(("total", 5)); + var command = c + .StoredProcedure("p") + .CaptureOutput("total", out DbCapture total); + + await command.ExecuteNonQueryAsync(Token); + Assert.Equal(5, await total); + + var ex = await Assert.ThrowsAsync( + async () => await command.ExecuteNonQueryAsync(Token)); + Contains(ex, + "already used by an earlier run of this command", + "with a new capture"); + Assert.Equal(1, c.Executed); + } + + [Fact] + public static void ASynchronousTerminal_Throws_AndArmsNothing() + { + var c = new CaptureConnection(("total", 5)); + var command = c + .StoredProcedure("p") + .CaptureOutput("total", out DbCapture total); + + var ex = Assert.Throws( + () => command.ExecuteNonQuery()); + Contains(ex, + "captures only work with async terminals", + "ExecuteNonQueryAsync instead of ExecuteNonQuery"); + Assert.Equal(0, c.Executed); + + // Not armed: awaiting it would wait forever, so it throws. + Contains( + Assert.Throws( + () => { _ = total.AsTask(); }), + "has not started"); + } + + [Fact] + public static async Task ExecuteAsyncWithAFunction_IsRefused_AndFaultsIt() + { + var c = new CaptureConnection(("total", 5)); + var command = c + .StoredProcedure("p") + .CaptureOutput("total", out DbCapture total); + + var ex = await Assert.ThrowsAsync( + async () => await command.ExecuteAsync( + static _ => ValueTask.CompletedTask)); + Contains(ex, "cannot be filled by ExecuteAsync(command => ...)"); + Assert.Same( + ex, + await Assert.ThrowsAsync( + async () => await total)); + } + + [Fact] + public static async Task ExecuteOutputAsync_BesideACapture_IsRefused() + { + var c = new CaptureConnection(("total", 5)); + var command = c + .StoredProcedure("p") + .CaptureOutput("total", out DbCapture total); + + var ex = await Assert.ThrowsAsync( + async () => await command.ExecuteOutputAsync("other", Token)); + Contains(ex, + "reads its output parameters twice", + "ExecuteOutputAsync(\"other\")"); + await Assert.ThrowsAsync( + async () => await total); + Assert.Equal(0, c.Executed); + } + + [Fact] + public static async Task ExecuteReturnAsync_BesideCaptureReturn_IsRefused() + { + var c = new CaptureConnection(("", 1)); + var command = c + .StoredProcedure("p") + .CaptureReturn(out DbCapture code); + + var ex = await Assert.ThrowsAsync( + async () => await command.ExecuteReturnAsync(Token)); + Contains(ex, "reads its return code twice"); + await Assert.ThrowsAsync( + async () => await code); + } + + [Fact] + public static async Task ExecuteReturnAsync_BesideANamedCapture_Runs() + { + var c = new CaptureConnection(("", 4), ("total", 5)); + + int code = await c + .StoredProcedure("p") + .CaptureOutput("total", out DbCapture total) + .ExecuteReturnAsync(Token); + + Assert.Equal(4, code); + Assert.Equal(5, await total); + } + + // ---- one owner per output -------------------------------------------- + + [Fact] + public static void EachOutput_HasOneOwner_CheckedAtTheCall() + { + var c = new CaptureConnection(); + + Contains( + Assert.Throws(() => c + .StoredProcedure("p") + .CaptureOutput(out DbCapture _) + .CaptureOutput(out DbCapture _)), + "reads its output parameters twice", + "one model capture, or named captures only"); + Contains( + Assert.Throws(() => c + .StoredProcedure("p") + .CaptureOutput("total", out DbCapture _) + .CaptureOutput(out DbCapture _)), + "reads its output parameters twice"); + Contains( + Assert.Throws(() => c + .StoredProcedure("p") + .CaptureOutput("@Total", out DbCapture _) + .CaptureOutput("total", out DbCapture _)), + "reads output parameter @Total twice", + "Capture each parameter once"); + Contains( + Assert.Throws(() => c + .StoredProcedure("p") + .CaptureReturn(out DbCapture _) + .CaptureOutput(out DbCapture _)), + "reads its return code twice", + "the ReturnValue member of Touched"); + Contains( + Assert.Throws(() => c + .StoredProcedure("p") + .CaptureReturn(out DbCapture _) + .CaptureReturn(out DbCapture _)), + "reads its return code twice"); + } + + [Fact] + public static void TheReturnCode_NeedsAStoredProcedure_AndAnInteger() + { + var c = new CaptureConnection(); + + Contains( + Assert.Throws(() => c + .Command("select 1") + .CaptureReturn(out DbCapture _)), + "CaptureReturn needs a stored procedure", + "StoredProcedure(…)"); + Contains( + Assert.Throws(() => c + .Command("select 1") + .CaptureOutput(out DbCapture _)), + "the ReturnValue member of Touched, which needs a stored procedure"); + Contains( + Assert.Throws(() => c + .StoredProcedure("p") + .CaptureReturn(out DbCapture _)), + "CaptureReturn cannot hold it"); + } + + [Fact] + public static void TheArguments_AreCheckedAtTheCall() + { + var c = new CaptureConnection(); + + Assert.Throws(() => c + .StoredProcedure("p") + .CaptureOutput(null!, out DbCapture _)); + Assert.Throws(() => c + .StoredProcedure("p") + .CaptureOutput("@", out DbCapture _)); + Assert.Throws(() => c + .StoredProcedure("p") + .CaptureOutputDecimal("a", 0, 0, out DbCapture _)); + Assert.Throws(() => c + .StoredProcedure("p") + .CaptureOutput("a", 10, 2, out DbCapture _)); + Assert.Throws(() => c + .StoredProcedure("p") + .CaptureOutput("a", out DbCapture _)); + Assert.Throws(() => c + .StoredProcedure("p") + .CaptureOutput(out DbCapture _)); + } + + // ---- the mapped query ------------------------------------------------ + + [Fact] + public static async Task OnAQuery_TheTerminalFillsIt_BeforeItsTaskCompletes() + { + var c = new CaptureConnection(("total", 9)); + + List rows = await c + .StoredProcedure("p") + .Map() + .CaptureOutput("total", out DbCapture total) + .ToListAsync(Token); + + Assert.Equal(3, rows.Count); + Assert.True(total.GetAwaiter().IsCompleted); + Assert.Equal(9, await total); + } + + [Fact] + public static async Task TheSkipAndTakeViews_CarryIt() + { + var c = new CaptureConnection(("total", 9), ("", 1)); + + List skipped = await c + .StoredProcedure("p") + .Map() + .Skip(1) + .CaptureOutput("total", out DbCapture total) + .CaptureReturn(out DbCapture code) + .ToListAsync(Token); + List taken = await c + .StoredProcedure("p") + .Map() + .Take(1) + .CaptureOutput(out DbCapture page) + .ToListAsync(Token); + + Assert.Equal(2, skipped.Count); + Assert.Equal(9, await total); + Assert.Equal(1, await code); + Assert.Single(taken); + + // Never set by the provider: not delivered, for the whole set. + Contains( + await Assert.ThrowsAsync( + async () => await page), + "were never delivered"); + } + + [Fact] + public static async Task Map_SharesTheCommandsCapture_TheFirstRunTakesIt() + { + var c = new CaptureConnection(("total", 9)); + var command = c + .StoredProcedure("p") + .CaptureOutput("total", out DbCapture total); + MappedQuery query = command.Map(); + + Assert.Equal(3, (await query.ToListAsync(Token)).Count); + Assert.Equal(9, await total); + + Contains( + await Assert.ThrowsAsync( + async () => await command.ExecuteNonQueryAsync(Token)), + "already used by an earlier run of this command"); + Assert.Equal(1, c.Executed); + } + + [Fact] + public static async Task AQueryWithACapture_RunsOnce() + { + var c = new CaptureConnection(("total", 9)); + MappedQuery query = c + .StoredProcedure("p") + .Map() + .CaptureOutput("total", out DbCapture _); + + await query.ToListAsync(Token); + Contains( + await Assert.ThrowsAsync( + async () => await query.ToArrayAsync(Token)), + "already used by an earlier run of this query", + "build the query again, with a new capture"); + Assert.Equal(1, c.Executed); + } + + [Fact] + public static async Task EveryBuilder_CarriesIt_AndItIsPartOfTheEquality() + { + var c = new CaptureConnection(("total", 9)); + MappedQuery plain = c.StoredProcedure("p").Map(); + MappedQuery captured = plain + .CaptureOutput("total", out DbCapture total); + MappedQuery copy = captured; + + Assert.NotEqual(plain, captured); + Assert.Equal(captured, copy); + Assert.Equal(captured.GetHashCode(), copy.GetHashCode()); + + List rows = await captured + .SingleResult() + .AsyncReads() + .SequentialAccess() + .Skip(1) + .ToListAsync(Token); + + Assert.Equal(2, rows.Count); + Assert.Equal(9, await total); + } + + [Fact] + public static async Task ASynchronousTerminal_OnAQuery_Throws_AndArmsNothing() + { + var c = new CaptureConnection(("total", 9)); + MappedQuery query = c + .StoredProcedure("p") + .Map() + .CaptureOutput("total", out DbCapture total); + + Contains( + Assert.Throws(() => query.ToList()), + "This query has CaptureOutput(\"total\")", + "ToListAsync instead of ToList"); + Assert.Throws(() => { _ = total.AsTask(); }); + + // Still unused: the async terminal runs it. + Assert.Equal(3, (await query.ToListAsync(Token)).Count); + Assert.Equal(9, await total); + } + + [Fact] + public static async Task CancelOnEarlyStop_IsRefused_AndFaultsIt() + { + var c = new CaptureConnection(("total", 9)); + var query = c + .StoredProcedure("p") + .Map() + .CaptureOutput("total", out DbCapture total) + .CancelOnEarlyStop(); + + var ex = await Assert.ThrowsAsync( + async () => await query.ToListAsync(Token)); + Contains(ex, + "cannot be used with CancelOnEarlyStop()", + "Remove CancelOnEarlyStop(), or remove the capture"); + Assert.Same( + ex, + await Assert.ThrowsAsync( + async () => await total)); + Assert.Equal(0, c.Executed); + } + + [Fact] + public static void AQuery_ThatIsNotFromAnExpressiveCommand_RefusesIt() + { + var c = new CaptureConnection(); + FakeExecuteReader source = new(["Id"], [1]); + + Contains( + Assert.Throws(() => DbQuery + .Text("select") + .Using(c) + .Map() + .CaptureOutput("total", out DbCapture _)), + "a query from a DbQuery definition gets captures in a later"); + Contains( + Assert.Throws(() => source + .Map() + .CaptureOutput("total", out DbCapture _)), + "this query reads from FakeExecuteReader, which cannot"); + } + + // ---- awaiting -------------------------------------------------------- + + [Fact] + public static async Task ItIsArmedAtTheCall_SoItCanBeAwaitedBeforeTheTerminal() + { + var c = new CaptureConnection(("total", 9)) + { + Gate = new(TaskCreationOptions.RunContinuationsAsynchronously), + }; + MappedQuery query = c + .StoredProcedure("p") + .Map() + .CaptureOutput("total", out DbCapture total); + + ValueTask> pending = query.ToListAsync(Token); + Task task = total.AsTask(); + Assert.False(task.IsCompleted); + Assert.Same(task, total.AsTask()); + + // Pending: GetResult throws instead of blocking. + Contains( + Assert.Throws( + () => total.GetAwaiter().GetResult()), + "is not complete yet"); + + c.Gate.SetResult(); + Assert.Equal(9, await total); + Assert.Equal(3, (await pending).Count); + } + + [Fact] + public static void BeforeTheTerminal_EveryMemberThrows() + { + var c = new CaptureConnection(); + _ = c.StoredProcedure("p") + .CaptureOutput("total", out DbCapture total); + + Contains( + Assert.Throws(() => total.GetAwaiter()), + "CaptureOutput(\"total\") has not started", + "Call the query's terminal first"); + Assert.Throws( + () => total.ConfigureAwait(false)); + Assert.Throws(() => { _ = total.AsTask(); }); + } + + [Fact] + public static void ADefaultValue_EveryMemberThrows() + { + DbCapture none = default; + + Contains( + Assert.Throws(() => none.GetAwaiter()), + "This DbCapture was never assigned"); + Assert.Throws( + () => none.ConfigureAwait(false)); + Assert.Throws(() => { _ = none.AsTask(); }); + } + + [Fact] + public static async Task ACanceledToken_CancelsIt() + { + var c = new CaptureConnection(("total", 9)); + using var canceled = new CancellationTokenSource(); + canceled.Cancel(); + MappedQuery query = c + .StoredProcedure("p") + .Map() + .CaptureOutput("total", out DbCapture total); + + await Assert.ThrowsAnyAsync( + async () => await query.ToListAsync(canceled.Token)); + await Assert.ThrowsAnyAsync( + async () => await total); + Assert.True(total.AsTask().IsCanceled); + } + + [Fact] + public static async Task ConfigureAwait_ReadsIt() + { + var c = new CaptureConnection(("total", 9)); + + await c + .StoredProcedure("p") + .CaptureOutput("total", out DbCapture total) + .ExecuteNonQueryAsync(Token); + + Assert.Equal(9, await total.ConfigureAwait(false)); + } + + [Fact] + public static async Task TwoRacingTerminals_OneRuns_TheOtherThrows() + { + for (int round = 0; round < 20; round++) + { + var c = new CaptureConnection(("total", 9)); + MappedQuery query = c + .StoredProcedure("p") + .Map() + .CaptureOutput("total", out DbCapture total); + using var barrier = new Barrier(2); + + Task Run() + => Task.Run(async () => + { + barrier.SignalAndWait(Token); + try + { + return (await query.ToListAsync(Token)).Count; + } + catch (InvalidOperationException ex) + when (ex.Message.Contains( + "already used", + StringComparison.Ordinal)) + { + return -1; + } + }, Token); + + int[] results = await Task.WhenAll(Run(), Run()); + + Assert.Equal(new[] { -1, 3 }, results.Order()); + Assert.Equal(1, c.Executed); + Assert.Equal(9, await total); + } + } + + [Fact] + public static async Task ACaptureFaultedWithTheTerminal_IsNotReportedUnobserved() + { + // The terminal throws the same exception, so a capture that is never + // awaited is not reported again when it is collected. + const string marker = "cannot be used with CancelOnEarlyStop()"; + int unobserved = 0; + void OnUnobserved(object? sender, UnobservedTaskExceptionEventArgs e) + { + if (e.Exception.ToString().Contains( + marker, + StringComparison.Ordinal)) + { + Interlocked.Increment(ref unobserved); + } + } + + TaskScheduler.UnobservedTaskException += OnUnobserved; + try + { + await FaultWithoutAwaiting(); + GC.Collect(); + GC.WaitForPendingFinalizers(); + GC.Collect(); + } + finally + { + TaskScheduler.UnobservedTaskException -= OnUnobserved; + } + + Assert.Equal(0, unobserved); + + static async Task FaultWithoutAwaiting() + { + var c = new CaptureConnection(); + var query = c + .StoredProcedure("p") + .Map() + .CaptureOutput("total", out DbCapture total) + .CancelOnEarlyStop(); + await Assert.ThrowsAsync( + async () => await query.ToListAsync(Token)); + Assert.True(total.AsTask().IsFaulted); + } + } + + [Theory] + [InlineData("Stream")] + [InlineData("StreamBuffered")] + [InlineData("ToPooledStream")] + [InlineData("ToPooledBufferStream")] + public static async Task EveryStream_DeliversOnABreak(string kind) + { + var c = new CaptureConnection(("total", 9)) { Rows = 5000 }; + MappedQuery query = c + .StoredProcedure("p") + .Map() + .CaptureOutput("total", out DbCapture total); + var forever = Timeout.InfiniteTimeSpan; + + int seen = kind switch + { + "Stream" => await TwoRows(query.Stream(forever, Token)), + "StreamBuffered" => await TwoRows( + query.StreamBuffered(forever, 4, Token)), + "ToPooledStream" => await TwoRows(query.ToPooledStream(Token)), + _ => await TwoRows(query.ToPooledBufferStream(Token)), + }; + + Assert.Equal(2, seen); + Assert.Equal(9, await total); + Assert.Equal(1, c.Executed); + + static async Task TwoRows(IAsyncEnumerable rows) + { + int count = 0; + await foreach (TItem _ in rows) + { + if (++count == 2) break; + } + + return count; + } + } + + [Fact] + public static async Task APooledBuffer_ClaimsAtTheCall_AndDelivers() + { + var c = new CaptureConnection(("total", 9)) { Rows = 100 }; + MappedQuery query = c + .StoredProcedure("p") + .Map() + .CaptureOutput("total", out DbCapture total); + + using (PooledBuffer buffer = query.ToPooledBuffer(Token)) + { + Assert.Equal(100, (await buffer.Items).Count); + } + + Assert.Equal(9, await total); + Contains( + Assert.Throws( + () => query.ToPooledBuffer(Token)), + "already used by an earlier run of this query"); + } + + [Fact] + public static async Task CancelingTheEnumeration_CancelsIt() + { + var c = new CaptureConnection(("total", 9)) { Rows = 5000 }; + using var stop = new CancellationTokenSource(); + IAsyncEnumerable rows = c + .StoredProcedure("p") + .Map() + .CaptureOutput("total", out DbCapture total) + .Stream(Timeout.InfiniteTimeSpan, Token); + + await Assert.ThrowsAnyAsync(async () => + { + await foreach (Row row in rows.WithCancellation(stop.Token)) + { + if (row.Id == 2) await stop.CancelAsync(); + } + }); + + await Assert.ThrowsAnyAsync( + async () => await total); + } + + // ---- streams --------------------------------------------------------- + + [Fact] + public static async Task AStream_FillsItWhenTheLoopEnds_EvenOnABreak() + { + var c = new CaptureConnection(("total", 9)) { Rows = 50 }; + IAsyncEnumerable rows = c + .StoredProcedure("p") + .Map() + .CaptureOutput("total", out DbCapture total) + .Stream(Timeout.InfiniteTimeSpan, Token); + + Task? handed = null; + await foreach (Row row in rows) + { + // Awaiting it inside its own loop would wait forever. + Contains( + Assert.Throws( + () => total.GetAwaiter()), + "Await it after the loop"); + handed = total.AsTask(); + if (row.Id == 2) break; + } + + Assert.Equal(9, await total); + Assert.Equal(9, await handed!); + } + + [Fact] + public static async Task AStreamDisposedBeforeItsFirstRow_NeverRan() + { + var c = new CaptureConnection(("total", 9)); + IAsyncEnumerable rows = c + .StoredProcedure("p") + .Map() + .CaptureOutput("total", out DbCapture total) + .Stream(Timeout.InfiniteTimeSpan, Token); + + await rows.GetAsyncEnumerator(Token).DisposeAsync(); + + Contains( + await Assert.ThrowsAsync( + async () => await total), + "the query never ran"); + Assert.Equal(0, c.Executed); + } +} From 6e5b1ef8c90687f7ec5c607b7b380dc2cf8cdcd1 Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Wed, 2 Dec 2026 05:35:49 -0800 Subject: [PATCH 14/20] Docs: captures, output parameters beside rows Three samples in OutputParameters.cs, pulled into the expressive commands article under "Output parameters beside rows": a capture beside ToListAsync, CaptureReturn on the command before Map, and a stream whose capture is awaited after the loop. The article says the definition form is the recommended one, that captures on it come in a later commit of this pull request, and that a capture is per call. One bullet each in What's new and the release notes. Co-Authored-By: Claude Opus 5.5 --- docsite/articles/expressive-commands.md | 21 ++++++++ docsite/articles/release-notes.md | 1 + docsite/articles/whats-new-11.md | 1 + docsite/samples/OutputParameters.cs | 68 +++++++++++++++++++++++++ 4 files changed, 91 insertions(+) diff --git a/docsite/articles/expressive-commands.md b/docsite/articles/expressive-commands.md index 59b37785..26b3ab90 100644 --- a/docsite/articles/expressive-commands.md +++ b/docsite/articles/expressive-commands.md @@ -213,6 +213,27 @@ There is no blocking form. Known limits: - **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. +### Output parameters beside rows + +`ExecuteOutputAsync` runs the command for its outputs alone. To read rows and outputs from one call, capture the outputs: `CaptureOutput` (a model, one value, or a `decimal` with its precision and scale, as `ExecuteOutputAsync` takes them), `CaptureOutputDecimal` and `CaptureReturn` give a `DbCapture` as an `out` argument, and the query's async terminal fills it. Await the capture after the terminal: + +[!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: + +[!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): + +[!code-csharp[](../samples/OutputParameters.cs#sql_server_output_capture_stream)] + +The recommended form for a query is the definition: `static readonly MappedDbQuery X = DbQuery.Procedure("…").Map();`, then `X.Using(factory).AddParam(…)` and the terminal per call (see [Map the definition too](#map-the-definition-too)). Captures on the definition form come in a later commit of this pull request, so these samples use the ad hoc form. There, too, a capture is per call: it goes after `Using` and the parameters, never on the stored definition. + +- **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. +- **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 | Terminal | Returns | diff --git a/docsite/articles/release-notes.md b/docsite/articles/release-notes.md index 75dd08fe..78e5bac9 100644 --- a/docsite/articles/release-notes.md +++ b/docsite/articles/release-notes.md @@ -11,6 +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 `InvalidOperationException` at the call. See [Output parameters beside rows](expressive-commands.md#output-parameters-beside-rows). - **New: `ToArrayAsync` and `ToImmutableArrayAsync` on a `DbDataReader`.** Like `ToListAsync(transform)`, they read the remaining rows of the current result set through an asynchronous transform into pooled chunks and copy them once, into an array of exactly their number; on .NET 8 and later the immutable array wraps that array and does not copy it again (on .NET Standard it is a copy). - **Changed: the collecting terminals clear their value rows when no pool is offered.** `ToList`, `ToArray`, `ToImmutableArray`, `ToHashSet` and the dictionaries, asynchronous and synchronous, on a view or on a `DbDataReader`, copy their rows out and never show their pooled arrays, so they hide their pooling: a query that does not call `UsePool` now always clears the used rows of those arrays before they go back, plain value rows included, whatever the `Open.Database.Extensions.ClearPooledArrays` switch says. `UsePool(pool, clearOnReturn)` is followed as before, so `clearOnReturn: false` still keeps the rows. Rows that hold references were always cleared. The buffers and streams are unchanged: their default is still not to clear value rows. A chunk of 128 KB or more is cleared in the background, as before, and the allocation of a call is the same. - **Changed: the synchronous `ToList()` reads into pooled chunks, as `ToListAsync` does.** On a view or a reader it grew a list of its own, and so allocated the growth as well as the result and rented no pooled array; it now reads into the chain of pooled arrays and copies the rows once into a list of exactly their number, so the copy-out clearing above applies to it too. The growth is gone: 100,000 `int` rows allocate about 400 KB instead of about 1.05 MB, and 1,000 rows about 28.8 KB instead of 33.2 KB. diff --git a/docsite/articles/whats-new-11.md b/docsite/articles/whats-new-11.md index c03394c5..a41ec817 100644 --- a/docsite/articles/whats-new-11.md +++ b/docsite/articles/whats-new-11.md @@ -131,6 +131,7 @@ See [Expressive commands](expressive-commands.md). - **After a run, `Params` holds what you added,** under the names as added. Read the provider command's `Parameters` in `Execute(command => ...)` to see what was sent. - **No direction on the chain.** `AddParam`, `AddParamIf` and `AddReturnParam` no longer take a `ParameterDirection`, so a parameter added on the chain is an input; `AddReturnParam` is gone. Calls that never passed a direction compile unchanged; `AddParam(name, direction)`, `AddParamIf(condition, name, direction)`, `AddParam(name, type)` and `AddParamIf(condition, name, type)` are now compile errors that say what to do instead. The forms that took a direction after the value, `AddParam(name, value, ParameterDirection)` and `AddParam(name, value, type, direction)` (the SQL Server forms with a database type and a direction too), fail to compile with the compiler's own argument error, without a message of their own: use the raw `AddParameter` inside `ExecuteAsync(command => ...)`, or read the output with `ExecuteOutputAsync`. To set a direction, use `ExecuteAsync(command => ...)` with the raw `AddParameter`, `AddParameterType` and `AddReturnParameter` extensions. `Param` has no `direction` constructor parameter and no `Direction` property. - **Output parameters into a model.** `ExecuteOutputAsync()` reads a command's output parameters and return code into a model by name (`ExecuteOutputAsync(name)` for one value): see [Output parameters](expressive-commands.md#output-parameters). +- **Output parameters beside rows.** `CaptureOutput`, `CaptureOutputDecimal` and `CaptureReturn` on a command or a mapped query give a `DbCapture` that the async terminal fills, so one call returns rows and outputs: see [Output parameters beside rows](expressive-commands.md#output-parameters-beside-rows). See [Parameters](expressive-commands.md#name-a-parameter-from-its-argument). diff --git a/docsite/samples/OutputParameters.cs b/docsite/samples/OutputParameters.cs index 15ab74cb..69e29f3a 100644 --- a/docsite/samples/OutputParameters.cs +++ b/docsite/samples/OutputParameters.cs @@ -72,6 +72,74 @@ public static async Task Decimals( } #endregion + #region sql_server_output_capture_list + public record PostRow(int Id, string Title); + + public record PostPage(List Rows, int Total); + + // A page of posts, and the total the procedure sets as an OUTPUT. + public static async Task Page( + int page, + CancellationToken cancellationToken) + { + List rows = await Blog + .StoredProcedure("[dbo].[PagePosts]") + .AddParam(page) + .Map() + .CaptureOutput("total", out DbCapture total) + .ToListAsync(cancellationToken); + + // Filled by the time the terminal's task completes: await it after. + return new PostPage(rows, await total); + } + #endregion + + #region sql_server_output_capture_return + public static async Task> Archive( + DateTime before, + CancellationToken cancellationToken) + { + // On the command: the query Map makes runs it, and fills it. + List archived = await Blog + .StoredProcedure("[dbo].[ArchivePosts]") + .AddParam(before) + .CaptureReturn(out DbCapture status) + .Map() + .ToListAsync(cancellationToken); + + int code = await status; + if (code != 0) + { + throw new InvalidOperationException( + $"ArchivePosts returned {code}."); + } + + return archived; + } + #endregion + + #region sql_server_output_capture_stream + public static async Task Export( + TextWriter writer, + CancellationToken cancellationToken) + { + IAsyncEnumerable rows = Blog + .StoredProcedure("[dbo].[ExportPosts]") + .Map() + .CaptureOutput("exported", out DbCapture exported) + .ToPooledStream(cancellationToken); + + await foreach (PostRow row in rows) + { + await writer.WriteLineAsync(row.Title); + } + + // Complete once the loop has ended, a break included: await it + // after the loop, never inside it. + return await exported; + } + #endregion + public static async Task Raw( string title, CancellationToken cancellationToken) From af80660484f78696d1fd49356324d92bcbfcf746 Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Wed, 2 Dec 2026 05:35:49 -0800 Subject: [PATCH 15/20] Samples: pass the token to WriteLineAsync in the stream sample. CA2016 at info severity: the capture stream sample now forwards its cancellation token to the writer. Co-Authored-By: Claude Opus 5.5 --- docsite/samples/OutputParameters.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docsite/samples/OutputParameters.cs b/docsite/samples/OutputParameters.cs index 69e29f3a..938bf79b 100644 --- a/docsite/samples/OutputParameters.cs +++ b/docsite/samples/OutputParameters.cs @@ -131,7 +131,9 @@ public static async Task Export( await foreach (PostRow row in rows) { - await writer.WriteLineAsync(row.Title); + await writer.WriteLineAsync( + row.Title.AsMemory(), + cancellationToken); } // Complete once the loop has ended, a break included: await it From 43640d40349e4ac66651c436d4fc2667fefd978c Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Wed, 2 Dec 2026 06:36:10 -0800 Subject: [PATCH 16/20] Captures: tests on every path, and the Channel and Dataflow members arm at the call A command that re-implements IExecuteReader can no longer leave a capture pending. A query with a capture (its own or its command's) runs through the command's own reader path, and the synchronous path refuses it as before. The Channel and Dataflow feeds take the stream's enumerator before their first await, so the capture is claimed at the call. Then they wait for room in the channel, or check that the block has not finished. A target closed before the first row runs nothing, and the capture says so: "the query never ran: ... its target closed". The stall signal of StreamBuffered is now seen through the capture's stream wrapper, so a stall while the target has no room still ends the pass with a TimeoutException. The docs say that a fault only the capture carries (a conversion, outputs not delivered) is reported only there. Tests: - The fake provider moves to TestHelpers/CaptureProvider.cs. It can now fail a run, and its gate honors the token. - CaptureStreamTests: a failed run; a stall; a cancel while the command runs, on every stream; a second enumeration; a PooledBuffer disposed mid-read or given a canceled token; every Channel and Dataflow member arming at its call; a closed channel, a finished block, a full channel, a cancel while waiting for room, a target closed after the first row, a stall through the wrapper; a command that re-implements its reader; a null transform throwing before anything is armed. - CaptureLocalDbTests (SQL Server LocalDB): rows with an output and the return code; an early stop on every stream and the buffer still delivers; a later error faults the capture with the same SqlException; a cancel mid-read; a model with a decimal; a text command's output marker. Co-Authored-By: Claude Opus 5.5 --- Source/Channel/ChannelPump.cs | 159 +++-- Source/Core/Capture.cs | 8 +- Source/Core/CapturedStream.cs | 10 +- Source/Core/MappedQuery.Capture.cs | 6 +- Source/Core/MappedQuery.cs | 17 +- Source/Core/Output.docs.xml | 3 + Source/Dataflow/BlockPump.cs | 137 +++-- .../CaptureLocalDbTests.cs | 213 +++++++ .../CaptureStreamTests.cs | 571 ++++++++++++++++++ .../CaptureTests.cs | 146 ----- .../TestHelpers/CaptureProvider.cs | 164 +++++ 11 files changed, 1179 insertions(+), 255 deletions(-) create mode 100644 Tests/Open.Database.Extensions.Core.Tests/CaptureLocalDbTests.cs create mode 100644 Tests/Open.Database.Extensions.Core.Tests/CaptureStreamTests.cs create mode 100644 Tests/Open.Database.Extensions.Core.Tests/TestHelpers/CaptureProvider.cs diff --git a/Source/Channel/ChannelPump.cs b/Source/Channel/ChannelPump.cs index fec60665..e4c390d5 100644 --- a/Source/Channel/ChannelPump.cs +++ b/Source/Channel/ChannelPump.cs @@ -34,16 +34,8 @@ internal static async ValueTask Run( Exception? error = null; try { - // Wait for room before the feed starts, so a full target never - // gets a command run or a connection opened for it. - // Closed before the first row: nothing to write, nothing read. - if (!await writer - .WaitToWriteAsync(cancellationToken) - .ConfigureAwait(false)) - { - return 0; - } - + // Reached at the call: the feed takes the stream's enumerator + // before its first await, then waits for room (ChannelPump.Open). return await feed .WriteAsync(writer, cancellationToken) .ConfigureAwait(false); @@ -60,6 +52,44 @@ internal static async ValueTask Run( } } + /// + /// Takes the enumerator of a feed's stream, then waits for room. + /// + /// + /// The enumerator is taken first, synchronously, so a stream that fills + /// captures claims them at the call; it starts nothing until the first + /// pull. The wait comes before that pull, so a full target never gets + /// a command run or a connection opened for it. + /// + /// + /// The enumerator, or when the writer was closed + /// before the first row (the enumerator is disposed: nothing read). + /// + internal static async ValueTask?> Open( + IAsyncEnumerable stream, + ChannelWriter writer, + CancellationToken cancellationToken) + { + IAsyncEnumerator rows + = stream.GetAsyncEnumerator(cancellationToken); + bool room = false; + try + { + room = await writer.WaitToWriteAsync(cancellationToken) + .ConfigureAwait(false); + } + finally + { + if (!room) + { + await rows.DisposeAsync() + .ConfigureAwait(false); + } + } + + return room ? rows : null; + } + /// /// Writes rows from a position of a chunk until the writer has no room. /// @@ -109,32 +139,46 @@ public async ValueTask WriteAsync( ChannelWriter writer, CancellationToken cancellationToken) { - long count = 0; - await foreach (ReadOnlyMemory chunk in chunks - .WithCancellation(cancellationToken) - .ConfigureAwait(false)) + IAsyncEnumerator>? chunked + = await ChannelPump.Open(chunks, writer, cancellationToken) + .ConfigureAwait(false); + if (chunked is null) return 0; + + try { - int i = 0; - while (true) + long count = 0; + while (await chunked.MoveNextAsync() + .ConfigureAwait(false)) { - int next = ChannelPump.TryWriteFrom(writer, chunk, i); - count += next - i; - i = next; - if (i == chunk.Length) break; - - // Full, or closed: wait for room, then write the same row. - // Leaving the loop disposes the stream, which cancels the - // query and releases every chunk. - if (!await writer - .WaitToWriteAsync(cancellationToken) - .ConfigureAwait(false)) + ReadOnlyMemory chunk = chunked.Current; + int i = 0; + while (true) { - return count; + int next = ChannelPump.TryWriteFrom(writer, chunk, i); + count += next - i; + i = next; + if (i == chunk.Length) break; + + // Full, or closed: wait for room, then write the same + // row. Leaving the loop disposes the stream, which + // cancels the query and releases every chunk (a query + // with a capture stops at its next chunk instead, and + // fills the capture). + if (!await writer.WaitToWriteAsync(cancellationToken) + .ConfigureAwait(false)) + { + return count; + } } } - } - return count; + return count; + } + finally + { + await chunked.DisposeAsync() + .ConfigureAwait(false); + } } } @@ -166,32 +210,45 @@ public async ValueTask WriteAsync( : null; CancellationToken wait = link?.Token ?? cancellationToken; - long count = 0; - await foreach (T row in rows - .WithCancellation(cancellationToken) - .ConfigureAwait(false)) + IAsyncEnumerator? pulled + = await ChannelPump.Open(rows, writer, cancellationToken) + .ConfigureAwait(false); + if (pulled is null) return 0; + + try { - while (!writer.TryWrite(row)) + long count = 0; + while (await pulled.MoveNextAsync() + .ConfigureAwait(false)) { - // Without a link there is no signal that can fire: - // the plain wait, nothing created. - bool room = link is null - ? await writer - .WaitToWriteAsync(cancellationToken) - .ConfigureAwait(false) - : await WaitAsync( - writer, - signal!, - wait, - cancellationToken).ConfigureAwait(false); - - if (!room) return count; + T row = pulled.Current; + while (!writer.TryWrite(row)) + { + // Without a link there is no signal that can fire: + // the plain wait, nothing created. + bool room = link is null + ? await writer.WaitToWriteAsync(cancellationToken) + .ConfigureAwait(false) + : await WaitAsync( + writer, + signal!, + wait, + cancellationToken) + .ConfigureAwait(false); + + if (!room) return count; + } + + ++count; } - ++count; + return count; + } + finally + { + await pulled.DisposeAsync() + .ConfigureAwait(false); } - - return count; } static async ValueTask WaitAsync( diff --git a/Source/Core/Capture.cs b/Source/Core/Capture.cs index 1fc8eb9d..57f95cfa 100644 --- a/Source/Core/Capture.cs +++ b/Source/Core/Capture.cs @@ -962,10 +962,10 @@ public static string NotDelivered(ICaptureSource source) public static string NotRun(ICaptureSource source) => $"{source.Display} has no value: " - + "the stream was disposed before it read anything, " - + "so the query never ran. " - + "Enumerate the stream (await foreach) to the end, " - + "then await the capture."; + + "the query never ran: its stream was disposed, or its target " + + "closed, before the first row. " + + "Read the stream (await foreach) to the end, or give the target " + + "room, then await the capture."; public static string Internal(ICaptureSource source) => $"{source.Display} was armed, " diff --git a/Source/Core/CapturedStream.cs b/Source/Core/CapturedStream.cs index 167d25d0..e9e3e922 100644 --- a/Source/Core/CapturedStream.cs +++ b/Source/Core/CapturedStream.cs @@ -22,7 +22,7 @@ namespace Open.Database.Extensions; sealed class CapturedStream( IAsyncEnumerable inner, CaptureRun run) - : IAsyncEnumerable, IAsyncEnumerator + : IAsyncEnumerable, IAsyncEnumerator, IStallSignal { IAsyncEnumerator? _inner; Exception? _error; @@ -33,6 +33,14 @@ sealed class CapturedStream( public TItem Current => _inner!.Current; + // The inner stream's stall signal, so the Channel and Dataflow pumps + // see it through the wrapper; none for a stream without a timeout. + public CancellationToken Expired + => (inner as IStallSignal)?.Expired ?? default; + + public TimeoutException ToException() + => ((IStallSignal)inner).ToException(); + public IAsyncEnumerator GetAsyncEnumerator( CancellationToken cancellationToken = default) { diff --git a/Source/Core/MappedQuery.Capture.cs b/Source/Core/MappedQuery.Capture.cs index 38d8de0e..4ab148b6 100644 --- a/Source/Core/MappedQuery.Capture.cs +++ b/Source/Core/MappedQuery.Capture.cs @@ -12,9 +12,9 @@ readonly partial struct MappedQueryCore /// command's. /// /// The captures, or . - // For the streams, the buffer and CancelOnEarlyStop() only: a direct - // terminal without its own captures runs on the command, which checks its - // own. + // Every run checks it: the two chokes, the streams, the buffer and + // CancelOnEarlyStop(). Without a capture it costs a type check of the + // command and a field read. CaptureHolder? Captured() => _captures ?? (_command as ICaptureRunner)?.Captures; diff --git a/Source/Core/MappedQuery.cs b/Source/Core/MappedQuery.cs index 77a4fe2b..f334a1af 100644 --- a/Source/Core/MappedQuery.cs +++ b/Source/Core/MappedQuery.cs @@ -560,21 +560,24 @@ ValueTask ExecuteAsync(TState state, FuncRuns the reader function on the call, held as it is, or on the command. // Captures are async only: a synchronous run is refused before anything - // runs, and nothing is claimed. + // runs, and nothing is claimed. The command's captures are checked here + // too, so a command that re-implements the reader cannot skip the check. TResult ExecuteReader(TState state, Func transform, CommandBehavior behavior) - => _captures is not null - ? throw _captures.SyncRefused() + => Captured() is { } captures + ? throw captures.SyncRefused() : _call.IsBound ? _call.Run(state, transform, behavior) : Command.AsSync().ExecuteReader(state, transform, behavior); /// Runs the asynchronous reader function on the call, held as it is, or on the command. - // With captures, the command fills them (only a command can be given them: - // see WithCapture). + // 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. ValueTask ExecuteReaderAsync(TState state, Func> transform, CommandBehavior behavior, CancellationToken token) - => _captures is not null + => Captured() is { } captures ? ((ICaptureRunner)_command!).ExecuteReaderAsync( - _captures, + captures, state, transform, behavior, diff --git a/Source/Core/Output.docs.xml b/Source/Core/Output.docs.xml index 7e3bd906..c22f8a1e 100644 --- a/Source/Core/Output.docs.xml +++ b/Source/Core/Output.docs.xml @@ -252,6 +252,9 @@ It completes once, with the run: with the value; faulted with the run's error or the conversion's (the terminal's own result is unaffected by a conversion error); canceled when the caller's token is; or faulted when the outputs were not delivered (the response did not complete). + A fault that only the capture carries + (a conversion, outputs not delivered) is reported only there: + a capture that is never awaited leaves it unobserved. diff --git a/Source/Dataflow/BlockPump.cs b/Source/Dataflow/BlockPump.cs index 08cecd66..768066e3 100644 --- a/Source/Dataflow/BlockPump.cs +++ b/Source/Dataflow/BlockPump.cs @@ -36,12 +36,8 @@ internal static async ValueTask Run( Exception? error = null; try { - // A block has no way to ask for room: only a row can tell. - // A block that is already finished is the one thing known now, - // and no command is run for it. - if (target.Completion.IsCompleted) - return 0; - + // Reached at the call: the feed takes the stream's enumerator + // before its first await, then checks the block (Open). return await feed .WriteAsync(target, cancellationToken) .ConfigureAwait(false); @@ -60,6 +56,34 @@ internal static async ValueTask Run( } } } + + /// + /// Takes the enumerator of a feed's stream, then checks the block. + /// + /// + /// The enumerator is taken first, synchronously, so a stream that fills + /// captures claims them at the call; it starts nothing until the first + /// pull. A block has no way to ask for room: only a row can tell. A block + /// that is already finished is the one thing known now, and no command + /// is run for it. + /// + /// + /// The enumerator, or when the block is already + /// finished (the enumerator is disposed: nothing read). + /// + internal static async ValueTask?> Open( + IAsyncEnumerable stream, + ITargetBlock target, + CancellationToken cancellationToken) + { + IAsyncEnumerator rows + = stream.GetAsyncEnumerator(cancellationToken); + if (!target.Completion.IsCompleted) return rows; + + await rows.DisposeAsync() + .ConfigureAwait(false); + return null; + } } /// @@ -92,30 +116,44 @@ public async ValueTask WriteAsync( ITargetBlock target, CancellationToken cancellationToken) { - long count = 0; - await foreach (ReadOnlyMemory chunk in chunks - .WithCancellation(cancellationToken) - .ConfigureAwait(false)) + IAsyncEnumerator>? chunked + = await BlockPump.Open(chunks, target, cancellationToken) + .ConfigureAwait(false); + if (chunked is null) return 0; + + try { - for (int i = 0; i < chunk.Length; ++i) + long count = 0; + while (await chunked.MoveNextAsync() + .ConfigureAwait(false)) { - // SendAsync waits while a bounded target is full; - // false means the target declined for good. - // Leaving the loop disposes the stream, which cancels the - // query and releases every chunk. - T row = chunk.Span[i]; - if (!await target - .SendAsync(row, cancellationToken) - .ConfigureAwait(false)) + ReadOnlyMemory chunk = chunked.Current; + for (int i = 0; i < chunk.Length; ++i) { - return count; - } + // SendAsync waits while a bounded target is full; + // false means the target declined for good. + // Leaving the loop disposes the stream, which cancels + // the query and releases every chunk (a query with a + // capture stops at its next chunk instead, and fills + // the capture). + T row = chunk.Span[i]; + if (!await target.SendAsync(row, cancellationToken) + .ConfigureAwait(false)) + { + return count; + } - ++count; + ++count; + } } - } - return count; + return count; + } + finally + { + await chunked.DisposeAsync() + .ConfigureAwait(false); + } } } @@ -146,27 +184,40 @@ public async ValueTask WriteAsync( : null; CancellationToken wait = link?.Token ?? cancellationToken; - long count = 0; - await foreach (T row in rows - .WithCancellation(cancellationToken) - .ConfigureAwait(false)) + IAsyncEnumerator? pulled + = await BlockPump.Open(rows, target, cancellationToken) + .ConfigureAwait(false); + if (pulled is null) return 0; + + try { - bool accepted = link is null - ? await target - .SendAsync(row, cancellationToken) - .ConfigureAwait(false) - : await SendAsync( - target, - row, - signal!, - wait, - cancellationToken).ConfigureAwait(false); - - if (!accepted) return count; - ++count; - } + long count = 0; + while (await pulled.MoveNextAsync() + .ConfigureAwait(false)) + { + T row = pulled.Current; + bool accepted = link is null + ? await target.SendAsync(row, cancellationToken) + .ConfigureAwait(false) + : await SendAsync( + target, + row, + signal!, + wait, + cancellationToken) + .ConfigureAwait(false); - return count; + if (!accepted) return count; + ++count; + } + + return count; + } + finally + { + await pulled.DisposeAsync() + .ConfigureAwait(false); + } } static async ValueTask SendAsync( diff --git a/Tests/Open.Database.Extensions.Core.Tests/CaptureLocalDbTests.cs b/Tests/Open.Database.Extensions.Core.Tests/CaptureLocalDbTests.cs new file mode 100644 index 00000000..915aece7 --- /dev/null +++ b/Tests/Open.Database.Extensions.Core.Tests/CaptureLocalDbTests.cs @@ -0,0 +1,213 @@ +using Microsoft.Data.SqlClient; +using System.ComponentModel.DataAnnotations.Schema; + +#nullable enable + +namespace Open.Database.Extensions.Tests; + +// The captures against SQL Server: the outputs come after the rows, on every +// path, and a consumer that stops early still gets them, because closing the +// reader reads the rest of the response. +// Skipped without LocalDB (see LocalDbFixture). +[ExcludeFromCodeCoverage] +[Collection("LocalDB DDL")] +public static class CaptureLocalDbTests +{ + static CancellationToken Token + => TestContext.Current.CancellationToken; + + public sealed record Row(int Id); + + public sealed record Totals( + [property: Column(TypeName = "decimal(10,2)")] decimal Total, + int Count); + + // Enough rows that a stop after the first leaves most of them unread. + const string ManyRows + = "select top (50000) row_number() over (order by (select null)) as Id" + + " from sys.all_objects a cross join sys.all_objects b;"; + + static LocalDbFixture.Scratch Procedure(string parameters, string body) + => LocalDbFixture.CreateProcedureWithBody( + parameters, + "set nocount on; " + body, + "ode_cap"); + + static async Task OpenAsync() + { + SqlConnection connection = LocalDbFixture.Create(); + await connection.OpenAsync(Token); + return connection; + } + + [Fact] + public static async Task TheRows_AnOutput_AndTheReturnCode() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = Procedure( + "@total int output", + "select n as Id from (values (1), (2), (3)) v(n);" + + " set @total = 3; return 7;"); + await using SqlConnection connection = await OpenAsync(); + string name = "dbo." + procedure.Name; + + List rows = await connection.StoredProcedure(name) + .CaptureOutput("total", out DbCapture total) + .CaptureReturn(out DbCapture code) + .Map() + .ToListAsync(Token); + + Assert.Equal([1, 2, 3], rows.Select(static r => r.Id)); + Assert.Equal(3, await total); + Assert.Equal(7, await code); + } + + // The real drain: the outputs are sent after every row, so they arrive + // only when closing the reader reads the rows nobody asked for. + [Theory] + [InlineData("Stream")] + [InlineData("StreamBuffered")] + [InlineData("ToPooledStream")] + [InlineData("ToPooledBufferStream")] + [InlineData("ToPooledBuffer")] + public static async Task AnEarlyStop_StillDelivers(string kind) + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = Procedure( + "@total int output", + ManyRows + " set @total = 42;"); + await using SqlConnection connection = await OpenAsync(); + string name = "dbo." + procedure.Name; + MappedQuery query = connection.StoredProcedure(name) + .Map() + .CaptureOutput("total", out DbCapture total); + var forever = Timeout.InfiniteTimeSpan; + + switch (kind) + { + case "Stream": + await TakeOne(query.Stream(forever, Token)); + break; + case "StreamBuffered": + await TakeOne(query.StreamBuffered(forever, 4, Token)); + break; + case "ToPooledStream": + await TakeOne(query.ToPooledStream(Token)); + break; + case "ToPooledBufferStream": + await TakeOne(query.ToPooledBufferStream(Token)); + break; + default: + query.ToPooledBuffer(Token) + .Dispose(); + break; + } + + Assert.Equal(42, await total); + + static async Task TakeOne(IAsyncEnumerable items) + { + await using IAsyncEnumerator e = items.GetAsyncEnumerator(); + Assert.True(await e.MoveNextAsync()); + } + } + + [Fact] + public static async Task ALaterError_FaultsIt_WithTheProvidersError() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = Procedure( + "@total int output", + "select 1 as Id; set @total = 7;" + + " raiserror('late failure', 16, 1);"); + await using SqlConnection connection = await OpenAsync(); + string name = "dbo." + procedure.Name; + + MappedQuery query = connection.StoredProcedure(name) + .Map() + .CaptureOutput("total", out DbCapture total); + + SqlException ex = await Assert.ThrowsAsync( + async () => await query.ToListAsync(Token)); + Assert.Contains("late failure", ex.Message); + Assert.Same( + ex, + await Assert.ThrowsAsync(async () => await total)); + } + + // The rows are handed over one at a time (or four), so the cancel lands + // mid-read: the caller's cancel cancels the capture too. + [Theory] + [InlineData(0)] + [InlineData(4)] + public static async Task ACancelMidRead_CancelsIt(int bufferSize) + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = Procedure( + "@total int output", + ManyRows + " set @total = 42;"); + await using SqlConnection connection = await OpenAsync(); + string name = "dbo." + procedure.Name; + IAsyncEnumerable rows = connection.StoredProcedure(name) + .Map() + .CaptureOutput("total", out DbCapture total) + .StreamBuffered(Timeout.InfiniteTimeSpan, bufferSize, Token); + using var stop = CancellationTokenSource.CreateLinkedTokenSource(Token); + + await Assert.ThrowsAnyAsync(async () => + { + await foreach (Row _ in rows.WithCancellation(stop.Token)) + { + await stop.CancelAsync(); + } + }); + + await Assert.ThrowsAnyAsync( + async () => await total); + } + + [Fact] + public static async Task AModel_WithADecimal_AndTheNamedDecimal() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = Procedure( + "@total decimal(10,2) output, @count int output", + "select 1 as Id; set @total = 12.34; set @count = 2;"); + await using SqlConnection connection = await OpenAsync(); + string name = "dbo." + procedure.Name; + + Assert.Single(await connection.StoredProcedure(name) + .Map() + .CaptureOutput(out DbCapture totals) + .ToListAsync(Token)); + Assert.Equal(new Totals(12.34m, 2), await totals); + + Assert.Single(await connection.StoredProcedure(name) + .Map() + .CaptureOutputDecimal("total", 10, 2, out DbCapture total) + .CaptureOutput("count", out DbCapture count) + .ToListAsync(Token)); + Assert.Equal(12.34m, await total); + Assert.Equal(2, await count); + } + + // A text command's @name OUTPUT marker. + [Fact] + public static async Task ATextCommand_FillsItThroughItsMarker() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = Procedure( + "@total int output", + "select n as Id from (values (1), (2)) v(n); set @total = 2;"); + await using SqlConnection connection = await OpenAsync(); + string sql = $"exec dbo.[{procedure.Name}] @total output"; + + List rows = await connection.Command(sql) + .CaptureOutput("total", out DbCapture total) + .Map() + .ToListAsync(Token); + + Assert.Equal(2, rows.Count); + Assert.Equal(2, await total); + } +} diff --git a/Tests/Open.Database.Extensions.Core.Tests/CaptureStreamTests.cs b/Tests/Open.Database.Extensions.Core.Tests/CaptureStreamTests.cs new file mode 100644 index 00000000..e97cc7a4 --- /dev/null +++ b/Tests/Open.Database.Extensions.Core.Tests/CaptureStreamTests.cs @@ -0,0 +1,571 @@ +using System.Threading.Tasks.Dataflow; + +#nullable enable + +namespace Open.Database.Extensions.Tests; + +// The captures on the stream paths (Stream, StreamBuffered, the pooled +// streams and buffer), on the Channel and Dataflow members, and on the edges: +// a failed run, a stall, a cancel mid-read, a command that re-implements its +// reader. Every armed capture completes, and none hangs. +[ExcludeFromCodeCoverage] +public static class CaptureStreamTests +{ + static CancellationToken Token + => TestContext.Current.CancellationToken; + + public sealed record Row(int Id); + + static void Contains(Exception ex, params string[] phrases) + { + foreach (string phrase in phrases) Assert.Contains(phrase, ex.Message); + } + + static MappedQuery Query( + CaptureConnection c, + out DbCapture total) + => c.StoredProcedure("p") + .Map() + .CaptureOutput("total", out total); + + // ---- a run that fails ------------------------------------------------ + + [Fact] + public static async Task AFailedRun_FaultsIt_WithTheSameException() + { + var fault = new InvalidOperationException("the provider failed"); + var c = new CaptureConnection(("total", 9)) { Fault = fault }; + MappedQuery query = Query(c, out DbCapture total); + + Assert.Same( + fault, + await Assert.ThrowsAsync( + async () => await query.ToListAsync(Token))); + Assert.Same( + fault, + await Assert.ThrowsAsync( + async () => await total)); + } + + [Fact] + public static async Task AFailedStream_FaultsIt() + { + var fault = new InvalidOperationException("the provider failed"); + var c = new CaptureConnection(("total", 9)) { Fault = fault }; + IAsyncEnumerable rows = Query(c, out DbCapture total) + .ToPooledStream(Token); + + await Assert.ThrowsAsync(async () => + { + await foreach (Row _ in rows) { } + }); + Assert.Same( + fault, + await Assert.ThrowsAsync( + async () => await total)); + } + + // ---- the streams ----------------------------------------------------- + + [Theory] + [InlineData(0)] + [InlineData(2)] + public static async Task AStall_FaultsIt_WithTheTimeout(int bufferSize) + { + var c = new CaptureConnection(("total", 9)) { Rows = 50 }; + IAsyncEnumerable rows = Query(c, out DbCapture total) + .StreamBuffered(TimeSpan.FromMilliseconds(50), bufferSize, Token); + + await Assert.ThrowsAsync(async () => + { + await foreach (Row _ in rows) + { + await Task.Delay(400, Token); + } + }); + await Assert.ThrowsAsync(async () => await total); + } + + [Theory] + [InlineData("Stream")] + [InlineData("StreamBuffered")] + [InlineData("ToPooledStream")] + [InlineData("ToPooledBufferStream")] + public static async Task ACancelWhileItRuns_CancelsIt(string kind) + { + var c = new CaptureConnection(("total", 9)) + { + Gate = new(TaskCreationOptions.RunContinuationsAsynchronously), + }; + MappedQuery query = Query(c, out DbCapture total); + var forever = Timeout.InfiniteTimeSpan; + + // The command waits at its gate; the enumeration's token cancels it. + await (kind switch + { + "Stream" => CancelFirst(query.Stream(forever, Token)), + "StreamBuffered" => CancelFirst( + query.StreamBuffered(forever, 4, Token)), + "ToPooledStream" => CancelFirst(query.ToPooledStream(Token)), + _ => CancelFirst(query.ToPooledBufferStream(Token)), + }); + + await Assert.ThrowsAnyAsync( + async () => await total); + Assert.Equal(0, c.Executed); + + static async Task CancelFirst(IAsyncEnumerable items) + { + using var stop = new CancellationTokenSource(); + IAsyncEnumerator e = items.GetAsyncEnumerator(stop.Token); + try + { + Task first = e.MoveNextAsync() + .AsTask(); + await stop.CancelAsync(); + await Assert.ThrowsAnyAsync( + () => first); + } + finally + { + await e.DisposeAsync(); + } + } + } + + [Fact] + public static async Task ASecondEnumeration_IsRefused_AndLeavesTheFirstRun() + { + var c = new CaptureConnection(("total", 9)); + IAsyncEnumerable rows = Query(c, out DbCapture total) + .Stream(Timeout.InfiniteTimeSpan, Token); + + int count = 0; + await foreach (Row _ in rows) + { + ++count; + } + + Contains( + Assert.Throws( + () => rows.GetAsyncEnumerator(Token)), + "can be enumerated only once"); + Assert.Equal(3, count); + Assert.Equal(9, await total); + } + + [Fact] + public static async Task APooledBufferDisposedMidRead_StillDelivers() + { + var c = new CaptureConnection(("total", 9)) { Rows = 200_000 }; + MappedQuery query = Query(c, out DbCapture total); + + query.ToPooledBuffer(Token) + .Dispose(); + + // Stopped at a chunk, or read to the end: the outputs either way. + Assert.Equal(9, await total); + } + + [Fact] + public static async Task APooledBuffer_WithACanceledToken_CancelsIt() + { + var c = new CaptureConnection(("total", 9)); + using var canceled = new CancellationTokenSource(); + await canceled.CancelAsync(); + MappedQuery query = Query(c, out DbCapture total); + + using (PooledBuffer buffer = query.ToPooledBuffer(canceled.Token)) + { + await Assert.ThrowsAnyAsync( + async () => await buffer.Items); + } + + await Assert.ThrowsAnyAsync( + async () => await total); + Assert.Equal(0, c.Executed); + } + + // ---- Channel and Dataflow -------------------------------------------- + + public static TheoryData Entries + => new( + "ToChannelReader", + "ToChannel", + "ToBoundedChannelReader", + "ToChannel(target)", + "ToChannelHoldingConnection", + "AsSourceBlock", + "ToTargetBlock", + "ToTargetBlockHoldingConnection"); + + // Every member claims the capture at its call, before its first await, + // and the capture completes with the pass. + [Theory] + [MemberData(nameof(Entries))] + public static async Task EveryChannelAndBlockMember_ArmsAtTheCall( + string entry) + { + var c = new CaptureConnection(("total", 9)) + { + Gate = new(TaskCreationOptions.RunContinuationsAsynchronously), + }; + MappedQuery query = Query(c, out DbCapture total); + + Func> drain = Start(query, entry); + + // Armed, not complete: AsTask would throw "has not started" if not. + Task pending = total.AsTask(); + Assert.False(pending.IsCompleted); + + c.Gate.SetResult(); + Assert.Equal(3, await drain()); + Assert.Equal(9, await total); + Assert.Equal(1, c.Executed); + } + + // Starts the member and returns what drains it, with the row count. + static Func> Start(MappedQuery query, string entry) + { + var forever = Timeout.InfiniteTimeSpan; + switch (entry) + { + case "ToChannelReader": + return Drain(query.ToChannelReader(Token)); + case "ToChannel": + return Drain(query.ToChannel(Token).Reader); + case "ToBoundedChannelReader": + return Drain(query.ToBoundedChannelReader(1, Token)); + case "ToChannel(target)": + { + var channel = Channel.CreateUnbounded(); + ValueTask pass = query.ToChannel(channel, true, Token); + return async () => + { + long count = await pass; + await Drain(channel.Reader)(); + return count; + }; + } + case "ToChannelHoldingConnection": + { + var channel = Channel.CreateUnbounded(); + ValueTask pass = query.ToChannelHoldingConnection( + channel, + forever, + Token); + return async () => await pass; + } + case "AsSourceBlock": + { + IReceivableSourceBlock block = query.AsSourceBlock(Token); + return async () => + { + long count = 0; + while (await block.OutputAvailableAsync(Token)) + { + while (block.TryReceive(out _)) ++count; + } + + await block.Completion; + return count; + }; + } + case "ToTargetBlock": + { + var block = new BufferBlock(); + ValueTask pass = query.ToTargetBlock(block, Token); + return async () => await pass; + } + default: + { + var block = new BufferBlock(); + ValueTask pass = query.ToTargetBlockHoldingConnection( + block, + forever, + Token); + return async () => await pass; + } + } + + static Func> Drain(ChannelReader reader) + => async () => + { + long count = 0; + await foreach (Row _ in reader.ReadAllAsync(Token)) ++count; + return count; + }; + } + + [Fact] + public static async Task AClosedChannel_RunsNothing_AndSaysSo() + { + var c = new CaptureConnection(("total", 9)); + var channel = Channel.CreateUnbounded(); + channel.Writer.Complete(); + + long count = await Query(c, out DbCapture total) + .ToChannel(channel, Token); + + Assert.Equal(0, count); + Assert.Equal(0, c.Executed); + Contains( + await Assert.ThrowsAsync( + async () => await total), + "the query never ran", + "its target closed"); + } + + [Fact] + public static async Task AFinishedBlock_RunsNothing_AndSaysSo() + { + var c = new CaptureConnection(("total", 9)); + var block = new BufferBlock(); + block.Complete(); + + // A block finishes after Complete, on its own scheduler. + await block.Completion; + + long count = await Query(c, out DbCapture total) + .ToTargetBlock(block, Token); + + Assert.Equal(0, count); + Assert.Equal(0, c.Executed); + Contains( + await Assert.ThrowsAsync( + async () => await total), + "the query never ran"); + } + + [Fact] + public static async Task AFullChannel_HoldsTheRun_WithTheCaptureArmed() + { + var c = new CaptureConnection(("total", 9)); + var channel = Channel.CreateBounded(1); + Assert.True(channel.Writer.TryWrite(new Row(0))); + + ValueTask pass = Query(c, out DbCapture total) + .ToChannel(channel, true, Token); + + Assert.False(total.AsTask().IsCompleted); + Assert.Equal(0, c.Executed); + + int read = 0; + await foreach (Row _ in channel.Reader.ReadAllAsync(Token)) ++read; + + Assert.Equal(3, await pass); + Assert.Equal(4, read); + Assert.Equal(9, await total); + } + + // A cancel while the feed waits for room: nothing ran, and the capture + // is canceled with the call. + [Fact] + public static async Task AFullChannel_CanceledWhileItWaits_CancelsIt() + { + var c = new CaptureConnection(("total", 9)); + var channel = Channel.CreateBounded(1); + Assert.True(channel.Writer.TryWrite(new Row(0))); + using var stop = new CancellationTokenSource(); + + ValueTask pass = Query(c, out DbCapture total) + .ToChannel(channel, true, stop.Token); + await stop.CancelAsync(); + + await Assert.ThrowsAnyAsync( + async () => await pass); + await Assert.ThrowsAnyAsync( + async () => await total); + Assert.Equal(0, c.Executed); + } + + // A target that closes after the first row: the feed stops and disposes + // the stream, and the captured run stops at its next chunk and delivers. + [Theory] + [InlineData(true)] + [InlineData(false)] + public static async Task ATargetClosedAfterTheFirstRow_StillDelivers( + bool channel) + { + const int rows = 200_000; + var c = new CaptureConnection(("total", 9)) { Rows = rows }; + MappedQuery query = Query(c, out DbCapture total); + long count; + + if (channel) + { + var target = Channel.CreateBounded(1); + ValueTask pass = query.ToChannel(target, false, Token); + await target.Reader.ReadAsync(Token); + target.Writer.Complete(); + count = await pass; + } + else + { + var target = new BufferBlock(new() { BoundedCapacity = 1 }); + ValueTask pass = query.ToTargetBlock(target, false, Token); + await target.ReceiveAsync(Token); + target.Complete(); + count = await pass; + } + + Assert.InRange(count, 1, rows - 1); + Assert.Equal(9, await total); + } + + // The stall signal is seen through the capture's wrapper: the channel + // made no room in time, and the capture has the same timeout. + [Fact] + public static async Task AFullChannel_PastTheStallTimeout_FaultsIt() + { + // More rows than the channel and the stream hold: the read stalls. + var c = new CaptureConnection(("total", 9)) { Rows = 50 }; + MappedQuery query = Query(c, out DbCapture total); + + await Assert.ThrowsAsync( + async () => await query.ToChannelHoldingConnection( + Channel.CreateBounded(1), + TimeSpan.FromMilliseconds(100), + Token)); + await Assert.ThrowsAsync(async () => await total); + } + + // A canceled token throws at the call, before the stream exists: nothing + // is armed, and awaiting the capture throws instead of waiting. + [Fact] + public static async Task ACanceledToken_ThrowsAtTheCall_AndArmsNothing() + { + var c = new CaptureConnection(("total", 9)); + using var canceled = new CancellationTokenSource(); + await canceled.CancelAsync(); + + MappedQuery toChannel = Query(c, out DbCapture first); + MappedQuery toBlock = Query(c, out DbCapture second); + + Assert.Throws( + () => toChannel.ToChannelReader(canceled.Token)); + Assert.Throws( + () => toBlock.AsSourceBlock(canceled.Token)); + + foreach (DbCapture capture in (DbCapture[])[first, second]) + { + Contains( + Assert.Throws( + () => { _ = capture.AsTask(); }), + "has not started"); + } + + Assert.Equal(0, c.Executed); + } + + // ---- 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. + sealed class OwnReaderCommand(CaptureConnection connection) + : ExpressiveCommand( + () => connection, + CommandType.StoredProcedure, + "p"), + IExecuteReader + { + public int OwnReads { get; private set; } + + async ValueTask + IExecuteReader.ExecuteReaderAsync( + TState state, + Func> transform, + CommandBehavior behavior, + CancellationToken cancellationToken) + { + OwnReads++; + using var table = new DataTable(); + table.Columns.Add("Id", typeof(int)); + table.Rows.Add(1); + await using DataTableReader reader = table.CreateDataReader(); + return await transform(reader, state); + } + } + + [Fact] + public static async Task ACommandThatReimplementsItsReader_StillFillsIt() + { + var c = new CaptureConnection(("total", 9)); + var command = new OwnReaderCommand(c); + + List rows = await command.CaptureOutput( + "total", + out DbCapture total) + .Map() + .ToListAsync(Token); + + Assert.Equal(3, rows.Count); + Assert.Equal(9, await total); + Assert.Equal(0, command.OwnReads); + + // 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); + } + + [Fact] + public static async Task ACommandThatReimplementsItsReader_OnAQueryCapture() + { + var c = new CaptureConnection(("total", 9)); + var command = new OwnReaderCommand(c); + + List rows = await command.Map() + .CaptureOutput("total", out DbCapture total) + .ToListAsync(Token); + + Assert.Equal(3, rows.Count); + Assert.Equal(9, await total); + Assert.Equal(0, command.OwnReads); + } + + // The synchronous path is refused before its own reader is asked. + [Fact] + public static void ACommandThatReimplementsItsReader_RefusesSync() + { + var c = new CaptureConnection(("total", 9)); + var command = new OwnReaderCommand(c); + MappedQuery query = command.Map() + .CaptureOutput("total", out DbCapture total); + + Contains( + Assert.Throws(() => query.ToList()), + "captures only work with async terminals"); + Assert.Equal(0, command.OwnReads); + Assert.Equal(0, c.Executed); + Contains( + Assert.Throws( + () => { _ = total.AsTask(); }), + "has not started"); + } + + // ---- an argument guard ----------------------------------------------- + + // The guard throws before anything is armed (decision 9): the capture + // was never started, so awaiting it throws instead of waiting forever. + [Fact] + public static void ANullTransform_ThrowsBeforeArming() + { + var c = new CaptureConnection(("total", 9)); + var command = c.StoredProcedure("p") + .CaptureOutput("total", out DbCapture total); + + Assert.Throws( + () => ((IExecuteReader)command).ExecuteReaderAsync( + 0, + null!, + CommandBehavior.Default, + Token)); + + Contains( + Assert.Throws(() => total.GetAwaiter()), + "has not started"); + Assert.Equal(0, c.Executed); + } +} diff --git a/Tests/Open.Database.Extensions.Core.Tests/CaptureTests.cs b/Tests/Open.Database.Extensions.Core.Tests/CaptureTests.cs index e39109f1..470356f1 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/CaptureTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/CaptureTests.cs @@ -1,4 +1,3 @@ -using Open.Database.Extensions.Benchmarks; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Common; @@ -28,151 +27,6 @@ public sealed record Touched(int Count, int ReturnValue); public sealed record Money( [property: Column(TypeName = "decimal(10,2)")] decimal Total); - // ---- the provider ---------------------------------------------------- - - sealed class CaptureConnection( - params (string Name, object? Value)[] outputs) - : DbConnection - { - public CaptureCommand? Last { get; private set; } - - public int Executed { get; set; } - - public int Rows { get; set; } = 3; - - // When set, an async execution waits for it before it runs. - public TaskCompletionSource? Gate { get; set; } - - public (string Name, object? Value)[] Outputs { get; } = outputs; - - [AllowNull] - public override string ConnectionString { get; set; } = "capture"; - public override string Database => "capture"; - public override string DataSource => "capture"; - public override string ServerVersion => "1.0"; - public override ConnectionState State => ConnectionState.Open; - public override void ChangeDatabase(string databaseName) { } - public override void Close() { } - public override void Open() { } - - protected override DbTransaction BeginDbTransaction( - IsolationLevel isolationLevel) - => throw new NotSupportedException(); - - protected override DbCommand CreateDbCommand() - => Last = new CaptureCommand(this); - } - - sealed class CaptureCommand(CaptureConnection connection) : DbCommand - { - readonly BenchParameterCollection _parameters = []; - - public IReadOnlyList All - => [.. _parameters.Cast()]; - - public DbParameter Named(string name) - => All.Single(p => p.ParameterName == name); - - [AllowNull] - public override string CommandText { get; set; } = ""; - public override int CommandTimeout { get; set; } - public override CommandType CommandType { get; set; } - public override bool DesignTimeVisible { get; set; } - public override UpdateRowSource UpdatedRowSource { get; set; } - - protected override DbConnection? DbConnection - { - get => connection; - set { } - } - - protected override DbParameterCollection DbParameterCollection - => _parameters; - - protected override DbTransaction? DbTransaction { get; set; } - public override void Cancel() { } - public override void Prepare() { } - - protected override DbParameter CreateDbParameter() - => new CaptureParameter(); - - public override int ExecuteNonQuery() - { - Run(); - return 1; - } - - public override object? ExecuteScalar() - { - Run(); - return 1; - } - - protected override DbDataReader ExecuteDbDataReader( - CommandBehavior behavior) - { - Run(); - var table = new DataTable(); - table.Columns.Add("Id", typeof(int)); - for (int i = 1; i <= connection.Rows; i++) table.Rows.Add(i); - return table.CreateDataReader(); - } - - protected override async Task ExecuteDbDataReaderAsync( - CommandBehavior behavior, - CancellationToken cancellationToken) - { - if (connection.Gate is { } gate) await gate.Task; - return ExecuteDbDataReader(behavior); - } - - public override async Task ExecuteNonQueryAsync( - CancellationToken cancellationToken) - { - if (connection.Gate is { } gate) await gate.Task; - return ExecuteNonQuery(); - } - - // Sets every output (and the return value, under "") from the values - // the connection was given, by name. - void Run() - { - connection.Executed++; - foreach (DbParameter p in All) - { - if (p.Direction == ParameterDirection.Input) continue; - - string key = p.Direction == ParameterDirection.ReturnValue - ? "" - : p.ParameterName; - foreach ((string name, object? value) in connection.Outputs) - { - if (name == key) p.Value = value; - } - } - } - } - - sealed class CaptureParameter : DbParameter - { - public override DbType DbType { get; set; } - - public override ParameterDirection Direction { get; set; } - = ParameterDirection.Input; - - public override bool IsNullable { get; set; } - [AllowNull] - public override string ParameterName { get; set; } = ""; - public override int Size { get; set; } - public override byte Precision { get; set; } - public override byte Scale { get; set; } - [AllowNull] - public override string SourceColumn { get; set; } = ""; - public override bool SourceColumnNullMapping { get; set; } - public override object? Value { get; set; } - public override void ResetDbType() { } - } - static void Contains(Exception ex, params string[] phrases) { foreach (string phrase in phrases) Assert.Contains(phrase, ex.Message); diff --git a/Tests/Open.Database.Extensions.Core.Tests/TestHelpers/CaptureProvider.cs b/Tests/Open.Database.Extensions.Core.Tests/TestHelpers/CaptureProvider.cs new file mode 100644 index 00000000..93f8f010 --- /dev/null +++ b/Tests/Open.Database.Extensions.Core.Tests/TestHelpers/CaptureProvider.cs @@ -0,0 +1,164 @@ +using Open.Database.Extensions.Benchmarks; +using System.Data.Common; + +#nullable enable + +namespace Open.Database.Extensions.Tests; + +// The provider of the capture tests: it records its parameters, fills the +// outputs when it executes, can hold an async execution at a gate, and can +// fail its execution. +internal sealed class CaptureConnection( + params (string Name, object? Value)[] outputs) + : DbConnection +{ + public CaptureCommand? Last { get; private set; } + + public int Executed { get; set; } + + public int Rows { get; set; } = 3; + + // When set, every execution throws it, after counting. + public Exception? Fault { get; set; } + + // When set, an async execution waits for it before it runs. + public TaskCompletionSource? Gate { get; set; } + + public (string Name, object? Value)[] Outputs { get; } = outputs; + + [AllowNull] + public override string ConnectionString { get; set; } = "capture"; + public override string Database => "capture"; + public override string DataSource => "capture"; + public override string ServerVersion => "1.0"; + public override ConnectionState State => ConnectionState.Open; + public override void ChangeDatabase(string databaseName) { } + public override void Close() { } + public override void Open() { } + + protected override DbTransaction BeginDbTransaction( + IsolationLevel isolationLevel) + => throw new NotSupportedException(); + + protected override DbCommand CreateDbCommand() + => Last = new CaptureCommand(this); +} + +internal sealed class CaptureCommand(CaptureConnection connection) : DbCommand +{ + readonly BenchParameterCollection _parameters = []; + + public IReadOnlyList All + => [.. _parameters.Cast()]; + + public DbParameter Named(string name) + => All.Single(p => p.ParameterName == name); + + [AllowNull] + public override string CommandText { get; set; } = ""; + public override int CommandTimeout { get; set; } + public override CommandType CommandType { get; set; } + public override bool DesignTimeVisible { get; set; } + public override UpdateRowSource UpdatedRowSource { get; set; } + + protected override DbConnection? DbConnection + { + get => connection; + set { } + } + + protected override DbParameterCollection DbParameterCollection + => _parameters; + + protected override DbTransaction? DbTransaction { get; set; } + public override void Cancel() { } + public override void Prepare() { } + + protected override DbParameter CreateDbParameter() + => new CaptureParameter(); + + public override int ExecuteNonQuery() + { + Run(); + return 1; + } + + public override object? ExecuteScalar() + { + Run(); + return 1; + } + + protected override DbDataReader ExecuteDbDataReader( + CommandBehavior behavior) + { + Run(); + var table = new DataTable(); + table.Columns.Add("Id", typeof(int)); + for (int i = 1; i <= connection.Rows; i++) table.Rows.Add(i); + return table.CreateDataReader(); + } + + protected override async Task ExecuteDbDataReaderAsync( + CommandBehavior behavior, + CancellationToken cancellationToken) + { + if (connection.Gate is { } gate) + { + await gate.Task.WaitAsync(cancellationToken); + } + return ExecuteDbDataReader(behavior); + } + + public override async Task ExecuteNonQueryAsync( + CancellationToken cancellationToken) + { + if (connection.Gate is { } gate) + { + await gate.Task.WaitAsync(cancellationToken); + } + return ExecuteNonQuery(); + } + + // Sets every output (and the return value, under "") from the values + // the connection was given, by name. + void Run() + { + connection.Executed++; + if (connection.Fault is { } fault) throw fault; + + foreach (DbParameter p in All) + { + if (p.Direction == ParameterDirection.Input) continue; + + string key = p.Direction == ParameterDirection.ReturnValue + ? "" + : p.ParameterName; + foreach ((string name, object? value) in connection.Outputs) + { + if (name == key) p.Value = value; + } + } + } +} + +internal sealed class CaptureParameter : DbParameter +{ + public override DbType DbType { get; set; } + + public override ParameterDirection Direction { get; set; } + = ParameterDirection.Input; + + public override bool IsNullable { get; set; } + [AllowNull] + public override string ParameterName { get; set; } = ""; + public override int Size { get; set; } + public override byte Precision { get; set; } + public override byte Scale { get; set; } + [AllowNull] + public override string SourceColumn { get; set; } = ""; + public override bool SourceColumnNullMapping { get; set; } + public override object? Value { get; set; } + public override void ResetDbType() { } +} + From 59fb812cd41cb367c30c252dd0668d59b076dd20 Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Wed, 2 Dec 2026 07:16:14 -0800 Subject: [PATCH 17/20] Captures: fixes from the C1 review, and tests for the decided cases A null transform passed to ExecuteScalarAsync now faults the task without arming the command's capture, so the capture says it has not started instead of being faulted. This follows the rule that every exit completes every armed capture, while argument, layout and shape guards arm nothing. The helper that faulted the capture for that guard is gone. The Channel and Dataflow pumps open their stream without an async frame: when the channel has room, or the block is open, the enumerator comes back in a completed task with nothing allocated. When the channel wait fails, a failure to dispose the unread stream no longer replaces the wait's exception, so a cancel stays a cancel. The message for a capture on a query from a DbQuery definition now says what to do, without naming a release. Repeated comments are cut, the comment on an early stop names how the outputs arrive (the provider's close of the reader drains the response), and the byte order mark of ExpressiveDbCommandBase.cs is back. The docs now say that an early stop waits for the server to finish sending, which the stall timeout does not bound, and that FirstAsync or SingleAsync with no rows still fills the capture. New tests: a SingleResult() read on LocalDB (one row asked for, no read-through) delivers the output; FirstAsync and SingleAsync with no rows throw and still fill the capture; AnyAsync and CountAsync on a command fill its capture and give the command's second-run message; a null transform and a bad ExecuteOutputAsync argument arm nothing; a capture added to the command after Map() is filled; a pooled buffer whose scheduler refuses the start faults its capture; a canceled channel wait is not replaced by a failed dispose; ToBoundedChannel arms at the call; CaptureOutput without a precision and scale is refused at the call. The pooled buffer test now disposes after the first chunk, the unobserved-fault test has a positive control, and the null-transform test awaits its ValueTask (CA2012). Co-Authored-By: Claude Opus 5.5 --- Source/Channel/ChannelPump.cs | 54 +++++- Source/Core/Capture.cs | 15 +- Source/Core/CapturedStream.cs | 1 - Source/Core/DbCapture.cs | 5 - Source/Core/ExpressiveCommandBase.Capture.cs | 23 +-- Source/Core/ExpressiveCommandBase.Output.cs | 2 - Source/Core/ExpressiveDbCommandBase.cs | 18 +- Source/Core/Output.docs.xml | 4 + Source/Dataflow/BlockPump.cs | 12 +- .../CaptureLocalDbTests.cs | 23 +++ .../CaptureStreamTests.cs | 117 +++++++++++- .../CaptureTests.cs | 170 +++++++++++++++++- 12 files changed, 379 insertions(+), 65 deletions(-) diff --git a/Source/Channel/ChannelPump.cs b/Source/Channel/ChannelPump.cs index e4c390d5..af392b19 100644 --- a/Source/Channel/ChannelPump.cs +++ b/Source/Channel/ChannelPump.cs @@ -65,29 +65,69 @@ internal static async ValueTask Run( /// The enumerator, or when the writer was closed /// before the first row (the enumerator is disposed: nothing read). /// - internal static async ValueTask?> Open( + // Not async: with room now, it returns the enumerator with no frame and + // nothing allocated. Only a wait, a closed writer or a failure goes on. + internal static ValueTask?> Open( IAsyncEnumerable stream, ChannelWriter writer, CancellationToken cancellationToken) { IAsyncEnumerator rows = stream.GetAsyncEnumerator(cancellationToken); - bool room = false; + ValueTask wait; try { - room = await writer.WaitToWriteAsync(cancellationToken) - .ConfigureAwait(false); + wait = writer.WaitToWriteAsync(cancellationToken); } - finally + catch (Exception ex) + { + return OpenAsync(rows, new(Task.FromException(ex))); + } + + if (!wait.IsCompletedSuccessfully) return OpenAsync(rows, wait); + + return wait.Result + ? new(rows) + : CloseAsync(rows); + } + + static async ValueTask?> OpenAsync( + IAsyncEnumerator rows, + ValueTask wait) + { + bool room; + try { - if (!room) + room = await wait.ConfigureAwait(false); + } + catch + { + try { await rows.DisposeAsync() .ConfigureAwait(false); } + catch + { + // The wait's exception is the one the pass reports (a cancel + // stays a cancel): a failed dispose must not replace it. + } + + throw; } - return room ? rows : null; + return room + ? rows + : await CloseAsync(rows) + .ConfigureAwait(false); + } + + static async ValueTask?> CloseAsync( + IAsyncEnumerator rows) + { + await rows.DisposeAsync() + .ConfigureAwait(false); + return null; } /// diff --git a/Source/Core/Capture.cs b/Source/Core/Capture.cs index 57f95cfa..98e8d8fe 100644 --- a/Source/Core/Capture.cs +++ b/Source/Core/Capture.cs @@ -509,17 +509,7 @@ public override Exception Refuse( /// a command that is not a stored procedure. /// The exception. public InvalidOperationException NotProcedure() - { - foreach (ICaptureSource source in Sources) - { - if (source.ReadsReturn) - { - return new(CaptureMessages.NotProcedure(source)); - } - } - - return new(CaptureMessages.NotProcedure(Sources[0])); - } + => new(CaptureMessages.NotProcedure(ReturnReader!)); /// Gets the capture that reads the return code, or /// . @@ -982,8 +972,7 @@ public static string ReturnModel(string type) public static string NotFromDefinition(ICaptureSource source) => $"{source.Display} needs a query built from an expressive command " + "(connection.Command(…).Map()); " - + "a query from a DbQuery definition gets captures in a later release " - + "candidate. " + + "a query from a DbQuery definition cannot take a capture. " + "Build it from a command, " + "or read the outputs with ExecuteOutputAsync."; diff --git a/Source/Core/CapturedStream.cs b/Source/Core/CapturedStream.cs index e9e3e922..c13e3004 100644 --- a/Source/Core/CapturedStream.cs +++ b/Source/Core/CapturedStream.cs @@ -108,7 +108,6 @@ public async ValueTask DisposeAsync() { if (Interlocked.Exchange(ref _disposed, 1) != 0) return; - // Stopped before the end, by the consumer: the run delivers. if (!_ended && _error is null && !run.OwnerCanceled) run.ConsumerStopped = true; diff --git a/Source/Core/DbCapture.cs b/Source/Core/DbCapture.cs index a2237a32..5383433b 100644 --- a/Source/Core/DbCapture.cs +++ b/Source/Core/DbCapture.cs @@ -22,7 +22,6 @@ public readonly struct DbCapture internal DbCapture(CaptureSource source) => Source = source; - // Null in a default value, which every member refuses. CaptureSource Source => field ?? throw Unassigned(); @@ -162,10 +161,6 @@ public ConfiguredAwaiter GetAwaiter() /// /// The awaiter of . /// - /// - /// throws while the capture is not complete, - /// instead of blocking. - /// public readonly struct ConfiguredAwaiter : ICriticalNotifyCompletion { readonly CaptureSource? _source; diff --git a/Source/Core/ExpressiveCommandBase.Capture.cs b/Source/Core/ExpressiveCommandBase.Capture.cs index 4afd3c58..76ddd539 100644 --- a/Source/Core/ExpressiveCommandBase.Capture.cs +++ b/Source/Core/ExpressiveCommandBase.Capture.cs @@ -297,10 +297,11 @@ static async ValueTask InvokeAsync( catch (OperationCanceledException) when (call._run.StoppedByConsumer) { - // The consumer stopped early (a break, a dispose): the reader - // is closed, and closing it read the rest of the response, the - // outputs included. The stream's own stop is not the caller's - // failure. + // The consumer stopped early (a break, a dispose), so no + // read-through ran: the outputs are there because the + // provider's close of the reader drained the rest of the + // response (SqlClient does). The stream's own stop is not + // the caller's failure. call._run.Deliver(call); throw; } @@ -350,18 +351,4 @@ void ThrowIfCanceled(CancellationToken callToken) throw exception; } - - /// - /// Makes the exception of a missing argument of an asynchronous terminal; a - /// capture on the command is faulted with it. - /// - /// The argument's name. - /// The exception, to throw. - private protected Exception NullArgument(string name) - { - var exception = new ArgumentNullException(name); - return _captures is { } captures - ? captures.Refuse(exception) - : exception; - } } diff --git a/Source/Core/ExpressiveCommandBase.Output.cs b/Source/Core/ExpressiveCommandBase.Output.cs index fbec6c23..fa7b5fae 100644 --- a/Source/Core/ExpressiveCommandBase.Output.cs +++ b/Source/Core/ExpressiveCommandBase.Output.cs @@ -69,8 +69,6 @@ public ValueTask ExecuteOutputAsync( OutputLayout layout = OutputLayout.Get(); if (layout.HasReturnValue) ThrowUnlessProcedure(layout); - // Before the cancel: a capture on the command is completed by the - // refusal. RefuseBesideCaptures($"ExecuteOutputAsync<{layout.Model}>()"); // Thrown synchronously, not through the returned task. diff --git a/Source/Core/ExpressiveDbCommandBase.cs b/Source/Core/ExpressiveDbCommandBase.cs index 11389fa0..ed2103cc 100644 --- a/Source/Core/ExpressiveDbCommandBase.cs +++ b/Source/Core/ExpressiveDbCommandBase.cs @@ -1,4 +1,4 @@ -namespace Open.Database.Extensions; +namespace Open.Database.Extensions; /// /// Represents the base class of the expressive commands that execute on a @@ -180,8 +180,12 @@ public async ValueTask ExecuteScalarAsync( Func transform, CancellationToken cancellationToken = default) { - // A capture on the command is faulted with it. - if (transform is null) throw NullArgument(nameof(transform)); + // Before the claim: a capture on the command is not armed, and says + // it has not started. + if (transform is null) + { + throw new ArgumentNullException(nameof(transform)); + } Contract.EndContractBlock(); return transform( @@ -222,8 +226,12 @@ public async ValueTask ExecuteScalarAsync( Func> transform, CancellationToken cancellationToken = default) { - // A capture on the command is faulted with it. - if (transform is null) throw NullArgument(nameof(transform)); + // Before the claim: a capture on the command is not armed, and says + // it has not started. + if (transform is null) + { + throw new ArgumentNullException(nameof(transform)); + } Contract.EndContractBlock(); return await transform( diff --git a/Source/Core/Output.docs.xml b/Source/Core/Output.docs.xml index c22f8a1e..9c57c81f 100644 --- a/Source/Core/Output.docs.xml +++ b/Source/Core/Output.docs.xml @@ -228,6 +228,8 @@ The capture belongs to the copy, which also shares any capture on its command, and 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. A query that carries a capture runs once, with an async terminal only: @@ -252,6 +254,8 @@ It completes once, with the run: with the value; faulted with the run's error or the conversion's (the terminal's own result is unaffected by a conversion error); canceled when the caller's token is; or faulted when the outputs were not delivered (the response did not complete). + A terminal that throws after a complete run, such as FirstAsync or SingleAsync with no rows, + still fills it: the outputs were read before the terminal threw. A fault that only the capture carries (a conversion, outputs not delivered) is reported only there: a capture that is never awaited leaves it unobserved. diff --git a/Source/Dataflow/BlockPump.cs b/Source/Dataflow/BlockPump.cs index 768066e3..bc58da44 100644 --- a/Source/Dataflow/BlockPump.cs +++ b/Source/Dataflow/BlockPump.cs @@ -71,15 +71,23 @@ internal static async ValueTask Run( /// The enumerator, or when the block is already /// finished (the enumerator is disposed: nothing read). /// - internal static async ValueTask?> Open( + // Not async: an open block gets the enumerator with no frame and nothing + // allocated. Only a finished block goes on, to dispose the enumerator. + internal static ValueTask?> Open( IAsyncEnumerable stream, ITargetBlock target, CancellationToken cancellationToken) { IAsyncEnumerator rows = stream.GetAsyncEnumerator(cancellationToken); - if (!target.Completion.IsCompleted) return rows; + return target.Completion.IsCompleted + ? CloseAsync(rows) + : new(rows); + } + static async ValueTask?> CloseAsync( + IAsyncEnumerator rows) + { await rows.DisposeAsync() .ConfigureAwait(false); return null; diff --git a/Tests/Open.Database.Extensions.Core.Tests/CaptureLocalDbTests.cs b/Tests/Open.Database.Extensions.Core.Tests/CaptureLocalDbTests.cs index 915aece7..a8fed985 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/CaptureLocalDbTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/CaptureLocalDbTests.cs @@ -62,6 +62,29 @@ public static async Task TheRows_AnOutput_AndTheReturnCode() Assert.Equal(7, await code); } + // SingleResult() asks the provider for one row (CommandBehavior.SingleRow) + // and skips the read-through: closing the reader still brings the output. + [Fact] + public static async Task ASingleRowRead_StillDelivers() + { + LocalDbFixture.SkipUnlessAvailable(); + using LocalDbFixture.Scratch procedure = Procedure( + "@total int output", + "select n as Id from (values (1), (2), (3)) v(n);" + + " set @total = 3;"); + await using SqlConnection connection = await OpenAsync(); + string name = "dbo." + procedure.Name; + + Row? row = await connection.StoredProcedure(name) + .Map() + .SingleResult() + .CaptureOutput("total", out DbCapture total) + .FirstOrDefaultAsync(Token); + + Assert.Equal(new Row(1), row); + Assert.Equal(3, await total); + } + // The real drain: the outputs are sent after every row, so they arrive // only when closing the reader reads the rows nobody asked for. [Theory] diff --git a/Tests/Open.Database.Extensions.Core.Tests/CaptureStreamTests.cs b/Tests/Open.Database.Extensions.Core.Tests/CaptureStreamTests.cs index e97cc7a4..1724fbad 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/CaptureStreamTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/CaptureStreamTests.cs @@ -160,11 +160,56 @@ public static async Task APooledBufferDisposedMidRead_StillDelivers() var c = new CaptureConnection(("total", 9)) { Rows = 200_000 }; MappedQuery query = Query(c, out DbCapture total); - query.ToPooledBuffer(Token) - .Dispose(); + // Disposed once the first chunk has arrived: the read has started. + PooledBuffer buffer = query.ToPooledBuffer(Token); + await using (IAsyncEnumerator e = buffer.AsAsyncEnumerable(Token) + .GetAsyncEnumerator(Token)) + { + Assert.True(await e.MoveNextAsync()); + } + + buffer.Dispose(); // Stopped at a chunk, or read to the end: the outputs either way. Assert.Equal(9, await total); + Assert.Equal(1, c.Executed); + } + + // The buffer's read starts on the ambient scheduler: one that refuses + // the start leaves nothing running, and the capture faults with the + // call's exception instead of waiting. + [Fact] + public static void APooledBuffer_WhoseSchedulerRefusesTheStart_FaultsIt() + { + var c = new CaptureConnection(("total", 9)); + MappedQuery query = Query(c, out DbCapture total); + + Exception? thrown = null; + var call = new Task(() => thrown = Record.Exception( + () => query.ToPooledBuffer(Token))); + call.RunSynchronously(new RefusingScheduler()); + + Assert.IsType(thrown); + Task task = total.AsTask(); + Assert.True(task.IsFaulted); + Assert.Same(thrown, task.Exception!.InnerException); + Assert.Equal(0, c.Executed); + } + + // Runs a task inline, and refuses to queue one. + sealed class RefusingScheduler : TaskScheduler + { + protected override void QueueTask(Task task) + => throw new InvalidOperationException( + "This scheduler queues nothing."); + + protected override bool TryExecuteTaskInline( + Task task, + bool taskWasPreviouslyQueued) + => TryExecuteTask(task); + + protected override IEnumerable GetScheduledTasks() + => []; } [Fact] @@ -193,6 +238,7 @@ public static TheoryData Entries "ToChannelReader", "ToChannel", "ToBoundedChannelReader", + "ToBoundedChannel", "ToChannel(target)", "ToChannelHoldingConnection", "AsSourceBlock", @@ -236,6 +282,8 @@ static Func> Start(MappedQuery query, string entry) return Drain(query.ToChannel(Token).Reader); case "ToBoundedChannelReader": return Drain(query.ToBoundedChannelReader(1, Token)); + case "ToBoundedChannel": + return Drain(query.ToBoundedChannel(1, Token).Reader); case "ToChannel(target)": { var channel = Channel.CreateUnbounded(); @@ -379,6 +427,64 @@ await Assert.ThrowsAnyAsync( Assert.Equal(0, c.Executed); } + // The cancel of the wait is what the pass reports, even when disposing + // the unread stream fails too. + [Fact] + public static async Task ACanceledWait_IsNotReplacedByAFailedDispose() + { + var channel = Channel.CreateBounded(1); + Assert.True(channel.Writer.TryWrite(new Row(0))); + using var stop = new CancellationTokenSource(); + var source = new DisposeFails(); + + ValueTask pass = source.ToChannel(channel, true, stop.Token); + await stop.CancelAsync(); + + await Assert.ThrowsAnyAsync( + async () => await pass); + } + + // A source whose one stream has no rows and fails to dispose. + sealed class DisposeFails + : IMappedQuery, + IAsyncEnumerable>, + IAsyncEnumerator> + { + public ReadOnlyMemory Current + => default; + + public IAsyncEnumerable> ToPooledBufferStream( + CancellationToken cancellationToken = default) + => this; + + public IAsyncEnumerator> GetAsyncEnumerator( + CancellationToken cancellationToken = default) + => this; + + public ValueTask MoveNextAsync() + => new(false); + + public ValueTask DisposeAsync() + => ValueTask.FromException( + new InvalidOperationException("The dispose failed.")); + + public IAsyncEnumerable Stream( + TimeSpan stallTimeout, + CancellationToken cancellationToken = default) + => throw new NotSupportedException(); + + public IAsyncEnumerable StreamBuffered( + TimeSpan stallTimeout, + CancellationToken cancellationToken = default) + => throw new NotSupportedException(); + + public IAsyncEnumerable StreamBuffered( + TimeSpan stallTimeout, + int bufferSize, + CancellationToken cancellationToken = default) + => throw new NotSupportedException(); + } + // A target that closes after the first row: the feed stops and disposes // the stream, and the captured run stops at its next chunk and delivers. [Theory] @@ -550,14 +656,15 @@ public static void ACommandThatReimplementsItsReader_RefusesSync() // The guard throws before anything is armed (decision 9): the capture // was never started, so awaiting it throws instead of waiting forever. [Fact] - public static void ANullTransform_ThrowsBeforeArming() + public static async Task ANullTransform_ThrowsBeforeArming() { var c = new CaptureConnection(("total", 9)); var command = c.StoredProcedure("p") .CaptureOutput("total", out DbCapture total); + var reader = (IExecuteReader)command; - Assert.Throws( - () => ((IExecuteReader)command).ExecuteReaderAsync( + await Assert.ThrowsAsync( + async () => await reader.ExecuteReaderAsync( 0, null!, CommandBehavior.Default, diff --git a/Tests/Open.Database.Extensions.Core.Tests/CaptureTests.cs b/Tests/Open.Database.Extensions.Core.Tests/CaptureTests.cs index 470356f1..08c81afc 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/CaptureTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/CaptureTests.cs @@ -149,6 +149,31 @@ public static async Task ACommandWithACapture_RunsOnce() Assert.Equal(1, c.Executed); } + // AnyAsync and CountAsync on a command run it as a query over it: they + // fill the command's capture, and a second run gets the command's message. + [Fact] + public static async Task AnyAsyncAndCountAsync_OnACommand_FillIt() + { + var c = new CaptureConnection(("total", 5)); + var any = c.StoredProcedure("p") + .CaptureOutput("total", out DbCapture first); + var count = c.StoredProcedure("p") + .CaptureOutput("total", out DbCapture second); + + Assert.True(await any.AnyAsync(Token)); + Assert.Equal(3, await count.CountAsync(Token)); + Assert.Equal(5, await first); + Assert.Equal(5, await second); + + var ex = await Assert.ThrowsAsync( + async () => await any.CountAsync(Token)); + Contains(ex, + "already used by an earlier run of this command", + "Build the command again, with a new capture"); + Assert.True(first.AsTask().IsCompletedSuccessfully); + Assert.Equal(2, c.Executed); + } + [Fact] public static void ASynchronousTerminal_Throws_AndArmsNothing() { @@ -207,6 +232,68 @@ await Assert.ThrowsAsync( Assert.Equal(0, c.Executed); } + // Its argument and shape guards throw at the call, before the refusal: + // nothing is armed, and the capture says it has not started. + [Fact] + public static async Task ExecuteOutputAsync_WithABadArgument_ArmsNothing() + { + var c = new CaptureConnection(("total", 5)); + var command = c.StoredProcedure("p") + .CaptureOutput(out DbCapture page); + + Contains( + await Assert.ThrowsAsync( + async () => await command.ExecuteOutputAsync( + "x", + 0, + 0, + Token)), + "Only a decimal output takes a precision and scale"); + Contains( + await Assert.ThrowsAsync( + async () => await command.ExecuteOutputAsync( + "x", + 0, + 0, + Token)), + "must be from 1 to 38"); + + Contains( + Assert.Throws( + () => { _ = page.AsTask(); }), + "has not started"); + Assert.Equal(0, c.Executed); + } + + // A guard inside an async method faults the task and arms nothing: the + // capture says it has not started, and never waits. + [Fact] + public static async Task ExecuteScalarAsync_WithANullTransform_ArmsNothing() + { + var c = new CaptureConnection(("total", 5)); + var command = c.StoredProcedure("p") + .CaptureOutput("total", out DbCapture total); + + await Assert.ThrowsAsync( + async () => await command.ExecuteScalarAsync( + (Func)null!, + Token)); + await Assert.ThrowsAsync( + async () => await command.ExecuteScalarAsync( + (Func>)null!, + Token)); + + Contains( + Assert.Throws( + () => { _ = total.AsTask(); }), + "has not started"); + Assert.Equal(0, c.Executed); + + // Still unused: a terminal runs it. + await command.ExecuteNonQueryAsync(Token); + Assert.Equal(5, await total); + } + [Fact] public static async Task ExecuteReturnAsync_BesideCaptureReturn_IsRefused() { @@ -321,6 +408,14 @@ public static void TheArguments_AreCheckedAtTheCall() Assert.Throws(() => c .StoredProcedure("p") .CaptureOutput("a", out DbCapture _)); + + // decimal? too: a decimal needs its precision and scale. + Contains( + Assert.Throws( + () => c.StoredProcedure("p") + .CaptureOutput("a", out DbCapture _)), + "A decimal output needs its precision and scale", + "CaptureOutputDecimal(\"a\", 19, 4, out …)"); Assert.Throws(() => c .StoredProcedure("p") .CaptureOutput(out DbCapture _)); @@ -344,6 +439,31 @@ public static async Task OnAQuery_TheTerminalFillsIt_BeforeItsTaskCompletes() Assert.Equal(9, await total); } + // "No rows" is thrown after a complete run: the capture holds its value. + [Fact] + public static async Task FirstAsyncAndSingleAsync_WithNoRows_StillFillIt() + { + var c = new CaptureConnection(("total", 9)) { Rows = 0 }; + MappedQuery first = c.StoredProcedure("p") + .Map() + .CaptureOutput("total", out DbCapture firstTotal); + MappedQuery single = c.StoredProcedure("p") + .Map() + .CaptureOutput("total", out DbCapture singleTotal); + + Contains( + await Assert.ThrowsAsync( + async () => await first.FirstAsync(Token)), + "the query returned no rows"); + Contains( + await Assert.ThrowsAsync( + async () => await single.SingleAsync(Token)), + "the query returned no rows"); + + Assert.Equal(9, await firstTotal); + Assert.Equal(9, await singleTotal); + } + [Fact] public static async Task TheSkipAndTakeViews_CarryIt() { @@ -394,6 +514,21 @@ await Assert.ThrowsAsync( Assert.Equal(1, c.Executed); } + // The query reads its command's captures when it runs, not when Map made + // it: a capture added to the command afterwards is filled too. + [Fact] + public static async Task ACaptureAddedToTheCommandAfterMap_IsFilled() + { + var c = new CaptureConnection(("total", 9)); + var command = c.StoredProcedure("p"); + MappedQuery query = command.Map(); + + _ = command.CaptureOutput("total", out DbCapture total); + + Assert.Equal(3, (await query.ToListAsync(Token)).Count); + Assert.Equal(9, await total); + } + [Fact] public static async Task AQueryWithACapture_RunsOnce() { @@ -490,7 +625,7 @@ public static void AQuery_ThatIsNotFromAnExpressiveCommand_RefusesIt() .Using(c) .Map() .CaptureOutput("total", out DbCapture _)), - "a query from a DbQuery definition gets captures in a later"); + "a query from a DbQuery definition cannot take a capture"); Contains( Assert.Throws(() => source .Map() @@ -631,30 +766,42 @@ public static async Task ACaptureFaultedWithTheTerminal_IsNotReportedUnobserved( // The terminal throws the same exception, so a capture that is never // awaited is not reported again when it is collected. const string marker = "cannot be used with CancelOnEarlyStop()"; + + // The positive control: a fault only the capture carries (a + // conversion) is reported, so the harness does see unobserved faults. + const string control = "unobserved_control"; int unobserved = 0; + int controls = 0; void OnUnobserved(object? sender, UnobservedTaskExceptionEventArgs e) { - if (e.Exception.ToString().Contains( - marker, - StringComparison.Ordinal)) + string text = e.Exception.ToString(); + if (text.Contains(marker, StringComparison.Ordinal)) { Interlocked.Increment(ref unobserved); } + if (text.Contains(control, StringComparison.Ordinal)) + { + Interlocked.Increment(ref controls); + } } TaskScheduler.UnobservedTaskException += OnUnobserved; try { await FaultWithoutAwaiting(); - GC.Collect(); - GC.WaitForPendingFinalizers(); - GC.Collect(); + await FaultOnlyTheCapture(control); + for (int i = 0; i < 10 && Volatile.Read(ref controls) == 0; i++) + { + GC.Collect(); + GC.WaitForPendingFinalizers(); + } } finally { TaskScheduler.UnobservedTaskException -= OnUnobserved; } + Assert.NotEqual(0, controls); Assert.Equal(0, unobserved); static async Task FaultWithoutAwaiting() @@ -669,6 +816,15 @@ await Assert.ThrowsAsync( async () => await query.ToListAsync(Token)); Assert.True(total.AsTask().IsFaulted); } + + static async Task FaultOnlyTheCapture(string name) + { + var c = new CaptureConnection((name, DBNull.Value)); + var command = c.StoredProcedure("p") + .CaptureOutput(name, 19, 4, out DbCapture v); + await command.ExecuteNonQueryAsync(Token); + Assert.True(v.AsTask().IsFaulted); + } } [Theory] From 89bb16ce7b3d6122150abc708d413b5d6db7531d Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Wed, 2 Dec 2026 07:30:00 -0800 Subject: [PATCH 18/20] Tests: the unobserved-fault check waits past its control The test stopped collecting as soon as the positive control was reported, so the capture it checks might not have been finalized yet and the test could pass without checking it. Two more collection rounds follow the control. Co-Authored-By: Claude Opus 5.5 --- .../CaptureTests.cs | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/Tests/Open.Database.Extensions.Core.Tests/CaptureTests.cs b/Tests/Open.Database.Extensions.Core.Tests/CaptureTests.cs index 08c81afc..743c37ee 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/CaptureTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/CaptureTests.cs @@ -792,9 +792,13 @@ void OnUnobserved(object? sender, UnobservedTaskExceptionEventArgs e) await FaultOnlyTheCapture(control); for (int i = 0; i < 10 && Volatile.Read(ref controls) == 0; i++) { - GC.Collect(); - GC.WaitForPendingFinalizers(); + Collect(); } + + // The control was finalized; two more rounds so the earlier + // task, if it were reported, would be too. + Collect(); + Collect(); } finally { @@ -804,6 +808,12 @@ void OnUnobserved(object? sender, UnobservedTaskExceptionEventArgs e) Assert.NotEqual(0, controls); Assert.Equal(0, unobserved); + static void Collect() + { + GC.Collect(); + GC.WaitForPendingFinalizers(); + } + static async Task FaultWithoutAwaiting() { var c = new CaptureConnection(); From fc64167e176cf4bc9f0d5144b5193fc7d2624c33 Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Wed, 2 Dec 2026 08:00:48 -0800 Subject: [PATCH 19/20] Channel and Dataflow pumps: owner review of PR 290, with tests Owner direction: the feeds dispose their enumerator with await using instead of a try/finally whose finally only disposes (ChunkFeed and RowFeed in ChannelPump and in BlockPump). The dispose still runs on every exit and an exception from it still replaces the loop's, as the finally did. The catch in ChannelPump.OpenAsync stays: it must not let a failed dispose replace the wait's exception. Owner direction: show by test that the wait for room belongs in ChannelPump.Open. For both Channel members, a full bounded channel opens no connection and runs no command until a row is taken (then the command runs once and every row arrives), and a channel that closes while full returns 0 with nothing opened. Dataflow has no wait for room; its tests pin the closed-at-call check for both feeds (completed and faulted: no command), that a full block still runs the command once and delivers every row, and that a block that completes while full still runs the command and returns 0, the documented difference from Channel. One test per stream class a pump can receive (ChunkStream, StallStream, and the capture wrapper over each): taking the enumerator and disposing it runs no command and opens no connection. A capture on a mapped query and on the skip view survives WithOptions. Co-Authored-By: Claude Sonnet 5.5 --- Source/Channel/ChannelPump.cs | 102 ++++++++---------- Source/Dataflow/BlockPump.cs | 94 +++++++--------- .../CaptureTests.cs | 25 +++++ .../PumpStreamOpenTests.cs | 85 +++++++++++++++ .../ToChannelStreamingTests.cs | 48 +++++++++ .../ToChannelTargetTests.cs | 44 ++++++++ .../ToTargetBlockStreamingTests.cs | 58 ++++++++++ .../ToTargetBlockTests.cs | 37 +++++++ 8 files changed, 383 insertions(+), 110 deletions(-) create mode 100644 Tests/Open.Database.Extensions.Core.Tests/PumpStreamOpenTests.cs diff --git a/Source/Channel/ChannelPump.cs b/Source/Channel/ChannelPump.cs index d2997950..ccd78bf7 100644 --- a/Source/Channel/ChannelPump.cs +++ b/Source/Channel/ChannelPump.cs @@ -184,41 +184,35 @@ public async ValueTask WriteAsync( .ConfigureAwait(false); if (chunked is null) return 0; - try + await using var _ = chunked.ConfigureAwait(false); + + long count = 0; + while (await chunked.MoveNextAsync() + .ConfigureAwait(false)) { - long count = 0; - while (await chunked.MoveNextAsync() - .ConfigureAwait(false)) + ReadOnlyMemory chunk = chunked.Current; + int i = 0; + while (true) { - ReadOnlyMemory chunk = chunked.Current; - int i = 0; - while (true) - { - int next = ChannelPump.TryWriteFrom(writer, chunk, i); - count += next - i; - i = next; - if (i == chunk.Length) break; + int next = ChannelPump.TryWriteFrom(writer, chunk, i); + count += next - i; + i = next; + if (i == chunk.Length) break; - // Full, or closed: wait for room, then write the same - // row. Leaving the loop disposes the stream, which - // cancels the query and releases every chunk (a query - // with a capture stops at its next chunk instead, and - // fills the capture). - if (!await writer.WaitToWriteAsync(cancellationToken) - .ConfigureAwait(false)) - { - return count; - } + // Full, or closed: wait for room, then write the same + // row. Leaving the loop disposes the stream, which + // cancels the query and releases every chunk (a query + // with a capture stops at its next chunk instead, and + // fills the capture). + if (!await writer.WaitToWriteAsync(cancellationToken) + .ConfigureAwait(false)) + { + return count; } } - - return count; - } - finally - { - await chunked.DisposeAsync() - .ConfigureAwait(false); } + + return count; } } @@ -255,40 +249,34 @@ public async ValueTask WriteAsync( .ConfigureAwait(false); if (pulled is null) return 0; - try + await using var _ = pulled.ConfigureAwait(false); + + long count = 0; + while (await pulled.MoveNextAsync() + .ConfigureAwait(false)) { - long count = 0; - while (await pulled.MoveNextAsync() - .ConfigureAwait(false)) + T row = pulled.Current; + while (!writer.TryWrite(row)) { - T row = pulled.Current; - while (!writer.TryWrite(row)) - { - // Without a link there is no signal that can fire: - // the plain wait, nothing created. - bool room = link is null - ? await writer.WaitToWriteAsync(cancellationToken) - .ConfigureAwait(false) - : await WaitAsync( - writer, - signal!, - wait, - cancellationToken) - .ConfigureAwait(false); - - if (!room) return count; - } + // Without a link there is no signal that can fire: + // the plain wait, nothing created. + bool room = link is null + ? await writer.WaitToWriteAsync(cancellationToken) + .ConfigureAwait(false) + : await WaitAsync( + writer, + signal!, + wait, + cancellationToken) + .ConfigureAwait(false); - ++count; + if (!room) return count; } - return count; - } - finally - { - await pulled.DisposeAsync() - .ConfigureAwait(false); + ++count; } + + return count; } static async ValueTask WaitAsync( diff --git a/Source/Dataflow/BlockPump.cs b/Source/Dataflow/BlockPump.cs index 4ce44dc1..a17a0e4b 100644 --- a/Source/Dataflow/BlockPump.cs +++ b/Source/Dataflow/BlockPump.cs @@ -129,39 +129,33 @@ public async ValueTask WriteAsync( .ConfigureAwait(false); if (chunked is null) return 0; - try + await using var _ = chunked.ConfigureAwait(false); + + long count = 0; + while (await chunked.MoveNextAsync() + .ConfigureAwait(false)) { - long count = 0; - while (await chunked.MoveNextAsync() - .ConfigureAwait(false)) + ReadOnlyMemory chunk = chunked.Current; + for (int i = 0; i < chunk.Length; ++i) { - ReadOnlyMemory chunk = chunked.Current; - for (int i = 0; i < chunk.Length; ++i) + // SendAsync waits while a bounded target is full; + // false means the target declined for good. + // Leaving the loop disposes the stream, which cancels + // the query and releases every chunk (a query with a + // capture stops at its next chunk instead, and fills + // the capture). + T row = chunk.Span[i]; + if (!await target.SendAsync(row, cancellationToken) + .ConfigureAwait(false)) { - // SendAsync waits while a bounded target is full; - // false means the target declined for good. - // Leaving the loop disposes the stream, which cancels - // the query and releases every chunk (a query with a - // capture stops at its next chunk instead, and fills - // the capture). - T row = chunk.Span[i]; - if (!await target.SendAsync(row, cancellationToken) - .ConfigureAwait(false)) - { - return count; - } - - ++count; + return count; } - } - return count; - } - finally - { - await chunked.DisposeAsync() - .ConfigureAwait(false); + ++count; + } } + + return count; } } @@ -197,35 +191,29 @@ public async ValueTask WriteAsync( .ConfigureAwait(false); if (pulled is null) return 0; - try - { - long count = 0; - while (await pulled.MoveNextAsync() - .ConfigureAwait(false)) - { - T row = pulled.Current; - bool accepted = link is null - ? await target.SendAsync(row, cancellationToken) - .ConfigureAwait(false) - : await SendAsync( - target, - row, - signal!, - wait, - cancellationToken) - .ConfigureAwait(false); - - if (!accepted) return count; - ++count; - } + await using var _ = pulled.ConfigureAwait(false); - return count; - } - finally + long count = 0; + while (await pulled.MoveNextAsync() + .ConfigureAwait(false)) { - await pulled.DisposeAsync() - .ConfigureAwait(false); + T row = pulled.Current; + bool accepted = link is null + ? await target.SendAsync(row, cancellationToken) + .ConfigureAwait(false) + : await SendAsync( + target, + row, + signal!, + wait, + cancellationToken) + .ConfigureAwait(false); + + if (!accepted) return count; + ++count; } + + return count; } static async ValueTask SendAsync( diff --git a/Tests/Open.Database.Extensions.Core.Tests/CaptureTests.cs b/Tests/Open.Database.Extensions.Core.Tests/CaptureTests.cs index 743c37ee..9a5477ad 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/CaptureTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/CaptureTests.cs @@ -495,6 +495,31 @@ await Assert.ThrowsAsync( "were never delivered"); } + [Fact] + public static async Task ACapture_SurvivesWithOptions_OnTheQueryAndTheSkipView() + { + var c = new CaptureConnection(("total", 9)); + + List rows = await c + .StoredProcedure("p") + .Map() + .CaptureOutput("total", out DbCapture total) + .WithOptions(QueryOptions.SingleResult) + .ToListAsync(Token); + List skipped = await c + .StoredProcedure("p") + .Map() + .Skip(1) + .CaptureOutput("total", out DbCapture skipTotal) + .WithOptions(QueryOptions.SingleResult) + .ToListAsync(Token); + + Assert.Equal(3, rows.Count); + Assert.Equal(9, await total); + Assert.Equal(2, skipped.Count); + Assert.Equal(9, await skipTotal); + } + [Fact] public static async Task Map_SharesTheCommandsCapture_TheFirstRunTakesIt() { diff --git a/Tests/Open.Database.Extensions.Core.Tests/PumpStreamOpenTests.cs b/Tests/Open.Database.Extensions.Core.Tests/PumpStreamOpenTests.cs new file mode 100644 index 00000000..2111751b --- /dev/null +++ b/Tests/Open.Database.Extensions.Core.Tests/PumpStreamOpenTests.cs @@ -0,0 +1,85 @@ +using Open.Database.Extensions.Core; +using static Open.Database.Extensions.Tests.ChannelFixtures; + +namespace Open.Database.Extensions.Tests; + +// The Channel and Dataflow pumps take the enumerator of a stream at the +// call (before their first await) and start the command only at the first +// pull. Each stream class a pump can be given: taking the enumerator and +// disposing it runs no command and opens no connection. +// ToChannel/ToTargetBlock (buffered) get a ChunkStream, or a CapturedStream +// over one when the query has a capture; the HoldingConnection members get +// a StallStream (the pumps ask for a buffer of one row, never 0, so never a +// DirectStream), or a CapturedStream over one. +[ExcludeFromCodeCoverage] +public static class PumpStreamOpenTests +{ + static CancellationToken Ct => TestContext.Current.CancellationToken; + + static readonly TimeSpan Long = TimeSpan.FromSeconds(30); + + static async Task TakeAndDispose( + IAsyncEnumerable stream, + DbTally tally) + { + IAsyncEnumerator rows = stream.GetAsyncEnumerator(Ct); + await rows.DisposeAsync(); + + Assert.Empty(tally.Connections); + Assert.Empty(tally.Commands); + } + + [Fact] + public static async Task ChunkStream_StartsNothing_UntilTheFirstPull() + { + DbTally tally = Tally(3); + + IAsyncEnumerable> stream + = Read(tally).ToPooledBufferStream(Ct); + + Assert.IsType>(stream); + await TakeAndDispose(stream, tally); + } + + [Fact] + public static async Task StallStream_StartsNothing_UntilTheFirstPull() + { + DbTally tally = Tally(3); + + IAsyncEnumerable stream + = Read(tally).StreamBuffered(Long, 1, Ct); + + Assert.IsType>(stream); + await TakeAndDispose(stream, tally); + } + + [Fact] + public static async Task CapturedStream_OverChunks_StartsNothing_UntilTheFirstPull() + { + DbTally tally = Tally(3); + + IAsyncEnumerable> stream = Read(tally) + .CaptureOutput("total", out DbCapture total) + .ToPooledBufferStream(Ct); + + Assert.IsType>>(stream); + await TakeAndDispose(stream, tally); + await Assert.ThrowsAsync( + async () => await total); + } + + [Fact] + public static async Task CapturedStream_OverRows_StartsNothing_UntilTheFirstPull() + { + DbTally tally = Tally(3); + + IAsyncEnumerable stream = Read(tally) + .CaptureOutput("total", out DbCapture total) + .StreamBuffered(Long, 1, Ct); + + Assert.IsType>(stream); + await TakeAndDispose(stream, tally); + await Assert.ThrowsAsync( + async () => await total); + } +} diff --git a/Tests/Open.Database.Extensions.Core.Tests/ToChannelStreamingTests.cs b/Tests/Open.Database.Extensions.Core.Tests/ToChannelStreamingTests.cs index 1054cf95..9338f5bd 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/ToChannelStreamingTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/ToChannelStreamingTests.cs @@ -99,6 +99,54 @@ public static async Task ItWaitsForRoom_BeforeTheCommandRuns() Assert.Equal(3, await task.Within()); } + // The wait for room is in ChannelPump.Open, before the first pull: with + // no room nothing is opened, however the wait ends. No sleeps: the task + // is checked at the instant of the call. + [Fact] + public static async Task AFullChannel_ThatCloses_ReturnsZero_AndOpensNothing() + { + DbTally tally = Tally(5); + Channel channel = Bounded(1); + Assert.True(channel.Writer.TryWrite(new(0))); + + Task task = Read(tally) + .ToChannelHoldingConnection(channel, Long, Ct) + .AsTask(); + + Assert.False(task.IsCompleted); + Assert.Empty(tally.Connections); + Assert.Empty(tally.Commands); + + channel.Writer.Complete(); + + Assert.Equal(0, await task.Within()); + Assert.Empty(tally.Connections); + Assert.Empty(tally.Commands); + } + + [Fact] + public static async Task AFullChannel_RunsTheCommandOnce_WhenARowIsTaken() + { + DbTally tally = Tally(5); + Channel channel = Bounded(1); + Assert.True(channel.Writer.TryWrite(new(0))); + + Task task = Read(tally) + .ToChannelHoldingConnection(channel, Long, Ct) + .AsTask(); + + Assert.False(task.IsCompleted); + Assert.Empty(tally.Connections); + Assert.Empty(tally.Commands); + + Assert.Equal(0, (await channel.Reader.ReadAsync(Ct).AsTask().Within()).Id); + Assert.Equal([1, 2, 3, 4, 5], await Drain(channel.Reader, 5)); + + Assert.Equal(5, await task.Within()); + Assert.Single(tally.Connections); + Assert.Single(tally.Commands); + } + [Fact] public static async Task AStalledTarget_TripsTheTimeout_AndClosesTheConnection() { diff --git a/Tests/Open.Database.Extensions.Core.Tests/ToChannelTargetTests.cs b/Tests/Open.Database.Extensions.Core.Tests/ToChannelTargetTests.cs index 01263729..ad73e7b6 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/ToChannelTargetTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/ToChannelTargetTests.cs @@ -110,6 +110,50 @@ public static async Task ItWaitsForRoom_BeforeTheCommandRuns() Assert.Equal(5, await task.Within()); } + // The wait for room is in ChannelPump.Open, before the first pull: with + // no room nothing is opened, however the wait ends. No sleeps: the task + // is checked at the instant of the call. + [Fact] + public static async Task AFullChannel_ThatCloses_ReturnsZero_AndOpensNothing() + { + DbTally tally = Tally(5); + Channel channel = Bounded(1); + Assert.True(channel.Writer.TryWrite(new(0))); + + Task task = Read(tally).ToChannel(channel, Ct).AsTask(); + + Assert.False(task.IsCompleted); + Assert.Empty(tally.Connections); + Assert.Empty(tally.Commands); + + channel.Writer.Complete(); + + Assert.Equal(0, await task.Within()); + Assert.Empty(tally.Connections); + Assert.Empty(tally.Commands); + } + + [Fact] + public static async Task AFullChannel_RunsTheCommandOnce_WhenARowIsTaken() + { + DbTally tally = Tally(5); + Channel channel = Bounded(1); + Assert.True(channel.Writer.TryWrite(new(0))); + + Task task = Read(tally).ToChannel(channel, Ct).AsTask(); + + Assert.False(task.IsCompleted); + Assert.Empty(tally.Connections); + Assert.Empty(tally.Commands); + + Assert.Equal(0, (await channel.Reader.ReadAsync(Ct).AsTask().Within()).Id); + Assert.Equal([1, 2, 3, 4, 5], await Drain(channel.Reader, 5)); + + Assert.Equal(5, await task.Within()); + Assert.Single(tally.Connections); + Assert.Single(tally.Commands); + } + [Fact] public static async Task AClosedTarget_StopsThePass_WithoutAnException() { diff --git a/Tests/Open.Database.Extensions.Core.Tests/ToTargetBlockStreamingTests.cs b/Tests/Open.Database.Extensions.Core.Tests/ToTargetBlockStreamingTests.cs index c55d57ca..a193d7d1 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/ToTargetBlockStreamingTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/ToTargetBlockStreamingTests.cs @@ -89,6 +89,64 @@ public static async Task AFinishedBlock_ReturnsZero_BeforeTheCommandRuns() 0, await Read(tally).ToTargetBlockHoldingConnection(block, Short, Ct)); Assert.Empty(tally.Connections); + Assert.Empty(tally.Commands); + } + + [Fact] + public static async Task AFaultedBlock_ReturnsZero_BeforeTheCommandRuns() + { + DbTally tally = Tally(3); + BufferBlock block = NewBlock(); + Fault(block, new InvalidOperationException("faulted")); + await Assert.ThrowsAsync( + () => block.Completion); + + Assert.Equal( + 0, + await Read(tally).ToTargetBlockHoldingConnection(block, Short, Ct)); + Assert.Empty(tally.Connections); + Assert.Empty(tally.Commands); + } + + // A block has no wait for room (BlockPump.Open only checks that the + // block is finished), so a full block is not a reason to hold the command. + [Fact] + public static async Task AFullBlock_RunsTheCommandOnce_AndDeliversEveryRow() + { + DbTally tally = Tally(5); + BufferBlock block = NewBounded(1); + Assert.True(block.Post(new(0))); + + Task task = Read(tally) + .ToTargetBlockHoldingConnection(block, Long, Ct) + .AsTask(); + + Assert.Equal([0, 1, 2, 3, 4, 5], await Receive(block, 6)); + Assert.Equal(5, await task.Within()); + Assert.Single(tally.Connections); + Assert.Single(tally.Commands); + } + + // The difference from a channel, pinned: a block that is finishing but + // not yet finished (it still holds a row) is not closed at the call, so + // the command runs once; the first row is declined and the pass returns 0. + [Fact] + public static async Task AFullBlock_ThatCompletes_StillRunsTheCommand_AndReturnsZero() + { + DbTally tally = Tally(5); + BufferBlock block = NewBounded(1); + Assert.True(block.Post(new(0))); + block.Complete(); + Assert.False(block.Completion.IsCompleted); + + long count = await Read(tally) + .ToTargetBlockHoldingConnection(block, Long, Ct) + .AsTask() + .Within(); + + Assert.Equal(0, count); + Assert.Single(tally.Connections); + Assert.Single(tally.Commands); } [Fact] diff --git a/Tests/Open.Database.Extensions.Core.Tests/ToTargetBlockTests.cs b/Tests/Open.Database.Extensions.Core.Tests/ToTargetBlockTests.cs index a7c3025c..b4211b7b 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/ToTargetBlockTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/ToTargetBlockTests.cs @@ -104,6 +104,43 @@ await Assert.ThrowsAsync( Assert.Equal(0, count); Assert.Empty(tally.Connections); + Assert.Empty(tally.Commands); + } + + // A block has no wait for room (BlockPump.Open only checks that the + // block is finished), so a full block is not a reason to hold the command. + [Fact] + public static async Task AFullBlock_RunsTheCommandOnce_AndDeliversEveryRow() + { + DbTally tally = Tally(5); + BufferBlock block = NewBounded(1); + Assert.True(block.Post(new(0))); + + Task task = Read(tally).ToTargetBlock(block, Ct).AsTask(); + + Assert.Equal([0, 1, 2, 3, 4, 5], await Receive(block, 6)); + Assert.Equal(5, await task.Within()); + Assert.Single(tally.Connections); + Assert.Single(tally.Commands); + } + + // The difference from a channel, pinned: a block that is finishing but + // not yet finished (it still holds a row) is not closed at the call, so + // the command runs once; the first row is declined and the pass returns 0. + [Fact] + public static async Task AFullBlock_ThatCompletes_StillRunsTheCommand_AndReturnsZero() + { + DbTally tally = Tally(5); + BufferBlock block = NewBounded(1); + Assert.True(block.Post(new(0))); + block.Complete(); + Assert.False(block.Completion.IsCompleted); + + long count = await Read(tally).ToTargetBlock(block, Ct).AsTask().Within(); + + Assert.Equal(0, count); + Assert.Single(tally.Connections); + Assert.Single(tally.Commands); } [Fact] From f06c10883bace7ec21a73177f8d0f304adf87112 Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Wed, 2 Dec 2026 08:07:28 -0800 Subject: [PATCH 20/20] Docs: capture wording after the final review expressive-commands.md no longer points at a later commit for captures on a definition: a query made from a definition does not take a capture. The release notes name both exceptions a capture call can throw: NotSupportedException on a query made from a definition or one that does not read from an expressive command, InvalidOperationException otherwise. Co-Authored-By: Claude Opus 5.5 --- docsite/articles/expressive-commands.md | 2 +- docsite/articles/release-notes.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docsite/articles/expressive-commands.md b/docsite/articles/expressive-commands.md index 2bba22ed..57659880 100644 --- a/docsite/articles/expressive-commands.md +++ b/docsite/articles/expressive-commands.md @@ -243,7 +243,7 @@ A stream fills its captures when the loop ends, and a `break` still fills them: [!code-csharp[](../samples/OutputParameters.cs#sql_server_output_capture_stream)] -The recommended form for a query is the definition: `static readonly MappedDbQuery X = DbQuery.Procedure("…").Map();`, then `X.Using(factory).AddParam(…)` and the terminal per call (see [Map the definition too](#map-the-definition-too)). Captures on the definition form come in a later commit of this pull request, so these samples use the ad hoc form. There, too, a capture is per call: it goes after `Using` and the parameters, never on the stored definition. +The recommended form for a query is the definition: `static readonly MappedDbQuery X = DbQuery.Procedure("…").Map();`, then `X.Using(factory).AddParam(…)` and the terminal per call (see [Map the definition too](#map-the-definition-too)). A query made from a definition does not take a capture, so these samples use the ad hoc form. A capture is per call: it goes after the parameters, never on a stored definition. - **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`. diff --git a/docsite/articles/release-notes.md b/docsite/articles/release-notes.md index ce9abbb3..22560526 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 `InvalidOperationException` at the call. 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. 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.