diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index f818eb94..78fde702 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 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/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/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/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/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/DbQueryCall.cs b/Source/Core/DbQueryCall.cs index d6b87780..b749d75e 100644 --- a/Source/Core/DbQueryCall.cs +++ b/Source/Core/DbQueryCall.cs @@ -168,10 +168,7 @@ DbQueryCall Bound() } internal static string CheckedName(string name) - => CheckedText( - name, - nameof(name), - "Parameter names cannot be empty or white space."); + => 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 7a38205f..505a5864 100644 --- a/Source/Core/ExpressiveCommandBase.Param.cs +++ b/Source/Core/ExpressiveCommandBase.Param.cs @@ -32,7 +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.", nameof(name)); + throw new ArgumentException(ParameterNameMessages.Blank, nameof(name)); Contract.EndContractBlock(); Name = name; 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/Extensions/Command.AddParameter.cs b/Source/Core/Extensions/Command.AddParameter.cs index f683ddbb..152db228 100644 --- a/Source/Core/Extensions/Command.AddParameter.cs +++ b/Source/Core/Extensions/Command.AddParameter.cs @@ -2,9 +2,6 @@ public static partial class CommandExtensions { - private const string ParameterNamesNotEmptyMessage = "Parameter names cannot be empty or white space."; - 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. /// @@ -24,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(); @@ -170,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/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)); } /// diff --git a/Source/Core/ProcedureParameterMetadata.cs b/Source/Core/ProcedureParameterMetadata.cs index cede113b..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 @@ -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..7bd03edb 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; @@ -17,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. /// @@ -177,16 +207,18 @@ 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[OrdinalPositionColumn], out int ordinal)) continue; - int ordinal = Convert.ToInt32(row["ORDINAL_POSITION"], CultureInfo.InvariantCulture); if (ordinal > 0) found.Add(new(ordinal, name)); } @@ -202,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/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/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. 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; } diff --git a/Source/MSSqlClient/Extensions/Command.AddParameter.cs b/Source/MSSqlClient/Extensions/Command.AddParameter.cs index 393c0699..bba76c7e 100644 --- a/Source/MSSqlClient/Extensions/Command.AddParameter.cs +++ b/Source/MSSqlClient/Extensions/Command.AddParameter.cs @@ -46,9 +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.", 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 fbf53103..5b124beb 100644 --- a/Source/SqlClient/Extensions/Command.AddParameter.cs +++ b/Source/SqlClient/Extensions/Command.AddParameter.cs @@ -46,9 +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.", nameof(name)); + throw new ArgumentException(ParameterNameMessages.Blank, nameof(name)); Contract.EndContractBlock(); SqlParameter c = target.CreateParameter(); 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 016f49e3..cf45d317 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/DbQueryChecksTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/DbQueryChecksTests.cs @@ -11,11 +11,6 @@ namespace Open.Database.Extensions.Tests; [ExcludeFromCodeCoverage] public static class DbQueryChecksTests { - const string BlankName = "Parameter names 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; // The message of an argument exception, without the argument name the framework appends to it (" (Parameter 'name')"). @@ -33,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] @@ -50,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] @@ -82,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)); } } @@ -123,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 f1f51121..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] @@ -236,6 +232,29 @@ 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; + 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); + + 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/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; + } +} 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(); } } diff --git a/docsite/articles/release-notes.md b/docsite/articles/release-notes.md index 1b7cbe58..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.