From 99f8136e224045df2200e592052d34365b84ade8 Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Thu, 3 Dec 2026 13:39:15 -0800 Subject: [PATCH 01/11] Remove the two ScalarValue helpers The sync scalar transform and the async command bases each had a private helper that turned a DBNull scalar into null. CoreExtensions.DBNullValueToNull already does that for the row readers, so the transform overloads call it and both helpers (one with its doc block) are gone. DBNull is a singleton, so the reference comparison and the type test give the same answer for every value. No behavior change; the same one comparison per scalar call. Co-Authored-By: Claude Sonnet 5.5 --- Source/Core/ExpressiveCommandBase.cs | 12 ------------ Source/Core/ExpressiveDbCommandBase.cs | 4 ++-- Source/Core/Synchronous/SyncExpressiveExtensions.cs | 6 ++---- 3 files changed, 4 insertions(+), 18 deletions(-) diff --git a/Source/Core/ExpressiveCommandBase.cs b/Source/Core/ExpressiveCommandBase.cs index 2fd8fe80..ba9f7f99 100644 --- a/Source/Core/ExpressiveCommandBase.cs +++ b/Source/Core/ExpressiveCommandBase.cs @@ -2047,16 +2047,4 @@ public ValueTask ExecuteReturnAsync( async ValueTask ReturnAsync(CancellationToken cancellationToken) => RowMap.ConvertScalar( await ExecuteReturnAsync(cancellationToken).ConfigureAwait(false)); - - /// - /// Gets what the transform overloads hand to the caller's function. - /// - /// - /// NULL () becomes , like no row; - /// any other value is passed unchanged. - /// - /// The raw value from the provider. - /// The value to pass on. - private protected static object? ScalarValue(object? value) - => value is DBNull ? null : value; } diff --git a/Source/Core/ExpressiveDbCommandBase.cs b/Source/Core/ExpressiveDbCommandBase.cs index 31b366dd..942128ed 100644 --- a/Source/Core/ExpressiveDbCommandBase.cs +++ b/Source/Core/ExpressiveDbCommandBase.cs @@ -190,7 +190,7 @@ public async ValueTask ExecuteScalarAsync( Contract.EndContractBlock(); return transform( - ScalarValue( + CoreExtensions.DBNullValueToNull( await ExecuteScalarAsync(cancellationToken) .ConfigureAwait(false))); } @@ -237,7 +237,7 @@ public async ValueTask ExecuteScalarAsync( Contract.EndContractBlock(); return await transform( - ScalarValue( + CoreExtensions.DBNullValueToNull( await ExecuteScalarAsync(cancellationToken) .ConfigureAwait(false))) .ConfigureAwait(false); diff --git a/Source/Core/Synchronous/SyncExpressiveExtensions.cs b/Source/Core/Synchronous/SyncExpressiveExtensions.cs index 82022bb8..89b8aaeb 100644 --- a/Source/Core/Synchronous/SyncExpressiveExtensions.cs +++ b/Source/Core/Synchronous/SyncExpressiveExtensions.cs @@ -83,7 +83,8 @@ public static T ExecuteScalar( if (transform is null) throw new ArgumentNullException(nameof(transform)); Contract.EndContractBlock(); - return transform(ScalarValue(command.ExecuteScalar())); + return transform( + CoreExtensions.DBNullValueToNull(command.ExecuteScalar())); } /// @@ -221,7 +222,4 @@ public static T ExecuteReader( Func transform, CommandBehavior behavior = CommandBehavior.Default) => command.AsSync().ExecuteReader(transform, behavior); - - private static object? ScalarValue(object? value) - => value is DBNull ? null : value; } From 94410b2df29575f7d914b140b750913717f9a3e4 Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Thu, 3 Dec 2026 13:39:15 -0800 Subject: [PATCH 02/11] ToDataTable and ToDataTables go through ExecuteReader The two blocking command extensions repeated the guard, the open-and-execute and the using that ExecuteReader(transform) already has. They now pass a static transform to it, like the sibling right below them: same null check (ArgumentNullException for "command"), same reader disposal, same behavior argument. Cost: one call through a cached static delegate for each ToDataTable or ToDataTables call; no allocation. Co-Authored-By: Claude Sonnet 5.5 --- Source/Core/Synchronous/SyncCommandExtensions.cs | 16 ++-------------- 1 file changed, 2 insertions(+), 14 deletions(-) diff --git a/Source/Core/Synchronous/SyncCommandExtensions.cs b/Source/Core/Synchronous/SyncCommandExtensions.cs index 055d551b..872834d7 100644 --- a/Source/Core/Synchronous/SyncCommandExtensions.cs +++ b/Source/Core/Synchronous/SyncCommandExtensions.cs @@ -18,13 +18,7 @@ public static class SyncCommandExtensions /// A that holds the result set. /// public static DataTable ToDataTable(this IDbCommand command, CommandBehavior behavior = CommandBehavior.Default) - { - if (command is null) throw new ArgumentNullException(nameof(command)); - Contract.EndContractBlock(); - - using IDataReader reader = command.OpenAndExecuteReader(behavior); - return reader.ToDataTable(); - } + => command.ExecuteReader(static r => r.ToDataTable(), behavior); /// /// Executes a reader and loads each result set into its own . @@ -43,13 +37,7 @@ public static DataTable ToDataTable(this IDbCommand command, CommandBehavior beh /// A list of tables, one for each result set. /// public static List ToDataTables(this IDbCommand command, CommandBehavior behavior = CommandBehavior.Default) - { - if (command is null) throw new ArgumentNullException(nameof(command)); - Contract.EndContractBlock(); - - using IDataReader reader = command.OpenAndExecuteReader(behavior); - return reader.ToDataTables(); - } + => command.ExecuteReader(static r => r.ToDataTables(), behavior); /// /// Executes a reader and passes it to a handler. From b25462df9c428573d8f1179c2fe41e1897de27af Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Thu, 3 Dec 2026 13:39:16 -0800 Subject: [PATCH 03/11] PooledArray ICollection.CopyTo reuses the span CopyTo The explicit ICollection.CopyTo kept its own copy of the chunk loop. It keeps its argument checks (null, negative index, destination too small, same exceptions and messages) and then calls CopyTo(Span), which does the same chunk-by-chunk copy. Run time is the same copy; the one extra length check in the span overload is a compare. Co-Authored-By: Claude Sonnet 5.5 --- Source/Core/PooledArray.cs | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/Source/Core/PooledArray.cs b/Source/Core/PooledArray.cs index 48277b66..8c2fead2 100644 --- a/Source/Core/PooledArray.cs +++ b/Source/Core/PooledArray.cs @@ -408,11 +408,7 @@ void ICollection.CopyTo(T[] array, int arrayIndex) "The destination is too small.", nameof(array)); } - foreach (ArrayLease chunk in _chunks) - { - chunk.Span.CopyTo(array.AsSpan(arrayIndex)); - arrayIndex += chunk.Used; - } + CopyTo(array.AsSpan(arrayIndex)); } /// From 6a1d7cf06586ab36ab3e1aae3dccd6368f72c471 Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Thu, 3 Dec 2026 13:39:16 -0800 Subject: [PATCH 04/11] The chunk configuration is the recycle bin's runner The recycle bin queued a work item made of a per-row-type runner object, the array, the row count and the configuration as object, and the runner cast the configuration back. The configuration now implements RecycleBin.IRunner itself, so a work item is the runner, the array and the row count, ChunkRunner and its static instance are gone, and the loop no longer casts the configuration. The interface is not generic, so one bin still serves every row type. Cost on the release path: none. Posting a deferred chunk passes the configuration as an interface reference (no boxing, no allocation) in place of the static runner, and the work item is one field smaller. Checked with a throwaway test: 1,000 deferred releases on a warmed bin allocated 0 bytes on the releasing thread. Co-Authored-By: Claude Sonnet 5.5 --- Source/Core/ArrayLease.cs | 23 ++----------------- Source/Core/ChunkConfig.cs | 5 ++++ Source/Core/RecycleBin.cs | 18 +++++---------- .../TestHelpers/TestBin.cs | 6 ++--- 4 files changed, 16 insertions(+), 36 deletions(-) diff --git a/Source/Core/ArrayLease.cs b/Source/Core/ArrayLease.cs index a3fd2266..a7e73452 100644 --- a/Source/Core/ArrayLease.cs +++ b/Source/Core/ArrayLease.cs @@ -93,11 +93,8 @@ public void Release() // keep dirty rows: the clear runs here instead. Never a dirty // array to a pool, and no one waits on the loop. if (config.Bin.Post( - new RecycleBin.Work( - ChunkRunner.Instance, - Array, - Used, - config)) == RecycleBin.PostResult.Full) + new RecycleBin.Work(config, Array, Used)) + == RecycleBin.PostResult.Full) { config.ClearAndReturn(Array, Used); } @@ -113,19 +110,3 @@ public void Release() public void Dispose() => Release(); } - -/// The one runner of each row type. -/// -// One cached instance for each row type: no allocation per post. -internal sealed class ChunkRunner : RecycleBin.IRunner -{ - /// The one runner of this . - public static readonly ChunkRunner Instance = new(); - - /// Clears the first rows and gives the array back. - /// The array to clear and return. - /// - /// The the array came from. - public void Run(Array array, int used, object config) - => ((ChunkConfig)config).ClearAndReturn((T[])array, used); -} diff --git a/Source/Core/ChunkConfig.cs b/Source/Core/ChunkConfig.cs index b6d2c544..fb5aaca4 100644 --- a/Source/Core/ChunkConfig.cs +++ b/Source/Core/ChunkConfig.cs @@ -42,6 +42,7 @@ internal sealed class ChunkConfig( ChunkSizes sizes, RecycleBin bin, int deferFromClearedBytes) + : RecycleBin.IRunner { /// /// The bytes of rows (rows written times the size of a row) from which the @@ -186,4 +187,8 @@ public void ClearAndReturn(T[] array, int used) array.AsSpan(0, used).Clear(); Pool.Return(array, clearArray: false); } + + // What the recycle bin's loop calls: the same clear and return. + void RecycleBin.IRunner.Run(Array array, int used) + => ClearAndReturn((T[])array, used); } diff --git a/Source/Core/RecycleBin.cs b/Source/Core/RecycleBin.cs index 3b31dd10..a91eeae8 100644 --- a/Source/Core/RecycleBin.cs +++ b/Source/Core/RecycleBin.cs @@ -5,9 +5,9 @@ namespace Open.Database.Extensions.Core; // Threshold: a chunk of 128 KB or more of rows (value rows included) is cleared here; a smaller one is cleared where it is released. // The only work the bin ever runs is ours and bounded (clear the rows of one array, then give it back). The default path with no clearing, and small chunks, never touch it. // How it works: -// - One Channel of struct work items (a runner, an array, the number of rows, the configuration), bounded by the capacity, with one reader. +// - One Channel of struct work items (a runner, an array, the number of rows), bounded by the capacity, with one reader. // A post is a struct written into the queue: no delegate, no closure, no allocation once the queue has grown. -// The runner is one cached object per row type (ChunkRunner); it does the same ChunkConfig.ClearAndReturn that the immediate release does. +// The runner is the chunk's own ChunkConfig, which does the same ClearAndReturn that the immediate release does; IRunner is not generic, so one bin serves every row type. // - One always-on loop (an async method, no task per item), started once by the first post: it waits for work, drains the available batch with TryRead, // runs each item in its own try/catch (an item that throws, such as a pool whose Return throws, costs only that item), and yields once per batch // so it does not hog a pool thread. There is no idle exit: a parked await holds no thread. @@ -62,26 +62,23 @@ public enum PostResult Full, } - /// What the loop runs: one cached object per row type. + /// What the loop runs: the configuration the array came from. public interface IRunner { /// Clears the first rows and gives the array back. /// The array to clear and return. /// - /// The configuration the array came from. - void Run(Array array, int used, object config); + void Run(Array array, int used); } /// One array to clear and give back. /// Does the clear and the return. /// The array to clear and return. /// How many slots, from the start, hold rows. - /// The configuration the array came from. public readonly struct Work( IRunner runner, Array array, - int used, - object config) + int used) { /// Gets the runner that does the clear and the return. public IRunner Runner { get; } = runner; @@ -91,9 +88,6 @@ public readonly struct Work( /// Gets how many slots, from the start, hold rows. public int Used { get; } = used; - - /// Gets the configuration the array came from. - public object Config { get; } = config; } /// The bin every default configuration posts to. @@ -192,7 +186,7 @@ async Task DrainAsync() { while (reader.TryRead(out Work work)) { - try { work.Runner.Run(work.Array, work.Used, work.Config); } + try { work.Runner.Run(work.Array, work.Used); } catch { } } diff --git a/Tests/Open.Database.Extensions.Core.Tests/TestHelpers/TestBin.cs b/Tests/Open.Database.Extensions.Core.Tests/TestHelpers/TestBin.cs index 3b5b1baa..3e97d57c 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/TestHelpers/TestBin.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/TestHelpers/TestBin.cs @@ -36,7 +36,7 @@ public override PostResult TryPost(Work work) /// for a test of the bin itself. /// public static Work Item(IRunner runner) - => new(runner, Array.Empty(), 0, new object()); + => new(runner, Array.Empty(), 0); /// A runner that blocks the bin's one loop until the gate opens. public sealed class GateRunner( @@ -44,7 +44,7 @@ public sealed class GateRunner( ManualResetEventSlim gate) : IRunner { - public void Run(Array array, int used, object config) + public void Run(Array array, int used) { started.Set(); gate.Wait(TimeSpan.FromSeconds(30)); @@ -54,7 +54,7 @@ public void Run(Array array, int used, object config) /// A runner that runs an action. public sealed class ActionRunner(Action action) : IRunner { - public void Run(Array array, int used, object config) + public void Run(Array array, int used) => action(); } } From 8c832b2cbc28b9160cf8cdbbdb1e0f347d8e6d55 Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Thu, 3 Dec 2026 13:49:03 -0800 Subject: [PATCH 05/11] A schema row with a bad ordinal no longer fails the parameter-name lookup The lookup of a stored procedure's parameter names converted ORDINAL_POSITION with Convert.ToInt32 and no guard, so a provider that reports a value that is not a number, or one that does not fit an int, failed the call with FormatException, InvalidCastException or OverflowException. The check of output parameters reads the same column through TryInt and treats such a value as not known, and the lookup's own docs say not known gives no names. The lookup now uses the same TryInt (one home, in ProcedureParameterMetadata) and skips the row; the other parameters are still found. Tests: a stub schema connection whose ordinal column holds a string, DBNull, a long and a numeric string that overflows an int, beside a good row; the call must not throw and send only the good row's name. Before the change the string and the two overflow cases failed with FormatException and OverflowException from the lookup; DBNull was already skipped. Cost: none on the normal path (a number converts as before); a bad value is now caught inside TryInt instead of escaping. The release note has a Fixed line. Co-Authored-By: Claude Sonnet 5.5 --- Source/Core/ProcedureParameterMetadata.cs | 9 ++++++- Source/Core/ProcedureSchemaNames.cs | 5 ++-- .../ProcedureSchemaNamesTests.cs | 27 +++++++++++++++++++ docsite/articles/release-notes.md | 1 + 4 files changed, 39 insertions(+), 3 deletions(-) diff --git a/Source/Core/ProcedureParameterMetadata.cs b/Source/Core/ProcedureParameterMetadata.cs index cede113b..e1f3f400 100644 --- a/Source/Core/ProcedureParameterMetadata.cs +++ b/Source/Core/ProcedureParameterMetadata.cs @@ -202,7 +202,14 @@ static int ScaleOf(object value) ? scale : ParameterMetadata.NoScale; - static bool TryInt(object value, out int result) + /// + /// Reads a value from the schema table as an ; a value that + /// is not a number that fits is not known, not a failure. + /// + /// The value of a schema table cell. + /// The number; 0 when it is not known. + /// if the value is a number that fits; otherwise, . + public static bool TryInt(object value, out int result) { try { diff --git a/Source/Core/ProcedureSchemaNames.cs b/Source/Core/ProcedureSchemaNames.cs index 64f01f68..c0ab2d02 100644 --- a/Source/Core/ProcedureSchemaNames.cs +++ b/Source/Core/ProcedureSchemaNames.cs @@ -1,4 +1,3 @@ -using System.Globalization; using System.Text; namespace Open.Database.Extensions; @@ -186,7 +185,9 @@ static ImmutableArray Names(DataTable? table, bool schemaGiven) { if (row["PARAMETER_NAME"] is not string { Length: > 0 } name || row["ORDINAL_POSITION"] is DBNull) continue; - int ordinal = Convert.ToInt32(row["ORDINAL_POSITION"], CultureInfo.InvariantCulture); + // A value that is not a number that fits is not known, as the metadata read of the column treats it. + if (!ProcedureParameterMetadata.TryInt(row["ORDINAL_POSITION"], out int ordinal)) continue; + if (ordinal > 0) found.Add(new(ordinal, name)); } diff --git a/Tests/Open.Database.Extensions.Core.Tests/ProcedureSchemaNamesTests.cs b/Tests/Open.Database.Extensions.Core.Tests/ProcedureSchemaNamesTests.cs index f1f51121..2119d452 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/ProcedureSchemaNamesTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/ProcedureSchemaNamesTests.cs @@ -236,6 +236,33 @@ public static void ATableWithoutParameters_IsNotKnown_AndRememberedForAShortWhil Assert.Equal(1, connection.SchemaCalls); // an empty answer ("not known") is remembered for a short while, not read again in every run } + // What a provider can put in ORDINAL_POSITION that is not a number that fits an int: not known, as the metadata read of the same column treats it. + public static TheoryData BadOrdinals => new() + { + "abc", + DBNull.Value, + long.MaxValue, + "99999999999", + }; + + [Theory] + [MemberData(nameof(BadOrdinals), DisableDiscoveryEnumeration = true)] + public static void ARowWhoseOrdinalIsNotANumberThatFits_IsSkipped_AndTheCallDoesNotFail(object badOrdinal) + { + const int orderId = 5; + var table = new DataTable("ProcedureParameters"); + table.Columns.Add("SPECIFIC_SCHEMA", typeof(string)); + table.Columns.Add("SPECIFIC_NAME", typeof(string)); + table.Columns.Add("ORDINAL_POSITION", typeof(object)); + table.Columns.Add("PARAMETER_NAME", typeof(string)); + table.Rows.Add("dbo", "proc", 1, "@order_id"); + table.Rows.Add("dbo", "proc", badOrdinal, "@p_name"); + var connection = new SchemaConnection(table, null); + + Assert.Equal(["@order_id"], Run(connection, Proc(), c => c.AddParam(orderId))); + Assert.Equal(1, connection.SchemaCalls); + } + public static TheoryData Unsupported => new() { new NotSupportedException(), diff --git a/docsite/articles/release-notes.md b/docsite/articles/release-notes.md index 1b7cbe58..d080df8c 100644 --- a/docsite/articles/release-notes.md +++ b/docsite/articles/release-notes.md @@ -11,6 +11,7 @@ Version 11 is `11.0.0-rc.17`. 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`; both packages now throw `InvalidOperationException`, with a message that says the cause and the fix. `CreateTextCommand` and `CreateStoredProcedureCommand` follow. - **Fixed: a failed read through `ToChannel` or `ToChannelReader` was also raised as an unobserved task exception.** The failure reached the channel, as documented, but the read's task was dropped by the forms that do not return the count, so `TaskScheduler.UnobservedTaskException` fired when the task was collected. The task's fault is now read, so nothing is raised; the count you ask for with `ToChannel(out Task readCount)` still throws when awaited. +- **Fixed: a stored procedure's parameter names with an ordinal that is not a number.** A row of the `ProcedureParameters` schema collection whose `ORDINAL_POSITION` is not a number that fits an `int` failed the call that looks up the names; the row is now skipped, as the check of output parameters already treats it, and the other parameters are still found. - **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. A parameter on the chain is an input. `Param` has no `direction` constructor parameter and no `Direction` property. - **To set a direction, or read an output:** use `ExecuteAsync(command => ...)` with the raw `AddParameter`, `AddParameterType` and `AddReturnParameter` extensions, or read the output with `ExecuteOutputAsync`. - **Changed: `AddParam(name, (byte)0)` on the SQL Server command is an ambiguous call.** A constant zero of type `byte` used to bind silently to the direction overload; it now fails to compile (CS0121). Pass a variable, or give the database type, `AddParam(name, value, SqlDbType.TinyInt)`. Calls that never passed a direction compile unchanged. From ca52910980c44d73df9804884d0b5f8b4d226b51 Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Thu, 3 Dec 2026 13:49:03 -0800 Subject: [PATCH 06/11] The blank parameter name message says what to pass Adding a parameter to a stored query call with a blank name threw "Parameter names cannot be empty or white space." and stopped there. It now adds "Pass the name of a parameter of the command." The key phrase and the ParamName are unchanged, and the test that pins the text is updated. Co-Authored-By: Claude Sonnet 5.5 --- Source/Core/DbQueryCall.cs | 2 +- .../Open.Database.Extensions.Core.Tests/DbQueryChecksTests.cs | 4 +++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/Source/Core/DbQueryCall.cs b/Source/Core/DbQueryCall.cs index d6b87780..98197e92 100644 --- a/Source/Core/DbQueryCall.cs +++ b/Source/Core/DbQueryCall.cs @@ -171,7 +171,7 @@ internal static string CheckedName(string name) => CheckedText( name, nameof(name), - "Parameter names cannot be empty or white space."); + "Parameter names cannot be empty or white space. Pass the name of a parameter of the command."); /// Checks a text that must be given and not blank. /// The text. diff --git a/Tests/Open.Database.Extensions.Core.Tests/DbQueryChecksTests.cs b/Tests/Open.Database.Extensions.Core.Tests/DbQueryChecksTests.cs index 016f49e3..0c35eafd 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/DbQueryChecksTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/DbQueryChecksTests.cs @@ -11,7 +11,9 @@ namespace Open.Database.Extensions.Tests; [ExcludeFromCodeCoverage] public static class DbQueryChecksTests { - const string BlankName = "Parameter names cannot be empty or white space."; + const string BlankName = + "Parameter names cannot be empty or white space. " + + "Pass the name of a parameter of the command."; const string BlankCommand = "The command cannot be empty or white space. " + "Pass the SQL text or the name of the stored procedure."; From 165639bacb3f07efcc1a1bfd3aec428caaa36505 Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Thu, 3 Dec 2026 14:02:02 -0800 Subject: [PATCH 07/11] Say the fix in every blank parameter name message, and give the release note its own section A blank parameter name raised the same message in five places, one of which now says what to pass. The other four (the command's own check, the add-parameter extension in Core, and the two SQL Server packages) now use the same wording, so the one condition has one message that says the fix. The messages are wrapped to the layout rules and the wrapped throws are braced. The release note for the ordinal fix moves to a new "Changes since rc.17" section, since rc.17 is published, and no longer refers to another check that readers cannot see. Co-Authored-By: Claude Sonnet 5.5 --- Source/Core/DbQueryCall.cs | 3 ++- Source/Core/ExpressiveCommandBase.Param.cs | 7 ++++++- Source/Core/Extensions/Command.AddParameter.cs | 4 +++- Source/MSSqlClient/Extensions/Command.AddParameter.cs | 7 ++++++- Source/SqlClient/Extensions/Command.AddParameter.cs | 7 ++++++- docsite/articles/release-notes.md | 5 ++++- 6 files changed, 27 insertions(+), 6 deletions(-) diff --git a/Source/Core/DbQueryCall.cs b/Source/Core/DbQueryCall.cs index 98197e92..d62b0709 100644 --- a/Source/Core/DbQueryCall.cs +++ b/Source/Core/DbQueryCall.cs @@ -171,7 +171,8 @@ internal static string CheckedName(string name) => CheckedText( name, nameof(name), - "Parameter names cannot be empty or white space. Pass the name of a parameter of the command."); + "Parameter names cannot be empty or white space. " + + "Pass the name of a parameter of the command."); /// Checks a text that must be given and not blank. /// The text. diff --git a/Source/Core/ExpressiveCommandBase.Param.cs b/Source/Core/ExpressiveCommandBase.Param.cs index 7a38205f..e2e1cb06 100644 --- a/Source/Core/ExpressiveCommandBase.Param.cs +++ b/Source/Core/ExpressiveCommandBase.Param.cs @@ -32,7 +32,12 @@ public Param( { if (name is null) throw new ArgumentNullException(nameof(name)); if (string.IsNullOrWhiteSpace(name)) - throw new ArgumentException("Parameter names cannot be empty or white space.", nameof(name)); + { + throw new ArgumentException( + "Parameter names cannot be empty or white space. " + + "Pass the name of a parameter of the command.", + nameof(name)); + } Contract.EndContractBlock(); Name = name; diff --git a/Source/Core/Extensions/Command.AddParameter.cs b/Source/Core/Extensions/Command.AddParameter.cs index f683ddbb..790cc2c5 100644 --- a/Source/Core/Extensions/Command.AddParameter.cs +++ b/Source/Core/Extensions/Command.AddParameter.cs @@ -2,7 +2,9 @@ public static partial class CommandExtensions { - private const string ParameterNamesNotEmptyMessage = "Parameter names cannot be empty or white space."; + private const string ParameterNamesNotEmptyMessage = + "Parameter names cannot be empty or white space. " + + "Pass the name of a parameter of the command."; private const string ParameterNamesOnlyNullForReturn = "Parameter names can only be null for a return parameter."; /// diff --git a/Source/MSSqlClient/Extensions/Command.AddParameter.cs b/Source/MSSqlClient/Extensions/Command.AddParameter.cs index 393c0699..c1177e16 100644 --- a/Source/MSSqlClient/Extensions/Command.AddParameter.cs +++ b/Source/MSSqlClient/Extensions/Command.AddParameter.cs @@ -48,7 +48,12 @@ public static SqlParameter AddParameterType( if (direction != ParameterDirection.ReturnValue && name == null) throw new ArgumentNullException(nameof(name), "Parameter names can only be null for a return parameter."); else if (name != null && string.IsNullOrWhiteSpace(name)) - throw new ArgumentException("Parameter names cannot be empty or white space.", nameof(name)); + { + throw new ArgumentException( + "Parameter names cannot be empty or white space. " + + "Pass the name of a parameter of the command.", + nameof(name)); + } Contract.EndContractBlock(); SqlParameter c = target.CreateParameter(); diff --git a/Source/SqlClient/Extensions/Command.AddParameter.cs b/Source/SqlClient/Extensions/Command.AddParameter.cs index fbf53103..f5911587 100644 --- a/Source/SqlClient/Extensions/Command.AddParameter.cs +++ b/Source/SqlClient/Extensions/Command.AddParameter.cs @@ -48,7 +48,12 @@ public static SqlParameter AddParameterType( if (direction != ParameterDirection.ReturnValue && name == null) throw new ArgumentNullException(nameof(name), "Parameter names can only be null for a return parameter."); else if (name != null && string.IsNullOrWhiteSpace(name)) - throw new ArgumentException("Parameter names cannot be empty or white space.", nameof(name)); + { + throw new ArgumentException( + "Parameter names cannot be empty or white space. " + + "Pass the name of a parameter of the command.", + nameof(name)); + } Contract.EndContractBlock(); SqlParameter c = target.CreateParameter(); diff --git a/docsite/articles/release-notes.md b/docsite/articles/release-notes.md index d080df8c..d5c61f55 100644 --- a/docsite/articles/release-notes.md +++ b/docsite/articles/release-notes.md @@ -4,6 +4,10 @@ Version 11 is `11.0.0-rc.17`. For moving a 10.x codebase, read [Coming from earl ## Version 11 release candidates +### Changes since rc.17 + +- **Fixed: a stored procedure's parameter names with an ordinal that is not a number.** A row of the `ProcedureParameters` schema collection whose `ORDINAL_POSITION` is not a number that fits an `int` failed the call that looks up the names; the row is now skipped, and the other parameters are still found. + ### Changes since rc.16 - **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. @@ -11,7 +15,6 @@ Version 11 is `11.0.0-rc.17`. 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`; both packages now throw `InvalidOperationException`, with a message that says the cause and the fix. `CreateTextCommand` and `CreateStoredProcedureCommand` follow. - **Fixed: a failed read through `ToChannel` or `ToChannelReader` was also raised as an unobserved task exception.** The failure reached the channel, as documented, but the read's task was dropped by the forms that do not return the count, so `TaskScheduler.UnobservedTaskException` fired when the task was collected. The task's fault is now read, so nothing is raised; the count you ask for with `ToChannel(out Task readCount)` still throws when awaited. -- **Fixed: a stored procedure's parameter names with an ordinal that is not a number.** A row of the `ProcedureParameters` schema collection whose `ORDINAL_POSITION` is not a number that fits an `int` failed the call that looks up the names; the row is now skipped, as the check of output parameters already treats it, and the other parameters are still found. - **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. A parameter on the chain is an input. `Param` has no `direction` constructor parameter and no `Direction` property. - **To set a direction, or read an output:** use `ExecuteAsync(command => ...)` with the raw `AddParameter`, `AddParameterType` and `AddReturnParameter` extensions, or read the output with `ExecuteOutputAsync`. - **Changed: `AddParam(name, (byte)0)` on the SQL Server command is an ambiguous call.** A constant zero of type `byte` used to bind silently to the direction overload; it now fails to compile (CS0121). Pass a variable, or give the database type, `AddParam(name, value, SqlDbType.TinyInt)`. Calls that never passed a direction compile unchanged. From f995349ca3ade592b741229f47a8b0d0e4d91a44 Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Thu, 3 Dec 2026 14:21:43 -0800 Subject: [PATCH 08/11] Brace the parameter name checks in the two SQL Server packages and the command's own check The wrapped throws made the one-line conditions around them multi-line, so the style check asked for braces on the whole if chain. The bodies are indented under their braces. Co-Authored-By: Claude Sonnet 5.5 --- Source/Core/ExpressiveCommandBase.Param.cs | 8 ++++---- Source/MSSqlClient/Extensions/Command.AddParameter.cs | 10 ++++++---- Source/SqlClient/Extensions/Command.AddParameter.cs | 10 ++++++---- 3 files changed, 16 insertions(+), 12 deletions(-) diff --git a/Source/Core/ExpressiveCommandBase.Param.cs b/Source/Core/ExpressiveCommandBase.Param.cs index e2e1cb06..b2dd453d 100644 --- a/Source/Core/ExpressiveCommandBase.Param.cs +++ b/Source/Core/ExpressiveCommandBase.Param.cs @@ -33,10 +33,10 @@ public Param( if (name is null) throw new ArgumentNullException(nameof(name)); if (string.IsNullOrWhiteSpace(name)) { - throw new ArgumentException( - "Parameter names cannot be empty or white space. " - + "Pass the name of a parameter of the command.", - nameof(name)); + throw new ArgumentException( + "Parameter names cannot be empty or white space. " + + "Pass the name of a parameter of the command.", + nameof(name)); } Contract.EndContractBlock(); diff --git a/Source/MSSqlClient/Extensions/Command.AddParameter.cs b/Source/MSSqlClient/Extensions/Command.AddParameter.cs index c1177e16..6f6996ed 100644 --- a/Source/MSSqlClient/Extensions/Command.AddParameter.cs +++ b/Source/MSSqlClient/Extensions/Command.AddParameter.cs @@ -46,13 +46,15 @@ public static SqlParameter AddParameterType( { if (target is null) throw new ArgumentNullException(nameof(target)); if (direction != ParameterDirection.ReturnValue && name == null) + { throw new ArgumentNullException(nameof(name), "Parameter names can only be null for a return parameter."); + } else if (name != null && string.IsNullOrWhiteSpace(name)) { - throw new ArgumentException( - "Parameter names cannot be empty or white space. " - + "Pass the name of a parameter of the command.", - nameof(name)); + throw new ArgumentException( + "Parameter names cannot be empty or white space. " + + "Pass the name of a parameter of the command.", + nameof(name)); } Contract.EndContractBlock(); diff --git a/Source/SqlClient/Extensions/Command.AddParameter.cs b/Source/SqlClient/Extensions/Command.AddParameter.cs index f5911587..718bd840 100644 --- a/Source/SqlClient/Extensions/Command.AddParameter.cs +++ b/Source/SqlClient/Extensions/Command.AddParameter.cs @@ -46,13 +46,15 @@ public static SqlParameter AddParameterType( { if (target is null) throw new ArgumentNullException(nameof(target)); if (direction != ParameterDirection.ReturnValue && name == null) + { throw new ArgumentNullException(nameof(name), "Parameter names can only be null for a return parameter."); + } else if (name != null && string.IsNullOrWhiteSpace(name)) { - throw new ArgumentException( - "Parameter names cannot be empty or white space. " - + "Pass the name of a parameter of the command.", - nameof(name)); + throw new ArgumentException( + "Parameter names cannot be empty or white space. " + + "Pass the name of a parameter of the command.", + nameof(name)); } Contract.EndContractBlock(); From df3f72ee26bbafc53c2858231e745b870a38bde2 Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Thu, 3 Dec 2026 15:34:52 -0800 Subject: [PATCH 09/11] Put the equals sign of a wrapped initializer at the start of the next line A wrapped constant now starts its continuation line with the equals sign, as an expression body starts with its arrow, so the sign and the plus of a joined literal line up. The constants beside them take the same shape. Layout only. Co-Authored-By: Claude Sonnet 5.5 --- Source/Core/Extensions/Command.AddParameter.cs | 7 ++++--- .../DbQueryChecksTests.cs | 8 ++++---- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/Source/Core/Extensions/Command.AddParameter.cs b/Source/Core/Extensions/Command.AddParameter.cs index 790cc2c5..f51759b1 100644 --- a/Source/Core/Extensions/Command.AddParameter.cs +++ b/Source/Core/Extensions/Command.AddParameter.cs @@ -2,10 +2,11 @@ public static partial class CommandExtensions { - private const string ParameterNamesNotEmptyMessage = - "Parameter names cannot be empty or white space. " + private const string ParameterNamesNotEmptyMessage + = "Parameter names cannot be empty or white space. " + "Pass the name of a parameter of the command."; - private const string ParameterNamesOnlyNullForReturn = "Parameter names can only be null for a return parameter."; + private const string ParameterNamesOnlyNullForReturn + = "Parameter names can only be null for a return parameter."; /// /// Adds a parameter with the given name and value to the command, leaving the provider to infer the database type from the value. diff --git a/Tests/Open.Database.Extensions.Core.Tests/DbQueryChecksTests.cs b/Tests/Open.Database.Extensions.Core.Tests/DbQueryChecksTests.cs index 0c35eafd..1b4055af 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/DbQueryChecksTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/DbQueryChecksTests.cs @@ -11,11 +11,11 @@ namespace Open.Database.Extensions.Tests; [ExcludeFromCodeCoverage] public static class DbQueryChecksTests { - const string BlankName = - "Parameter names cannot be empty or white space. " + const string BlankName + = "Parameter names cannot be empty or white space. " + "Pass the name of a parameter of the command."; - const string BlankCommand = - "The command cannot be empty or white space. " + const string BlankCommand + = "The command cannot be empty or white space. " + "Pass the SQL text or the name of the stored procedure."; static CancellationToken Token => TestContext.Current.CancellationToken; From 5164c6d907ea7a14263fa453a42fce0f863e7c3c Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Thu, 3 Dec 2026 15:37:36 -0800 Subject: [PATCH 10/11] Keep each parameter name message as one constant, and put the equals sign of a wrapped initializer on its next line The blank parameter name message was written out at five places and the message for a missing name on a non-return parameter at three, in Core and in the two SQL Server packages. Each is now one constant in an internal class in Core, which the provider packages can see, and every place references it. The definition's name check passes the constant instead of an inline joined literal. The one-line checks go back to their original unbraced shape. CONTRIBUTING.md gets the two rules: a wrapped initializer starts its continuation with the equals sign, and one text for each fact, as a named constant. The constants beside the first one take the same shape, each with a blank line above it. Co-Authored-By: Claude Sonnet 5.5 --- CONTRIBUTING.md | 2 ++ Source/Core/Core/ParameterNameMessages.cs | 17 +++++++++++++++++ Source/Core/DbQueryCall.cs | 6 +----- Source/Core/ExpressiveCommandBase.Param.cs | 7 +------ Source/Core/Extensions/Command.AddParameter.cs | 12 +++--------- .../Extensions/Command.AddParameter.cs | 11 ++--------- .../Extensions/Command.AddParameter.cs | 11 ++--------- 7 files changed, 28 insertions(+), 38 deletions(-) create mode 100644 Source/Core/Core/ParameterNameMessages.cs diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index f818eb94..77a4a70e 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -8,6 +8,7 @@ How code gets into Open.Database.Extensions (ODX): the code rules a reviewer che - **Chains.** The first call stays on the line of what it is called on; from the second call on, one call per line. A single call stays on one line. Never leave a bare receiver alone on a line. - **Line width.** About 80 columns, a soft limit. An expression body's `=>` goes on the next line. +- **Wrapped initializers.** When an initializer or assignment wraps, its `=` starts the next indented line, as `=>` does, and a joined literal continues with `+` under it. A constant beside it takes the same shape even if it would fit on one line, and each constant has a blank line above it. - **Arguments.** Keep a call on one line when it fits. When it does not, break the arguments into groups that belong together, one group per line. A long run of one-argument lines is a sign to regroup. - **Braces.** A header that wraps over two or more lines always gets braces, even for one statement. A one-line header with one short statement may skip them (`csharp_prefer_braces = when_multiline`). @@ -22,6 +23,7 @@ How code gets into Open.Database.Extensions (ODX): the code rules a reviewer che - **Every exception says what is wrong and what to do.** Name the object or parameter, the cause, and the fix ("Call the query's terminal first, then await the capture."). - **Guard once, at the public entry point,** with the right parameter name. Internal code trusts it and uses `Debug.Assert`. Our code never throws `NullReferenceException`. +- **One text for each fact.** A message that says the same thing in more than one place is one `const` in Core (an `internal` class is visible to the provider packages), referenced everywhere, and a message passed as an argument is that named constant, not an inline concatenation. Messages that differ on purpose, because each names its own call site, stay separate. - **A misuse the compiler can catch is a compile error,** not a runtime throw, when that costs little API. ### Performance diff --git a/Source/Core/Core/ParameterNameMessages.cs b/Source/Core/Core/ParameterNameMessages.cs new file mode 100644 index 00000000..6960c052 --- /dev/null +++ b/Source/Core/Core/ParameterNameMessages.cs @@ -0,0 +1,17 @@ +namespace Open.Database.Extensions; + +/// +/// The messages of the checks on a parameter's name: one text for each fact, +/// used by every place that makes the check. +/// +internal static class ParameterNameMessages +{ + /// A parameter's name is empty or white space. + public const string Blank + = "Parameter names cannot be empty or white space. " + + "Pass the name of a parameter of the command."; + + /// A parameter other than a return parameter has no name. + public const string NullOnlyForReturn + = "Parameter names can only be null for a return parameter."; +} diff --git a/Source/Core/DbQueryCall.cs b/Source/Core/DbQueryCall.cs index d62b0709..b749d75e 100644 --- a/Source/Core/DbQueryCall.cs +++ b/Source/Core/DbQueryCall.cs @@ -168,11 +168,7 @@ DbQueryCall Bound() } internal static string CheckedName(string name) - => CheckedText( - name, - nameof(name), - "Parameter names cannot be empty or white space. " - + "Pass the name of a parameter of the command."); + => CheckedText(name, nameof(name), ParameterNameMessages.Blank); /// Checks a text that must be given and not blank. /// The text. diff --git a/Source/Core/ExpressiveCommandBase.Param.cs b/Source/Core/ExpressiveCommandBase.Param.cs index b2dd453d..505a5864 100644 --- a/Source/Core/ExpressiveCommandBase.Param.cs +++ b/Source/Core/ExpressiveCommandBase.Param.cs @@ -32,12 +32,7 @@ public Param( { if (name is null) throw new ArgumentNullException(nameof(name)); if (string.IsNullOrWhiteSpace(name)) - { - throw new ArgumentException( - "Parameter names cannot be empty or white space. " - + "Pass the name of a parameter of the command.", - nameof(name)); - } + throw new ArgumentException(ParameterNameMessages.Blank, nameof(name)); Contract.EndContractBlock(); Name = name; diff --git a/Source/Core/Extensions/Command.AddParameter.cs b/Source/Core/Extensions/Command.AddParameter.cs index f51759b1..152db228 100644 --- a/Source/Core/Extensions/Command.AddParameter.cs +++ b/Source/Core/Extensions/Command.AddParameter.cs @@ -2,12 +2,6 @@ public static partial class CommandExtensions { - private const string ParameterNamesNotEmptyMessage - = "Parameter names cannot be empty or white space. " - + "Pass the name of a parameter of the command."; - private const string ParameterNamesOnlyNullForReturn - = "Parameter names can only be null for a return parameter."; - /// /// Adds a parameter with the given name and value to the command, leaving the provider to infer the database type from the value. /// @@ -27,7 +21,7 @@ public static IDbDataParameter AddParameter( if (name is null) throw new ArgumentNullException(nameof(name)); else if (string.IsNullOrWhiteSpace(name)) - throw new ArgumentException(ParameterNamesNotEmptyMessage, nameof(name)); + throw new ArgumentException(ParameterNameMessages.Blank, nameof(name)); Contract.EndContractBlock(); IDbDataParameter c = target.CreateParameter(); @@ -173,9 +167,9 @@ public static IDbDataParameter AddParameterType( if (target is null) throw new ArgumentNullException(nameof(target)); if (direction != ParameterDirection.ReturnValue && name == null) - throw new ArgumentNullException(nameof(name), ParameterNamesOnlyNullForReturn); + throw new ArgumentNullException(nameof(name), ParameterNameMessages.NullOnlyForReturn); else if (name != null && string.IsNullOrWhiteSpace(name)) - throw new ArgumentException(ParameterNamesNotEmptyMessage, nameof(name)); + throw new ArgumentException(ParameterNameMessages.Blank, nameof(name)); Contract.EndContractBlock(); IDbDataParameter c = target.CreateParameter(); diff --git a/Source/MSSqlClient/Extensions/Command.AddParameter.cs b/Source/MSSqlClient/Extensions/Command.AddParameter.cs index 6f6996ed..bba76c7e 100644 --- a/Source/MSSqlClient/Extensions/Command.AddParameter.cs +++ b/Source/MSSqlClient/Extensions/Command.AddParameter.cs @@ -46,16 +46,9 @@ public static SqlParameter AddParameterType( { if (target is null) throw new ArgumentNullException(nameof(target)); if (direction != ParameterDirection.ReturnValue && name == null) - { - throw new ArgumentNullException(nameof(name), "Parameter names can only be null for a return parameter."); - } + throw new ArgumentNullException(nameof(name), ParameterNameMessages.NullOnlyForReturn); else if (name != null && string.IsNullOrWhiteSpace(name)) - { - throw new ArgumentException( - "Parameter names cannot be empty or white space. " - + "Pass the name of a parameter of the command.", - nameof(name)); - } + throw new ArgumentException(ParameterNameMessages.Blank, nameof(name)); Contract.EndContractBlock(); SqlParameter c = target.CreateParameter(); diff --git a/Source/SqlClient/Extensions/Command.AddParameter.cs b/Source/SqlClient/Extensions/Command.AddParameter.cs index 718bd840..5b124beb 100644 --- a/Source/SqlClient/Extensions/Command.AddParameter.cs +++ b/Source/SqlClient/Extensions/Command.AddParameter.cs @@ -46,16 +46,9 @@ public static SqlParameter AddParameterType( { if (target is null) throw new ArgumentNullException(nameof(target)); if (direction != ParameterDirection.ReturnValue && name == null) - { - throw new ArgumentNullException(nameof(name), "Parameter names can only be null for a return parameter."); - } + throw new ArgumentNullException(nameof(name), ParameterNameMessages.NullOnlyForReturn); else if (name != null && string.IsNullOrWhiteSpace(name)) - { - throw new ArgumentException( - "Parameter names cannot be empty or white space. " - + "Pass the name of a parameter of the command.", - nameof(name)); - } + throw new ArgumentException(ParameterNameMessages.Blank, nameof(name)); Contract.EndContractBlock(); SqlParameter c = target.CreateParameter(); From 8e30af8dc30f5bb73e80dddfb55d56f64f75f2c3 Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Thu, 3 Dec 2026 15:56:34 -0800 Subject: [PATCH 11/11] Keep each name and message of production code as one constant, and have the tests reference it The blank command message now lives once in a Core constant that the command text check and its tests both use, and the parameter name message the tests used to copy is now referenced from its constant. The schema column names the procedure parameter reads used (parameter name, ordinal position, specific schema, parameter mode, numeric scale) are constants beside the collection name, so the metadata reads, the name reads and the tests all name them from one place. The concurrent-use message a connection source test copied is referenced from its constant as well. The four hand-built stub tables of the procedure parameter collection are one test helper. The tests behave as before; the output metadata stub gains an unread procedure name column so that it shares the helper. CONTRIBUTING.md says that a test does not copy a production name or message into its own constant but references the internal one. No message text changed and there is no run-time change. Co-Authored-By: Claude Sonnet 5.5 --- CONTRIBUTING.md | 2 +- Source/Core/Core/CommandTextMessages.cs | 13 ++++++ Source/Core/DbQuery.cs | 6 +-- Source/Core/ProcedureParameterMetadata.cs | 16 ++++---- Source/Core/ProcedureSchemaNames.cs | 41 ++++++++++++++++--- .../ConnectionSourceScopeTests.cs | 6 +-- .../DbQueryChecksTests.cs | 15 ++----- .../DbQueryProcedureNamesTests.cs | 7 +--- .../OutputMetadataTests.cs | 29 +++++++------ .../ProcedureSchemaNamesTests.cs | 14 ++----- .../TestHelpers/ProcedureParametersTable.cs | 36 ++++++++++++++++ 11 files changed, 121 insertions(+), 64 deletions(-) create mode 100644 Source/Core/Core/CommandTextMessages.cs create mode 100644 Tests/Open.Database.Extensions.Core.Tests/TestHelpers/ProcedureParametersTable.cs diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 77a4a70e..78fde702 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -23,7 +23,7 @@ How code gets into Open.Database.Extensions (ODX): the code rules a reviewer che - **Every exception says what is wrong and what to do.** Name the object or parameter, the cause, and the fix ("Call the query's terminal first, then await the capture."). - **Guard once, at the public entry point,** with the right parameter name. Internal code trusts it and uses `Debug.Assert`. Our code never throws `NullReferenceException`. -- **One text for each fact.** A message that says the same thing in more than one place is one `const` in Core (an `internal` class is visible to the provider packages), referenced everywhere, and a message passed as an argument is that named constant, not an inline concatenation. Messages that differ on purpose, because each names its own call site, stay separate. +- **One text for each fact.** A message that says the same thing in more than one place is one `const` in Core (an `internal` class is visible to the provider packages), referenced everywhere, and a message passed as an argument is that named constant, not an inline concatenation. Messages that differ on purpose, because each names its own call site, stay separate. A name or message of production code is never copied, either: a test does not put one into a constant of its own, it references the `internal` constant (the test project sees the internals of Core). - **A misuse the compiler can catch is a compile error,** not a runtime throw, when that costs little API. ### Performance diff --git a/Source/Core/Core/CommandTextMessages.cs b/Source/Core/Core/CommandTextMessages.cs new file mode 100644 index 00000000..84ec77d6 --- /dev/null +++ b/Source/Core/Core/CommandTextMessages.cs @@ -0,0 +1,13 @@ +namespace Open.Database.Extensions; + +/// +/// The messages of the checks on a command's text: one text for each fact, +/// used by every place that makes the check. +/// +internal static class CommandTextMessages +{ + /// A command's text is empty or white space. + public const string Blank + = "The command cannot be empty or white space. " + + "Pass the SQL text or the name of the stored procedure."; +} diff --git a/Source/Core/DbQuery.cs b/Source/Core/DbQuery.cs index 6e2ae34d..403edb8f 100644 --- a/Source/Core/DbQuery.cs +++ b/Source/Core/DbQuery.cs @@ -188,11 +188,7 @@ public static DbQuery Procedure(string name) // The one check of a command text (a definition's, and a command's). internal static string Checked(string text, string paramName) - => DbQueryCall.CheckedText( - text, - paramName, - "The command cannot be empty or white space. " - + "Pass the SQL text or the name of the stored procedure."); + => DbQueryCall.CheckedText(text, paramName, CommandTextMessages.Blank); /// /// Returns a new definition with the command timeout set; diff --git a/Source/Core/ProcedureParameterMetadata.cs b/Source/Core/ProcedureParameterMetadata.cs index e1f3f400..70ead396 100644 --- a/Source/Core/ProcedureParameterMetadata.cs +++ b/Source/Core/ProcedureParameterMetadata.cs @@ -148,14 +148,14 @@ or ArgumentException static ParameterMetadata ReadRows(DataTable table, NameSet names) { DataColumnCollection columns = table.Columns; - bool hasMode = columns.Contains("PARAMETER_MODE"); - bool hasScale = columns.Contains("NUMERIC_SCALE"); - if (!columns.Contains("PARAMETER_NAME") || !hasMode && !hasScale) + bool hasMode = columns.Contains(ProcedureSchemaNames.ParameterModeColumn); + bool hasScale = columns.Contains(ProcedureSchemaNames.NumericScaleColumn); + if (!columns.Contains(ProcedureSchemaNames.ParameterNameColumn) || !hasMode && !hasScale) { return ParameterMetadata.Unknown; } - bool hasOrdinal = columns.Contains("ORDINAL_POSITION"); + bool hasOrdinal = columns.Contains(ProcedureSchemaNames.OrdinalPositionColumn); int count = names.Names.Length; bool[] modeIn = new bool[count]; int[] scales = new int[count]; @@ -166,9 +166,9 @@ static ParameterMetadata ReadRows(DataTable table, NameSet names) { // The ordinal 0 row is the return value, never a declared // parameter. - if (hasOrdinal && IsReturnRow(row["ORDINAL_POSITION"])) continue; + if (hasOrdinal && IsReturnRow(row[ProcedureSchemaNames.OrdinalPositionColumn])) continue; - if (row["PARAMETER_NAME"] is not string { Length: > 0 } name + if (row[ProcedureSchemaNames.ParameterNameColumn] is not string { Length: > 0 } name || names.Find(name) is not { } entry || seen[entry.Index]) { @@ -180,9 +180,9 @@ static ParameterMetadata ReadRows(DataTable table, NameSet names) // Only the exact mode IN counts; INOUT (an OUTPUT parameter on SQL // Server), OUT, anything unexpected and a missing value do not. modeIn[entry.Index] = hasMode - && row["PARAMETER_MODE"] is string mode + && row[ProcedureSchemaNames.ParameterModeColumn] is string mode && string.Equals(mode, "IN", StringComparison.Ordinal); - if (hasScale) scales[entry.Index] = ScaleOf(row["NUMERIC_SCALE"]); + if (hasScale) scales[entry.Index] = ScaleOf(row[ProcedureSchemaNames.NumericScaleColumn]); } return any diff --git a/Source/Core/ProcedureSchemaNames.cs b/Source/Core/ProcedureSchemaNames.cs index c0ab2d02..7bd03edb 100644 --- a/Source/Core/ProcedureSchemaNames.cs +++ b/Source/Core/ProcedureSchemaNames.cs @@ -16,6 +16,37 @@ static class ProcedureSchemaNames /// public const string Collection = "ProcedureParameters"; + /// + /// The column of the collection with a parameter's name. + /// + public const string ParameterNameColumn + = "PARAMETER_NAME"; + + /// + /// The column of the collection with a parameter's position, 0 for the + /// return value. + /// + public const string OrdinalPositionColumn + = "ORDINAL_POSITION"; + + /// + /// The column of the collection with the schema of the procedure. + /// + public const string SpecificSchemaColumn + = "SPECIFIC_SCHEMA"; + + /// + /// The column of the collection with a parameter's mode. + /// + public const string ParameterModeColumn + = "PARAMETER_MODE"; + + /// + /// The column of the collection with a parameter's numeric scale. + /// + public const string NumericScaleColumn + = "NUMERIC_SCALE"; + /// /// Gets the names of the parameters a stored procedure declares. /// @@ -176,17 +207,17 @@ static ImmutableArray Names(DataTable? table, bool schemaGiven) if (table is null) return default; DataColumnCollection columns = table.Columns; - if (!columns.Contains("PARAMETER_NAME") || !columns.Contains("ORDINAL_POSITION")) return default; + if (!columns.Contains(ParameterNameColumn) || !columns.Contains(OrdinalPositionColumn)) return default; if (!schemaGiven && SpansSchemas(table)) return default; List> found = []; foreach (DataRow row in table.Rows) { - if (row["PARAMETER_NAME"] is not string { Length: > 0 } name || row["ORDINAL_POSITION"] is DBNull) continue; + if (row[ParameterNameColumn] is not string { Length: > 0 } name || row[OrdinalPositionColumn] is DBNull) continue; // A value that is not a number that fits is not known, as the metadata read of the column treats it. - if (!ProcedureParameterMetadata.TryInt(row["ORDINAL_POSITION"], out int ordinal)) continue; + if (!ProcedureParameterMetadata.TryInt(row[OrdinalPositionColumn], out int ordinal)) continue; if (ordinal > 0) found.Add(new(ordinal, name)); } @@ -203,12 +234,12 @@ static ImmutableArray Names(DataTable? table, bool schemaGiven) // ambiguous. public static bool SpansSchemas(DataTable table) { - if (!table.Columns.Contains("SPECIFIC_SCHEMA")) return false; + if (!table.Columns.Contains(SpecificSchemaColumn)) return false; string? schema = null; foreach (DataRow row in table.Rows) { - string current = row["SPECIFIC_SCHEMA"] as string ?? ""; + string current = row[SpecificSchemaColumn] as string ?? ""; schema ??= current; if (!string.Equals( schema, current, diff --git a/Tests/Open.Database.Extensions.Core.Tests/ConnectionSourceScopeTests.cs b/Tests/Open.Database.Extensions.Core.Tests/ConnectionSourceScopeTests.cs index 22d44906..44025443 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/ConnectionSourceScopeTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/ConnectionSourceScopeTests.cs @@ -305,10 +305,8 @@ public static void APoolOfOneConnection_TakenTwice_SaysWhatIsWrongAndTheFix() InvalidOperationException ex = Assert.Throws(pool.Take); Assert.Equal( - "Concurrent use of a single connection is not supported. " - + "Wait for the running call to finish, " - + "or create the command from a connection factory or pool " - + "so each call gets its own connection.", + Open.Database.Extensions.Core.DbConnectionProvider + .ConcurrentUseMessage, ex.Message); } diff --git a/Tests/Open.Database.Extensions.Core.Tests/DbQueryChecksTests.cs b/Tests/Open.Database.Extensions.Core.Tests/DbQueryChecksTests.cs index 1b4055af..cf45d317 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/DbQueryChecksTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/DbQueryChecksTests.cs @@ -11,13 +11,6 @@ namespace Open.Database.Extensions.Tests; [ExcludeFromCodeCoverage] public static class DbQueryChecksTests { - const string BlankName - = "Parameter names cannot be empty or white space. " - + "Pass the name of a parameter of the command."; - const string BlankCommand - = "The command cannot be empty or white space. " - + "Pass the SQL text or the name of the stored procedure."; - static CancellationToken Token => TestContext.Current.CancellationToken; // The message of an argument exception, without the argument name the framework appends to it (" (Parameter 'name')"). @@ -35,7 +28,7 @@ public static void DbQueryText_ABlankCommand_IsRefused_WithItsMessageAndName(str { ArgumentException ex = Assert.Throws(() => DbQuery.Text(text)); Assert.Equal("sql", ex.ParamName); - Assert.Equal(BlankCommand, Text(ex)); + Assert.Equal(CommandTextMessages.Blank, Text(ex)); } [Fact] @@ -52,7 +45,7 @@ public static void DbQueryProcedure_ABlankName_IsRefused_WithTheCommandMessage(s { ArgumentException ex = Assert.Throws(() => DbQuery.Procedure(name)); Assert.Equal("name", ex.ParamName); - Assert.Equal(BlankCommand, Text(ex)); + Assert.Equal(CommandTextMessages.Blank, Text(ex)); } [Fact] @@ -84,7 +77,7 @@ public static void AParamName_Blank_IsRefused_OnEveryFormOfTheCall(string name) { ArgumentException ex = Assert.Throws(add); Assert.Equal("name", ex.ParamName); - Assert.Equal(BlankName, Text(ex)); + Assert.Equal(ParameterNameMessages.Blank, Text(ex)); } } @@ -125,7 +118,7 @@ public static void ACommandText_Blank_IsRefused_ByEveryConstructorWithItsMessage { ArgumentException ex = Assert.Throws(make); Assert.Equal("command", ex.ParamName); - Assert.Equal(BlankCommand, Text(ex)); + Assert.Equal(CommandTextMessages.Blank, Text(ex)); } } diff --git a/Tests/Open.Database.Extensions.Core.Tests/DbQueryProcedureNamesTests.cs b/Tests/Open.Database.Extensions.Core.Tests/DbQueryProcedureNamesTests.cs index b1297371..7befdd0c 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/DbQueryProcedureNamesTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/DbQueryProcedureNamesTests.cs @@ -35,12 +35,7 @@ protected override DbCommand CreateDbCommand() public override DataTable GetSchema(string collectionName, string?[] restrictionValues) { SchemaCalls++; - var table = new DataTable("ProcedureParameters"); - table.Columns.Add("SPECIFIC_SCHEMA", typeof(string)); - table.Columns.Add("SPECIFIC_NAME", typeof(string)); - table.Columns.Add("ORDINAL_POSITION", typeof(int)); - table.Columns.Add("PARAMETER_NAME", typeof(string)); - return table; + return ProcedureParametersTable.Create(); } } diff --git a/Tests/Open.Database.Extensions.Core.Tests/OutputMetadataTests.cs b/Tests/Open.Database.Extensions.Core.Tests/OutputMetadataTests.cs index 4dc085bb..0700c16f 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/OutputMetadataTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/OutputMetadataTests.cs @@ -129,15 +129,18 @@ sealed class NamedPooledCommand(IDbConnectionPool pool, string pro // The columns of the collection that matter. A row: schema, ordinal, mode, name, scale. static DataTable Table(params (string Schema, int Ordinal, string? Mode, string Name, object? Scale)[] rows) { - var table = new DataTable("ProcedureParameters"); - table.Columns.Add("SPECIFIC_SCHEMA", typeof(string)); - table.Columns.Add("ORDINAL_POSITION", typeof(int)); - table.Columns.Add("PARAMETER_MODE", typeof(string)); - table.Columns.Add("PARAMETER_NAME", typeof(string)); - table.Columns.Add("NUMERIC_SCALE", typeof(object)); + DataTable table = ProcedureParametersTable.Create(); + table.Columns.Add( + ProcedureSchemaNames.ParameterModeColumn, + typeof(string)); + table.Columns.Add( + ProcedureSchemaNames.NumericScaleColumn, + typeof(object)); foreach ((string schema, int ordinal, string? mode, string name, object? scale) in rows) { - table.Rows.Add(schema, ordinal, mode ?? (object)DBNull.Value, name, scale ?? DBNull.Value); + table.Rows.Add( + schema, "proc", ordinal, name, + mode ?? (object)DBNull.Value, scale ?? DBNull.Value); } return table; @@ -537,14 +540,14 @@ public static async Task AParameterWithNoRow_IsNotModeInAndHasNoScale() public static async Task AMissingScaleColumn_StillGivesTheMode_AndAMissingModeColumn_StillGivesTheScale() { DataTable noScale = One("IN"); - noScale.Columns.Remove("NUMERIC_SCALE"); + noScale.Columns.Remove(ProcedureSchemaNames.NumericScaleColumn); ParameterMetadata mode = await Read(noScale, "@total"); Assert.True(mode.IsKnown); Assert.True(mode.IsModeIn(0)); Assert.Equal(ParameterMetadata.NoScale, mode.Scale(0)); DataTable noMode = One("IN", 3); - noMode.Columns.Remove("PARAMETER_MODE"); + noMode.Columns.Remove(ProcedureSchemaNames.ParameterModeColumn); ParameterMetadata scale = await Read(noMode, "@total"); Assert.True(scale.IsKnown); Assert.False(scale.IsModeIn(0)); @@ -555,7 +558,7 @@ public static async Task AMissingScaleColumn_StillGivesTheMode_AndAMissingModeCo public static async Task AMissingOrdinalColumn_MatchesByNameOnly() { DataTable table = One("IN", 2); - table.Columns.Remove("ORDINAL_POSITION"); + table.Columns.Remove(ProcedureSchemaNames.OrdinalPositionColumn); ParameterMetadata metadata = await Read(table, "@total"); @@ -566,10 +569,10 @@ public static async Task AMissingOrdinalColumn_MatchesByNameOnly() public static async Task NothingUsable_IsUnknown_AndKept() { DataTable noMode = One("IN", 3); - noMode.Columns.Remove("PARAMETER_MODE"); - noMode.Columns.Remove("NUMERIC_SCALE"); + noMode.Columns.Remove(ProcedureSchemaNames.ParameterModeColumn); + noMode.Columns.Remove(ProcedureSchemaNames.NumericScaleColumn); DataTable noName = One("IN", 3); - noName.Columns.Remove("PARAMETER_NAME"); + noName.Columns.Remove(ProcedureSchemaNames.ParameterNameColumn); Assert.Same(ParameterMetadata.Unknown, await Read(noMode, "@total")); Assert.Same(ParameterMetadata.Unknown, await Read(noName, "@total")); diff --git a/Tests/Open.Database.Extensions.Core.Tests/ProcedureSchemaNamesTests.cs b/Tests/Open.Database.Extensions.Core.Tests/ProcedureSchemaNamesTests.cs index 2119d452..f2bdfabd 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/ProcedureSchemaNamesTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/ProcedureSchemaNamesTests.cs @@ -61,11 +61,7 @@ public override Task GetSchemaAsync( // The columns of INFORMATION_SCHEMA.PARAMETERS that matter: a row per parameter, ordinal 0 is the return value. static DataTable Table(params object?[][] rows) { - var table = new DataTable("ProcedureParameters"); - table.Columns.Add("SPECIFIC_SCHEMA", typeof(string)); - table.Columns.Add("SPECIFIC_NAME", typeof(string)); - table.Columns.Add("ORDINAL_POSITION", typeof(int)); - table.Columns.Add("PARAMETER_NAME", typeof(string)); + DataTable table = ProcedureParametersTable.Create(); foreach (object?[] row in rows) table.Rows.Add([.. row.Select(v => v ?? DBNull.Value)]); return table; } @@ -106,7 +102,7 @@ public static void TheNamesOfTheSchemaCollection_AreMatched_ReturnValueSkipped_I Assert.Equal(["@order_id", "@p_name"], Run(connection, Proc(), c => c.AddParam(orderId).AddParam(name))); Assert.Equal([5, "ann"], connection.Command.Sent.Select(p => p.Value)); Assert.Equal(1, connection.SchemaCalls); - Assert.Equal("ProcedureParameters", connection.Collection); + Assert.Equal(ProcedureSchemaNames.Collection, connection.Collection); } [Fact] @@ -250,11 +246,7 @@ public static void ATableWithoutParameters_IsNotKnown_AndRememberedForAShortWhil public static void ARowWhoseOrdinalIsNotANumberThatFits_IsSkipped_AndTheCallDoesNotFail(object badOrdinal) { const int orderId = 5; - var table = new DataTable("ProcedureParameters"); - table.Columns.Add("SPECIFIC_SCHEMA", typeof(string)); - table.Columns.Add("SPECIFIC_NAME", typeof(string)); - table.Columns.Add("ORDINAL_POSITION", typeof(object)); - table.Columns.Add("PARAMETER_NAME", typeof(string)); + DataTable table = ProcedureParametersTable.Create(typeof(object)); table.Rows.Add("dbo", "proc", 1, "@order_id"); table.Rows.Add("dbo", "proc", badOrdinal, "@p_name"); var connection = new SchemaConnection(table, null); diff --git a/Tests/Open.Database.Extensions.Core.Tests/TestHelpers/ProcedureParametersTable.cs b/Tests/Open.Database.Extensions.Core.Tests/TestHelpers/ProcedureParametersTable.cs new file mode 100644 index 00000000..1831fcdb --- /dev/null +++ b/Tests/Open.Database.Extensions.Core.Tests/TestHelpers/ProcedureParametersTable.cs @@ -0,0 +1,36 @@ +namespace Open.Database.Extensions.Tests; + +#nullable enable + +/// +/// The stub of the ProcedureParameters schema collection that the +/// fake providers answer with: an empty table with the columns of the +/// collection that the library reads, for a test to add rows to. +/// +[ExcludeFromCodeCoverage] +internal static class ProcedureParametersTable +{ + /// + /// Creates the empty table, with the columns schema, procedure name, + /// ordinal and parameter name, in that order. + /// + /// + /// The type of the ordinal column; when not given. + /// + /// The table. + public static DataTable Create(Type? ordinalType = null) + { + var table = new DataTable(ProcedureSchemaNames.Collection); + table.Columns.Add( + ProcedureSchemaNames.SpecificSchemaColumn, + typeof(string)); + table.Columns.Add("SPECIFIC_NAME", typeof(string)); + table.Columns.Add( + ProcedureSchemaNames.OrdinalPositionColumn, + ordinalType ?? typeof(int)); + table.Columns.Add( + ProcedureSchemaNames.ParameterNameColumn, + typeof(string)); + return table; + } +}