From 6c21cd083e5c51597e47a0c265911da3a96b3b0f Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Fri, 4 Dec 2026 08:30:31 -0800 Subject: [PATCH 1/9] Make AnyAsync and CountAsync of a command with no model one line each AnyAsync and CountAsync on a command with no model built the query core with the object-array row source themselves and called its terminal. They now call AsObjectArrays() and its AnyAsync and CountAsync, which build the same core, so each body is one expression and the null check on the command is the one AsObjectArrays already makes (same exception type, same parameter name, "command"). The comment that says why the row source is never asked for a mapper stays, reworded to say that the work goes through AsObjectArrays(). Run-time cost: a MappedQuery wrapper struct is created and its terminal forwards to the core. A benchmark of AnyAsync and CountAsync before and after showed no gap worth keeping the longer body for. The Core tests for AnyAsync, CountAsync and the object-array views pass (72). Co-Authored-By: Claude Sonnet 5.5 --- Source/Core/AnyCount.cs | 21 ++++++--------------- 1 file changed, 6 insertions(+), 15 deletions(-) diff --git a/Source/Core/AnyCount.cs b/Source/Core/AnyCount.cs index 0ff0b454..515ebe36 100644 --- a/Source/Core/AnyCount.cs +++ b/Source/Core/AnyCount.cs @@ -17,17 +17,12 @@ public static partial class CoreExtensions /// Cancels the call, together with the cancellation token set on the command. /// A task that produces if there is a row; otherwise, . /// is . - // The query core of a mapped query does the work; its row source is never asked for a mapper. + // Through AsObjectArrays(), which checks the command: + // the query core of a mapped query does the work; its row source is never asked for a mapper. public static ValueTask AnyAsync( this IExecuteReader command, CancellationToken cancellationToken = default) - { - if (command is null) throw new ArgumentNullException(nameof(command)); - Contract.EndContractBlock(); - - return Views.QueryCore(command, ObjectArraySource.Instance) - .AnyAsync(cancellationToken); - } + => command.AsObjectArrays().AnyAsync(cancellationToken); /// /// Asynchronously counts the rows the query returns, with no model to map them to. @@ -44,14 +39,10 @@ public static ValueTask AnyAsync( /// A task that produces the number of rows. /// is . /// There are more than rows. + // Through AsObjectArrays(), which checks the command: + // the query core of a mapped query does the work; its row source is never asked for a mapper. public static ValueTask CountAsync( this IExecuteReader command, CancellationToken cancellationToken = default) - { - if (command is null) throw new ArgumentNullException(nameof(command)); - Contract.EndContractBlock(); - - return Views.QueryCore(command, ObjectArraySource.Instance) - .CountAsync(cancellationToken); - } + => command.AsObjectArrays().CountAsync(cancellationToken); } From a756426c44cc8eb914659223c697a96d4b9560c0 Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Fri, 4 Dec 2026 08:40:11 -0800 Subject: [PATCH 2/9] Run the LegacyCompiler tests one target framework at a time The legacy-compiler job ran `dotnet test` with no target framework, which builds and runs all four targets (net8.0, net10.0, net472, net11.0) at the same moment. On the runner the three test hosts that are not net11.0 twice failed to connect within 90 seconds, and the test code never ran for them; both runs passed when re-run. The step now builds the project once, reads its target frameworks from the project (so the list cannot drift from the .csproj), and runs `dotnet test --no-build -f ` for each one in sequence, with its own TRX file prefix so no file overwrites another. Every target runs even if one fails, each failure is reported, and the step fails at the end if any target failed. `dotnet test --no-build -f` exits 0 and runs nothing for a target that was not built, so a target that wrote no TRX file counts as a failure too. There is no retry and no longer connection timeout: a host that cannot connect still fails the step. Cost: three more test host starts per run (tens of seconds), no contention between them. The loop was run locally on all four targets (46, 46, 46 and 48 tests pass, exit 0) and with an extra unknown target (the step fails, naming it, after the four real ones ran). Co-Authored-By: Claude Sonnet 5.5 --- .github/workflows/tests.yml | 29 ++++++++++++++++++++++++++--- 1 file changed, 26 insertions(+), 3 deletions(-) diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 2e70c6e0..db9057b4 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -2,7 +2,7 @@ name: Tests # Runs the Core test suite on every pull request and every push to master, and checks the packages for known vulnerabilities. # The suite runs on net11.0 in Release and in Debug (Debug.Assert is live there). net10.0 is still built and shipped; its tests run only where it differs (the LegacyCompiler job). -# A separate job runs the LegacyCompiler tests, which compile the public call shapes with older C# language versions. +# A separate job runs the LegacyCompiler tests, which compile the public call shapes with older C# language versions (one target framework at a time). # Another runs the source generator's tests and the package consumer tests (see its steps). # Another job builds the Benchmarks project (it is not in the solution), so a change to the public API cannot leave its call sites behind. # Another runs `dotnet format` style and analyzers at info severity on every project, which is what the IDE shows. @@ -102,9 +102,32 @@ jobs: 11.0.x # This project compiles the public call shapes with the older C# language versions that consumers still use, one per target framework - # (see its .csproj), so a binding regression on an older compiler fails here. No -f: it runs every target framework the project has. + # (see its .csproj), so a binding regression on an older compiler fails here. + # It is built once, then each target framework runs on its own, one after the other: `dotnet test` with no -f starts a test host for every + # target at once, and the three that are not net11.0 twice failed to connect within 90 seconds on this runner. + # Every target runs even when one fails, so the step reports them all, and then fails if any did. - name: Run the LegacyCompiler tests - run: dotnet test Tests/Open.Database.Extensions.LegacyCompiler.Tests -c Release --logger "trx;LogFilePrefix=legacy-compiler" --results-directory TestResults/legacy-compiler + run: | + $project = 'Tests/Open.Database.Extensions.LegacyCompiler.Tests' + $frameworks = (dotnet msbuild $project -getProperty:TargetFrameworks) -split ';' | ForEach-Object { $_.Trim() } | Where-Object { $_ } + if ($LASTEXITCODE -ne 0 -or -not $frameworks) { throw "The target frameworks of $project could not be read." } + + dotnet build $project -c Release + if ($LASTEXITCODE -ne 0) { throw "dotnet build $project failed with exit code $LASTEXITCODE" } + + $failed = @() + $started = Get-Date + foreach ($framework in $frameworks) { + dotnet test $project -c Release --no-build -f $framework --logger "trx;LogFilePrefix=legacy-compiler-$framework" --results-directory TestResults/legacy-compiler + $exitCode = $LASTEXITCODE + # `dotnet test --no-build -f` exits 0 without running anything for a target framework that was not built, so a missing TRX file is a failure too. + $results = @(Get-ChildItem TestResults/legacy-compiler -Filter "legacy-compiler-${framework}_*.trx" -ErrorAction SilentlyContinue | Where-Object LastWriteTime -ge $started) + if ($exitCode -ne 0 -or -not $results) { + $failed += $framework + Write-Host "::error::The LegacyCompiler tests failed on $framework (exit code $exitCode, $($results.Count) result file(s))." + } + } + if ($failed) { throw "The LegacyCompiler tests failed on: $($failed -join ', ')." } - name: Upload the TRX files if: always() From 28a796415649810dbc01325d7ad4191777818778 Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Fri, 4 Dec 2026 08:55:13 -0800 Subject: [PATCH 3/9] Remove the protected PrepareCommand(TConnection) and ConnectionProvider of ExpressiveCommandBase Nothing in the library, its packages, the tests, the benchmarks or the documentation called or overrode either member. PrepareCommand(TConnection) only forwarded to the private PrepareCommand(TConnection, OutputRun?), which stays and which the one internal caller now calls directly. ConnectionProvider returned the pool, or a provider made around a bare connection, and no member read it; the field that cached that provider in the rarely-set options block is removed with it. The two shipped members are listed as removed in PublicAPI.Unshipped.txt, and the release notes say what was removed and that a subclass keeps its own reference to what it passed to the base constructor. Run-time cost: none; a command that is built the same way is built the same way. Co-Authored-By: Claude Sonnet 5.5 --- Source/Core/ExpressiveCommandBase.cs | 25 +------------------------ Source/Core/PublicAPI.Unshipped.txt | 2 ++ docsite/articles/release-notes.md | 1 + 3 files changed, 4 insertions(+), 24 deletions(-) diff --git a/Source/Core/ExpressiveCommandBase.cs b/Source/Core/ExpressiveCommandBase.cs index 8d99c587..7f160930 100644 --- a/Source/Core/ExpressiveCommandBase.cs +++ b/Source/Core/ExpressiveCommandBase.cs @@ -25,17 +25,6 @@ public abstract partial class ExpressiveCommandBase { - /// - /// Gets the pool that connections are taken from. - /// - /// The pool that connections are taken from. - /// - /// A command built on a bare connection gets a provider around that - /// connection, made on first use. - /// - protected IDbConnectionPool ConnectionProvider - => _poolOrConnection as IDbConnectionPool ?? (EnsureOptions().Provider ??= DbConnectionProvider.Create((TConnection)_poolOrConnection)); - /// /// The pool to take connections from or, for a command built from a bare /// connection, the connection itself. @@ -96,7 +85,6 @@ protected IDbConnectionPool ConnectionProvider private protected sealed class CommandOptions { public IDbTransaction? Transaction; - public IDbConnectionPool? Provider; public CancellationToken CancellationToken; public ushort Timeout = CommandTimeout.DEFAULT_SECONDS; public bool AsyncReads; @@ -283,17 +271,6 @@ public ushort Timeout } } - /// - /// Creates the expected command type from the connection provided. - /// - /// The connection to create the command from. - /// The new command to use. - /// - /// The connection creates a command that is not a . - /// - protected TCommand PrepareCommand(TConnection connection) - => PrepareCommand(connection, null); - /// /// Creates the command from the connection, with its parameters and, for a call that reads output parameters, those. /// @@ -1001,7 +978,7 @@ int ScannedCount() TCommand PrepareWritten(TConnection connection) => WrittenNames() is { } text ? PrepareDerived(connection, text, written: true) - : PrepareCommand(connection); + : PrepareCommand(connection, null); /// /// Builds the send list, sets up the command and resets, in one diff --git a/Source/Core/PublicAPI.Unshipped.txt b/Source/Core/PublicAPI.Unshipped.txt index ff19961a..c198b777 100644 --- a/Source/Core/PublicAPI.Unshipped.txt +++ b/Source/Core/PublicAPI.Unshipped.txt @@ -1,4 +1,6 @@ #nullable enable +*REMOVED*Open.Database.Extensions.ExpressiveCommandBase.ConnectionProvider.get -> Open.Database.Extensions.IDbConnectionPool! +*REMOVED*Open.Database.Extensions.ExpressiveCommandBase.PrepareCommand(TConnection! connection) -> TCommand! Open.Database.Extensions.Generation.GeneratedRowMap static Open.Database.Extensions.Generation.GeneratedRowMap.Create(System.Func?>! binder) -> Open.Database.Extensions.RowMap! Open.Database.Extensions.PooledBuffer.AsAsyncEnumerable(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Collections.Generic.IAsyncEnumerable! diff --git a/docsite/articles/release-notes.md b/docsite/articles/release-notes.md index 14a30e72..3746d84f 100644 --- a/docsite/articles/release-notes.md +++ b/docsite/articles/release-notes.md @@ -12,6 +12,7 @@ Version 11 is `11.0.0-rc.17`. For moving a 10.x codebase, read [Coming from earl - **Fixed: `UsingAsync` on a factory or a function disposes the connection asynchronously.** It called `Dispose`; a connection that implements `IAsyncDisposable` (every `DbConnection`) is now disposed with `DisposeAsync`, as the connection scopes do, and any other connection with `Dispose`. - **Changed: `AddReturnParameter` treats a blank name as no name.** The overload that takes a `DbType` (and the SQL Server one that takes a `SqlDbType`) threw `ArgumentException` for an empty or white-space name; like the overload without a type, it now adds an unnamed return parameter, as it does for `null`. - **Fixed: the name of the `ArgumentNullException` from `AsGeneric(IDbConnectionPool)`.** A `null` pool threw with the parameter name `source`; it is now `connectionPool`. +- **Removed: the protected `PrepareCommand(TConnection)` and `ConnectionProvider` of `ExpressiveCommandBase`.** Nothing in the library called either: `PrepareCommand` only forwarded to the private method that builds the command, and `ConnectionProvider` gave back the pool or a provider around the bare connection, which no member read. A class of your own that derives from `ExpressiveCommandBase` and called one of them no longer compiles. There is no replacement: a terminal builds the command when it runs, and a subclass that needs the connection, pool or factory keeps its own reference to what it passed to the base constructor. ### Changes since rc.16 From 5b0726176b2ec9f30f60776aae06f60e55637642 Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Fri, 4 Dec 2026 09:13:24 -0800 Subject: [PATCH 4/9] One internal const for each message, name and analyzer id that the code and its tests repeat A message, a name or an analyzer id that appeared more than once as a literal in Source and Tests is now one internal const (or one method, for a message with holes), and everything that used the text refers to it. Tests no longer copy a production message or name: they use the same const. No message text changed word for word; joined literals were only re-wrapped. New homes in Core, next to ParameterNameMessages and CommandTextMessages: AnalyzerIds and SuppressionJustifications (the SuppressMessage ids and the two reasons that repeat), TransactionMessages, ArgumentMessages, MappedDbQueryMessages and RowMapMessages (the checks on a type that a row map builds, which UnmappableTypeTests had copied whole). ParameterNameMessages gains the not-known, name-one-explicitly, not-supplied and tier texts; CommandTextMessages, CaptureMessages and OutputBinding gain one const each; ProcedureSchemaNames holds the SQL Server parameter-names query that the two SQL Server packages both wrote out. Four private consts that tests copied (ReaderAbandon.Option and the two attribute names in Shape) are public on their internal types. Repeats that stay are listed with the reason in the sweep notes: the same names written in the separate generator assembly, the documented AppContext switch name that a test pins on purpose, and test-owned text. Run-time cost: none on a hot path; the messages are built on the same failure paths as before, through a method instead of inline. Co-Authored-By: Claude Sonnet 5.5 --- Source/Core/Capture.cs | 22 ++++-- Source/Core/CaptureNames.cs | 2 +- Source/Core/ChunkConfig.cs | 2 +- Source/Core/ChunkProducer.cs | 2 +- Source/Core/Core/AnalyzerIds.cs | 40 ++++++++++ Source/Core/Core/ArgumentMessages.cs | 12 +++ Source/Core/Core/CancellationTokens.cs | 4 +- Source/Core/Core/CommandTextMessages.cs | 4 + Source/Core/Core/MappedDbQueryMessages.cs | 13 ++++ Source/Core/Core/ParameterNameMessages.cs | 38 +++++++++ Source/Core/Core/RowErrors.cs | 12 +-- Source/Core/Core/RowMap.cs | 28 +++---- Source/Core/Core/RowMapMessages.cs | 77 +++++++++++++++++++ Source/Core/Core/SuppressionJustifications.cs | 16 ++++ Source/Core/Core/TransactionMessages.cs | 14 ++++ Source/Core/DbQueryBinding.cs | 4 +- Source/Core/DbQueryCall.cs | 4 +- Source/Core/ExpressiveCommandBase.cs | 10 +-- .../Extensions/Connection.CreateCommand.cs | 4 +- Source/Core/Extensions/DataReader.cs | 2 +- .../Extensions/Transaction.CreateCommand.cs | 4 +- Source/Core/Extensions/Transaction.cs | 2 +- Source/Core/MappedDbQuery.cs | 5 +- Source/Core/MappedQuery.cs | 4 +- Source/Core/OutputBinding.cs | 18 +++-- Source/Core/OutputDbNonQuery.cs | 2 +- Source/Core/OutputLayout.cs | 12 ++- Source/Core/ParameterNames.cs | 12 +-- Source/Core/PooledArray.cs | 2 +- Source/Core/ProcedureSchemaNames.cs | 12 +++ Source/Core/ReaderAbandon.cs | 3 +- Source/Core/RecycleBin.cs | 2 +- Source/Core/StallStream.cs | 2 +- .../Synchronous/SyncTransactionExtensions.cs | 2 +- Source/Core/ValueMappingException.cs | 2 +- Source/MSSqlClient/ExpressiveSqlCommand.cs | 2 +- .../Extensions/Transaction.CreateCommand.cs | 2 +- Source/MSSqlClient/Extensions/Transaction.cs | 2 +- .../SyncSqlTransactionExtensions.cs | 2 +- Source/SqlClient/ExpressiveSqlCommand.cs | 2 +- .../Extensions/Connection.CreateCommand.cs | 4 +- .../Extensions/Transaction.CreateCommand.cs | 2 +- Source/SqlClient/Extensions/Transaction.cs | 2 +- .../SyncSqlTransactionExtensions.cs | 2 +- .../CancelOnEarlyStopStreamTests.cs | 4 +- .../CancelOnEarlyStopTests.cs | 2 +- .../CaptureNameLocalDbTests.cs | 8 +- .../CaptureTests.cs | 4 +- .../CommandExecuteFailureTests.cs | 2 +- .../ConstructorBindingTests.cs | 2 +- .../DbQueryBindingTests.cs | 2 +- .../DerivedNamesEveryRunCostTests.cs | 2 +- .../DerivedParameterNameTests.cs | 2 +- .../ExecuteScalarNullTests.cs | 2 +- .../GeneratedRowMapTests.cs | 2 +- .../LeakMatrixTests.cs | 4 +- .../MappedDbQueryTests.cs | 2 +- .../MappingCharacterizationTests.cs | 4 +- .../NullRuleRouteTests.cs | 2 +- .../OutputParameterTests.cs | 2 +- .../ParameterNameMessageTests.cs | 12 +-- .../PooledBufferAsAsyncEnumerableTests.cs | 2 +- .../ProcedureSchemaNamesTests.cs | 2 +- .../RequiredMemberTests.cs | 4 +- .../RowMapperTests.cs | 2 +- .../SqlServerPackageTests.cs | 4 +- .../TestHelpers/MultiSetReader.cs | 2 +- .../TestHelpers/NullAssert.cs | 3 +- .../UnmappableTypeTests.cs | 28 +++---- .../Harness.cs | 2 +- 70 files changed, 384 insertions(+), 137 deletions(-) create mode 100644 Source/Core/Core/AnalyzerIds.cs create mode 100644 Source/Core/Core/ArgumentMessages.cs create mode 100644 Source/Core/Core/MappedDbQueryMessages.cs create mode 100644 Source/Core/Core/RowMapMessages.cs create mode 100644 Source/Core/Core/SuppressionJustifications.cs create mode 100644 Source/Core/Core/TransactionMessages.cs diff --git a/Source/Core/Capture.cs b/Source/Core/Capture.cs index 163695a6..ea303946 100644 --- a/Source/Core/Capture.cs +++ b/Source/Core/Capture.cs @@ -305,15 +305,19 @@ protected override TValue Read(OutputRun call, int start) /// The type of the value. sealed class ReturnCapture() : CaptureSource( - $"CaptureReturn<{Shape.TypeName(typeof(TValue))}>", + Call(), CaptureKind.Return) { public override ImmutableArray Members { get; } = [new OutputMember( OutputLayout.ReturnValue, - $"CaptureReturn<{Shape.TypeName(typeof(TValue))}>", + Call(), named: true)]; + // How the messages name the call. + static string Call() + => $"CaptureReturn<{Shape.TypeName(typeof(TValue))}>"; + // As ExecuteReturnAsync(). protected override TValue Read(OutputRun call, int start) => RowMap.ConvertScalar(call.Value(start)); @@ -1010,6 +1014,14 @@ public static CaptureSource Return() /// static class CaptureMessages { + /// The async form of a query terminal, named in the message of a sync call. + public const string ToListInstead + = "ToListAsync instead of ToList"; + + /// The async form of a command terminal, named in the message of a sync call. + public const string ExecuteNonQueryInstead + = "ExecuteNonQueryAsync instead of ExecuteNonQuery"; + public static string NotStarted(string display) => $"{display} has not started: " + "the query it belongs to has not been run, " @@ -1039,8 +1051,8 @@ public static string Sync(CaptureSet set) => $"This {set.Noun} has {set.Displays}, " + "and captures only work with async terminals. " + $"Use the async form of this call (for example {(set.OnQuery - ? "ToListAsync instead of ToList" - : "ExecuteNonQueryAsync instead of ExecuteNonQuery")}), " + ? ToListInstead + : ExecuteNonQueryInstead)}), " + "or remove the capture."; public static string SecondRun(CaptureSet set) @@ -1057,7 +1069,7 @@ public static string SecondRun(CaptureSet set) + "to run it again."; } - [SuppressMessage("Roslynator", "RCS1047:Non-asynchronous method name should not end with 'Async'")] + [SuppressMessage("Roslynator", AnalyzerIds.RCS1047)] public static string ExecuteAsync(CaptureSet set) => $"{set.Displays} cannot be filled by ExecuteAsync(command => ...), " + "because your code runs the command. " diff --git a/Source/Core/CaptureNames.cs b/Source/Core/CaptureNames.cs index 474bb091..82f9de3f 100644 --- a/Source/Core/CaptureNames.cs +++ b/Source/Core/CaptureNames.cs @@ -123,7 +123,7 @@ static bool IsPlain(string text) // last argument of every capture call. [SuppressMessage( "Usage", - "CA2208:Instantiate argument exceptions correctly")] + AnalyzerIds.CA2208)] static ArgumentException NoName(string? text) => new( (text is null diff --git a/Source/Core/ChunkConfig.cs b/Source/Core/ChunkConfig.cs index fb5aaca4..6b2fb2db 100644 --- a/Source/Core/ChunkConfig.cs +++ b/Source/Core/ChunkConfig.cs @@ -63,7 +63,7 @@ internal sealed class ChunkConfig( // at 128 KB of references it is a tie. // Rows that hold no references are included: a large chunk of value rows is // cleared in the bin too. - [SuppressMessage("Roslynator", "RCS1158:Static member in generic type should use a type parameter", Justification = "The threshold is one number for every T: it is a member of the config so that each call site names the same constant (ChunkConfig.DefaultDeferFromClearedBytes).")] + [SuppressMessage("Roslynator", AnalyzerIds.RCS1158, Justification = "The threshold is one number for every T: it is a member of the config so that each call site names the same constant (ChunkConfig.DefaultDeferFromClearedBytes).")] public const int DefaultDeferFromClearedBytes = 131_072; /// Gets the pool the arrays come from and go back to. diff --git a/Source/Core/ChunkProducer.cs b/Source/Core/ChunkProducer.cs index c9824f34..541ceec6 100644 --- a/Source/Core/ChunkProducer.cs +++ b/Source/Core/ChunkProducer.cs @@ -169,7 +169,7 @@ public int Count /// A task that completes when the producer has ended (and the target has /// been finished). /// - [SuppressMessage("Roslynator", "RCS1229:Use async/await when necessary")] + [SuppressMessage("Roslynator", AnalyzerIds.RCS1229)] public Task Start() { if (caller.IsCancellationRequested) diff --git a/Source/Core/Core/AnalyzerIds.cs b/Source/Core/Core/AnalyzerIds.cs new file mode 100644 index 00000000..a7732752 --- /dev/null +++ b/Source/Core/Core/AnalyzerIds.cs @@ -0,0 +1,40 @@ +namespace Open.Database.Extensions; + +/// +/// The analyzer rules that the code suppresses: one text for each rule, +/// used by every place that suppresses it. +/// +internal static class AnalyzerIds +{ + /// Roslynator: an exception type does not implement the standard constructors. + public const string RCS1194 + = "RCS1194:Implement exception constructors"; + + /// Roslynator: a method with a name that ends in Async is not asynchronous. + public const string RCS1047 + = "RCS1047:Non-asynchronous method name should not end with 'Async'"; + + /// Roslynator: a method returns a task without async and await. + public const string RCS1229 + = "RCS1229:Use async/await when necessary"; + + /// Roslynator: a static member of a generic type does not use the type parameter. + public const string RCS1158 + = "RCS1158:Static member in generic type should use a type parameter"; + + /// Design: a parameter of the type CancellationToken is not the last. + public const string CA1068 + = "CA1068:CancellationToken parameters must come last"; + + /// Design: an exception type is not public. + public const string CA1064 + = "CA1064:Exceptions should be public"; + + /// Design: an exception type does not implement the standard constructors. + public const string CA1032 + = "CA1032:Implement standard exception constructors"; + + /// Usage: an argument exception names a parameter that is not one of the method. + public const string CA2208 + = "CA2208:Instantiate argument exceptions correctly"; +} \ No newline at end of file diff --git a/Source/Core/Core/ArgumentMessages.cs b/Source/Core/Core/ArgumentMessages.cs new file mode 100644 index 00000000..69469526 --- /dev/null +++ b/Source/Core/Core/ArgumentMessages.cs @@ -0,0 +1,12 @@ +namespace Open.Database.Extensions; + +/// +/// The messages of the checks on an argument's range: one text for each fact, +/// used by every place that makes the check. +/// +internal static class ArgumentMessages +{ + /// A count or an index is below zero. + public const string NotNegative + = "Cannot be negative."; +} \ No newline at end of file diff --git a/Source/Core/Core/CancellationTokens.cs b/Source/Core/Core/CancellationTokens.cs index e2463198..bcc36bec 100644 --- a/Source/Core/Core/CancellationTokens.cs +++ b/Source/Core/Core/CancellationTokens.cs @@ -15,7 +15,7 @@ internal static class CancellationTokens /// /// when neither token can be canceled, the one that can when only one can (or when both are the same), and the linked source's token otherwise. /// - [SuppressMessage("Design", "CA1068:CancellationToken parameters must come last")] + [SuppressMessage("Design", AnalyzerIds.CA1068)] public static CancellationToken Combine(CancellationToken commandToken, CancellationToken callToken, out CancellationTokenSource? linked) { linked = null; @@ -52,7 +52,7 @@ public static CancellationToken Combine(CancellationToken commandToken, Cancella /// its result is the result of . /// [SuppressMessage( - "Design", "CA1068:CancellationToken parameters must come last")] + "Design", AnalyzerIds.CA1068)] public static ValueTask RunAsync( CancellationToken commandToken, CancellationToken callToken, diff --git a/Source/Core/Core/CommandTextMessages.cs b/Source/Core/Core/CommandTextMessages.cs index 84ec77d6..2a8a7af9 100644 --- a/Source/Core/Core/CommandTextMessages.cs +++ b/Source/Core/Core/CommandTextMessages.cs @@ -10,4 +10,8 @@ internal static class CommandTextMessages public const string Blank = "The command cannot be empty or white space. " + "Pass the SQL text or the name of the stored procedure."; + + /// A command's text is empty or white space, in the check that names the argument. + public const string EmptyOrWhiteSpace + = "Command is empty or whitespace."; } diff --git a/Source/Core/Core/MappedDbQueryMessages.cs b/Source/Core/Core/MappedDbQueryMessages.cs new file mode 100644 index 00000000..e044b954 --- /dev/null +++ b/Source/Core/Core/MappedDbQueryMessages.cs @@ -0,0 +1,13 @@ +namespace Open.Database.Extensions; + +/// +/// The messages of the checks on a query mapped from a definition: one text for each fact, +/// used by every place that makes the check. +/// +internal static class MappedDbQueryMessages +{ + /// A parameter is added after Map to a query that does not come from a definition. + public const string NotFromADefinition + = "AddParam after Map applies only to a query made from a DbQuery definition; " + + "for a command, call AddParam before Map."; +} \ No newline at end of file diff --git a/Source/Core/Core/ParameterNameMessages.cs b/Source/Core/Core/ParameterNameMessages.cs index 6960c052..463b2f82 100644 --- a/Source/Core/Core/ParameterNameMessages.cs +++ b/Source/Core/Core/ParameterNameMessages.cs @@ -14,4 +14,42 @@ public const string Blank /// A parameter other than a return parameter has no name. public const string NullOnlyForReturn = "Parameter names can only be null for a return parameter."; + + /// The names of a procedure's parameters are not known, so a collision is explained without them. + public const string NotKnown + = "The parameter names are not known, " + + "so each argument is used under its last member as written."; + + /// The fix of a collision between two parameters. + public const string NameOneExplicitly + = "Name one of them explicitly: AddParam(\"name\", value)."; + + /// The compiler did not supply the text of an argument. + public const string NotSupplied + = "The compiler did not supply the argument's text " + + "(deriving a name needs C# 10 or newer). " + + "Pass the name explicitly: AddParam(\"name\", value)."; + + /// A tier of the name match: the names are the same. + public const string TierExactly + = "exactly"; + + /// A tier of the name match: the names are the same ignoring case. + public const string TierIgnoringCase + = "ignoring case"; + + /// A tier of the name match: the names are the same ignoring case and underscores. + public const string TierIgnoringCaseAndUnderscores + = "ignoring case and underscores"; + + /// A tier of the name match: the names are the same ignoring case and underscores, once a common prefix is removed. + public const string TierWithoutPrefix + = "ignoring case and underscores once one parameter prefix " + + "(p_, in_, i_, prm_, par_, v_ or a lone p) is removed from the real name"; + + /// A parameter name cannot be derived from an expression. + /// The text of the expression. + /// The message. + public static string CannotDerive(string expression) + => $"Cannot derive a parameter name from the expression '{expression}'."; } diff --git a/Source/Core/Core/RowErrors.cs b/Source/Core/Core/RowErrors.cs index 4eac87b4..4c9cb4f0 100644 --- a/Source/Core/Core/RowErrors.cs +++ b/Source/Core/Core/RowErrors.cs @@ -104,9 +104,9 @@ public static string NoRowsScalar(Type target, string method) /// The name of the column. /// The type of the member. #pragma warning disable IDE0079 // Remove unnecessary suppression -[SuppressMessage("Roslynator", "RCS1194:Implement exception constructors", Justification = "Internal wrapper: only the row readers create it.")] -[SuppressMessage("Design", "CA1064:Exceptions should be public", Justification = "Internal wrapper: the row reader's guard turns it into a ValueMappingException.")] -[SuppressMessage("Design", "CA1032:Implement standard exception constructors", Justification = "Internal wrapper: only the row readers create it.")] +[SuppressMessage("Roslynator", AnalyzerIds.RCS1194, Justification = SuppressionJustifications.InternalRowWrapper)] +[SuppressMessage("Design", AnalyzerIds.CA1064, Justification = "Internal wrapper: the row reader's guard turns it into a ValueMappingException.")] +[SuppressMessage("Design", AnalyzerIds.CA1032, Justification = SuppressionJustifications.InternalRowWrapper)] #pragma warning restore IDE0079 // Remove unnecessary suppression sealed class NullPolicyViolation(string member, string column, Type memberType) : Exception { @@ -135,9 +135,9 @@ public ValueMappingException Create(Type model, int row) /// The model type, or the type of the single value. /// for a single value; otherwise, for a model. #pragma warning disable IDE0079 // Remove unnecessary suppression -[SuppressMessage("Roslynator", "RCS1194:Implement exception constructors", Justification = "Internal wrapper: only the row readers create it.")] -[SuppressMessage("Design", "CA1064:Exceptions should be public", Justification = "Internal wrapper: every read loop catches it, so it never reaches a caller.")] -[SuppressMessage("Design", "CA1032:Implement standard exception constructors", Justification = "Internal wrapper: only the row readers create it.")] +[SuppressMessage("Roslynator", AnalyzerIds.RCS1194, Justification = SuppressionJustifications.InternalRowWrapper)] +[SuppressMessage("Design", AnalyzerIds.CA1064, Justification = "Internal wrapper: every read loop catches it, so it never reaches a caller.")] +[SuppressMessage("Design", AnalyzerIds.CA1032, Justification = SuppressionJustifications.InternalRowWrapper)] #pragma warning restore IDE0079 // Remove unnecessary suppression sealed class RowMappingFailure(Exception inner, Type target, bool singleValue) : Exception(null, inner) { diff --git a/Source/Core/Core/RowMap.cs b/Source/Core/Core/RowMap.cs index a1b7c331..04427dc3 100644 --- a/Source/Core/Core/RowMap.cs +++ b/Source/Core/Core/RowMap.cs @@ -479,7 +479,7 @@ RowMap Converting( /// (none for a model built as it always was), then one per settable public instance property no parameter covers, /// in declaration order (a property hidden by name keeps the first). /// - [SuppressMessage("Roslynator", "RCS1158:Static member in generic type should use a type parameter", Justification = "They are this T's slots: the type parameter names which T (RowMap.MappedSlots).")] + [SuppressMessage("Roslynator", AnalyzerIds.RCS1158, Justification = "They are this T's slots: the type parameter names which T (RowMap.MappedSlots).")] internal static ImmutableArray MappedSlots { get; } = Model.Slots; /// @@ -790,7 +790,7 @@ public static RowMap Default /// /// cannot be mapped (see ). /// A of cannot be honoured. - [SuppressMessage("Roslynator", "RCS1158:Static member in generic type should use a type parameter", Justification = "It checks this T's shape: the type parameter is how a caller names which T to check (RowMap.ThrowIfUnmappable()).")] + [SuppressMessage("Roslynator", AnalyzerIds.RCS1158, Justification = "It checks this T's shape: the type parameter is how a caller names which T to check (RowMap.ThrowIfUnmappable()).")] internal static void ThrowIfUnmappable() { if (TypeError is not null) throw new InvalidOperationException(TypeError); @@ -1025,7 +1025,7 @@ bool[] Declare(ReadOnlySpan> mappings, string?[] c bool[] named = new bool[columns.Length]; foreach (KeyValuePair pair in mappings) { - if (pair.Key is null) throw new ArgumentException("A mapping has no property name.", paramName); + if (pair.Key is null) throw new ArgumentException(RowMapMessages.NoPropertyName, paramName); bool known = TryFindSlot(pair.Key, out int index); if (known) @@ -2731,8 +2731,8 @@ static NullDeclaration Of(IList attributes) /// sealed class Shape { - const string RequiredMemberAttributeName = "System.Runtime.CompilerServices.RequiredMemberAttribute"; - const string SetsRequiredMembersAttributeName = "System.Diagnostics.CodeAnalysis.SetsRequiredMembersAttribute"; + public const string RequiredMemberAttributeName = "System.Runtime.CompilerServices.RequiredMemberAttribute"; + public const string SetsRequiredMembersAttributeName = "System.Diagnostics.CodeAnalysis.SetsRequiredMembersAttribute"; Shape(string? error, ConstructorInfo? constructor, bool setsRequiredMembers) { @@ -2773,9 +2773,9 @@ public void ThrowIfUnmappable() setsRequiredMembers = false; string name = TypeName(type); - if (IsScalar(type)) return $"'{name}' is a single value, not a row model. On a command use Map(), which reads the first column; else ExecuteScalar()."; - if (NotConcrete(type) is { } kind) return $"'{name}' cannot be mapped: it is {kind}. Map to a class or struct, or use Map(selector)."; - if (IsDictionaryOrDynamic(type)) return $"'{name}' cannot be mapped: it is a dictionary or a dynamic object, which has no properties to set from the columns. Map to a class or record, use AsDictionaryRows() for the values with their column names, or use Map(selector)."; + if (IsScalar(type)) return RowMapMessages.Single(name); + if (NotConcrete(type) is { } kind) return RowMapMessages.NotConcrete(name, kind); + if (IsDictionaryOrDynamic(type)) return RowMapMessages.Bag(name); return Choose(type, name, out constructor, out setsRequiredMembers) ?? (setsRequiredMembers ? null : RequiredField(type, name)); } @@ -2820,10 +2820,10 @@ static bool IsDictionaryOrDynamic(Type type) /// Returns what the type is when it cannot be created at all, else . static string? NotConcrete(Type type) - => type.IsInterface ? "an interface" + => type.IsInterface ? RowMapMessages.Interface : type.ContainsGenericParameters ? "an open generic type" : typeof(Delegate).IsAssignableFrom(type) ? "a delegate" - : type.IsAbstract ? "an abstract class" + : type.IsAbstract ? RowMapMessages.AbstractClass : null; /// @@ -2846,18 +2846,18 @@ static bool IsDictionaryOrDynamic(Type type) // A struct always can be created, as its default value, whatever non-public constructors it declares. if (type.IsValueType && constructors.Length == 0) return null; - if (constructors.Length == 0) return $"'{name}' cannot be mapped: it has no public constructor."; + if (constructors.Length == 0) return RowMapMessages.NoConstructor(name); if (constructors.Length > 1) { string[] signatures = [.. constructors.Select(c => Signature(name, c)).OrderBy(s => s, StringComparer.Ordinal)]; - return $"'{name}' cannot be mapped: it has {constructors.Length} public constructors, {string.Join(", ", signatures, 0, signatures.Length - 1)} and {signatures[^1]}, and none without parameters. Make one of them non-public, or use Map(selector)."; + return RowMapMessages.Ambiguous(name, constructors.Length, $"{string.Join(", ", signatures, 0, signatures.Length - 1)} and {signatures[^1]}"); } foreach (ParameterInfo parameter in constructors[0].GetParameters()) { if (parameter.ParameterType.IsByRef || parameter.ParameterType.IsPointer) - return $"'{name}' cannot be mapped: its constructor parameter '{parameter.Name}' is passed by reference or is a pointer. Use Map(selector)."; + return RowMapMessages.ByReference(name, parameter.Name); } constructor = constructors[0]; @@ -2876,7 +2876,7 @@ static string Signature(string name, ConstructorInfo constructor) { foreach (FieldInfo field in type.GetFields(BindingFlags.Public | BindingFlags.Instance)) { - if (IsRequired(field)) return $"'{name}' cannot be mapped: its required field '{field.Name}' cannot be set. Make it a property."; + if (IsRequired(field)) return RowMapMessages.RequiredField(name, field.Name); } return null; diff --git a/Source/Core/Core/RowMapMessages.cs b/Source/Core/Core/RowMapMessages.cs new file mode 100644 index 00000000..157bb6cb --- /dev/null +++ b/Source/Core/Core/RowMapMessages.cs @@ -0,0 +1,77 @@ +namespace Open.Database.Extensions; + +/// +/// The messages of the checks on a row map and on the type it builds: one text for each fact, +/// used by every place that makes the check. +/// +internal static class RowMapMessages +{ + /// What a type is when it is an interface, in the message of a type that cannot be created. + public const string Interface + = "an interface"; + + /// What a type is when it is an abstract class, in the message of a type that cannot be created. + public const string AbstractClass + = "an abstract class"; + + /// A mapping pair has no property name. + public const string NoPropertyName + = "A mapping has no property name."; + + /// The type is a single value, so it is a column, not a row model. + /// The type's name. + /// The message. + public static string Single(string name) + => $"'{name}' is a single value, not a row model. " + + "On a command use Map(), which reads the first column; " + + "else ExecuteScalar()."; + + /// The type cannot be created at all. + /// The type's name. + /// What the type is. + /// The message. + public static string NotConcrete(string name, string kind) + => $"'{name}' cannot be mapped: it is {kind}. " + + "Map to a class or struct, or use Map(selector)."; + + /// The type is a dictionary or a dynamic object, which has no properties to set. + /// The type's name. + /// The message. + public static string Bag(string name) + => $"'{name}' cannot be mapped: it is a dictionary or a dynamic object, " + + "which has no properties to set from the columns. " + + "Map to a class or record, use AsDictionaryRows() for the values with their column names, " + + "or use Map(selector)."; + + /// The type has no public constructor. + /// The type's name. + /// The message. + public static string NoConstructor(string name) + => $"'{name}' cannot be mapped: it has no public constructor."; + + /// The type has more than one public constructor and none without parameters. + /// The type's name. + /// The number of public constructors. + /// The signatures, joined as the message lists them. + /// The message. + public static string Ambiguous(string name, int count, string signatures) + => $"'{name}' cannot be mapped: it has {count} public constructors, {signatures}, " + + "and none without parameters. " + + "Make one of them non-public, or use Map(selector)."; + + /// A parameter of the type's constructor is passed by reference or is a pointer. + /// The type's name. + /// The parameter's name. + /// The message. + public static string ByReference(string name, string? parameter) + => $"'{name}' cannot be mapped: its constructor parameter '{parameter}' " + + "is passed by reference or is a pointer. Use Map(selector)."; + + /// A required public field cannot be set, because fields are not mapped. + /// The type's name. + /// The field's name. + /// The message. + public static string RequiredField(string name, string field) + => $"'{name}' cannot be mapped: its required field '{field}' cannot be set. " + + "Make it a property."; +} \ No newline at end of file diff --git a/Source/Core/Core/SuppressionJustifications.cs b/Source/Core/Core/SuppressionJustifications.cs new file mode 100644 index 00000000..1586b2e1 --- /dev/null +++ b/Source/Core/Core/SuppressionJustifications.cs @@ -0,0 +1,16 @@ +namespace Open.Database.Extensions; + +/// +/// The reasons the code gives for a suppression that more than one place makes: +/// one text for each reason. +/// +internal static class SuppressionJustifications +{ + /// An overload that takes the token before the other arguments. + public const string OverloadForEasierConsumption + = "Overload for easier consumption."; + + /// An exception type that only the row readers create. + public const string InternalRowWrapper + = "Internal wrapper: only the row readers create it."; +} \ No newline at end of file diff --git a/Source/Core/Core/TransactionMessages.cs b/Source/Core/Core/TransactionMessages.cs new file mode 100644 index 00000000..e70f6e7b --- /dev/null +++ b/Source/Core/Core/TransactionMessages.cs @@ -0,0 +1,14 @@ +namespace Open.Database.Extensions; + +/// +/// The messages of the checks on a transaction: one text for each fact, +/// used by every place that makes the check. +/// +internal static class TransactionMessages +{ + /// A transaction has no connection, for example because it completed. + public const string NoConnection + = "Transaction has no connection, for example after it completed. " + + "Create the command before the transaction commits or rolls back, " + + "from a transaction that was begun on a connection."; +} \ No newline at end of file diff --git a/Source/Core/DbQueryBinding.cs b/Source/Core/DbQueryBinding.cs index 7a1a34b6..8fdf2e6a 100644 --- a/Source/Core/DbQueryBinding.cs +++ b/Source/Core/DbQueryBinding.cs @@ -297,8 +297,8 @@ static InvalidOperationException Collision( => new($"Two parameters resolve to '{name}'. " + (Known(names) ? $"'{definition.CommandText}' declares: {string.Join(", ", names!.Names)}." - : "The parameter names are not known, so each argument is used under its last member as written.") - + " Name one of them explicitly: AddParam(\"name\", value)."); + : ParameterNameMessages.NotKnown) + + " " + ParameterNameMessages.NameOneExplicitly); // The one text of "matches none", for a command and for a query: the owner // is the command text or procedure name, declares the words before the names. diff --git a/Source/Core/DbQueryCall.cs b/Source/Core/DbQueryCall.cs index b749d75e..4a29ca7f 100644 --- a/Source/Core/DbQueryCall.cs +++ b/Source/Core/DbQueryCall.cs @@ -204,13 +204,13 @@ static ArgumentException Blank(string message, string paramName) // stands for is settled when the query runs. [SuppressMessage( "Usage", - "CA2208:Instantiate argument exceptions correctly")] + AnalyzerIds.CA2208)] internal static ParameterNames.DerivedExpression CheckedExpression( string? expression) => ParameterNames.Describe(expression) ?? throw (expression is null ? new ArgumentException( - "The compiler did not supply the argument's text (deriving a name needs C# 10 or newer). Pass the name explicitly: AddParam(\"name\", value).", + ParameterNameMessages.NotSupplied, "value") : new ArgumentException( $"Cannot derive a parameter name from the argument '{expression}'. Pass a variable or a chain of members such as filter.AuthorId, or name the parameter: AddParam(\"name\", value).", diff --git a/Source/Core/ExpressiveCommandBase.cs b/Source/Core/ExpressiveCommandBase.cs index 7f160930..e27a1bb3 100644 --- a/Source/Core/ExpressiveCommandBase.cs +++ b/Source/Core/ExpressiveCommandBase.cs @@ -601,10 +601,10 @@ TThis AddDerivedParam(object? value, string? expression, Type clrType) return (TThis)this; } - [SuppressMessage("Usage", "CA2208:Instantiate argument exceptions correctly")] + [SuppressMessage("Usage", AnalyzerIds.CA2208)] static ArgumentException NotDerivable(string? expression) => expression is null - ? new("The compiler did not supply the argument's text (deriving a name needs C# 10 or newer). Pass the name explicitly: AddParam(\"name\", value).", "value") + ? new(ParameterNameMessages.NotSupplied, "value") : new($"Cannot derive a parameter name from the argument '{expression}'. Pass a variable or a chain of members such as filter.CompanySerialNum, or name the parameter: AddParam(\"name\", value).", "value"); /// @@ -1218,9 +1218,9 @@ static string Written(Param original) InvalidOperationException Collision(string name, Param first, Param second, ImmutableArray real) => new($"Two parameters resolve to '{name}': {Written(first)} and {Written(second)}. " + (real.IsDefaultOrEmpty - ? "The parameter names are not known, so each argument is used under its last member as written." + ? ParameterNameMessages.NotKnown : $"The procedure '{Command}' declares: {string.Join(", ", real)}.") - + " Name one of them explicitly: AddParam(\"name\", value)."); + + " " + ParameterNameMessages.NameOneExplicitly); InvalidOperationException NoMatch(string expression, ImmutableArray real) => DbQueryBinding.NoMatch( @@ -1305,7 +1305,7 @@ TResult ExecuteOn(TConnection connection, ConnectionState prior /// The function to run. /// A task that represents the asynchronous operation; its result is the result of . [SuppressMessage( - "Design", "CA1068:CancellationToken parameters must come last")] + "Design", AnalyzerIds.CA1068)] private protected ValueTask ExecuteCombinedAsync( CancellationToken callToken, Func> func) diff --git a/Source/Core/Extensions/Connection.CreateCommand.cs b/Source/Core/Extensions/Connection.CreateCommand.cs index 2dfd61a0..dc1c3f28 100644 --- a/Source/Core/Extensions/Connection.CreateCommand.cs +++ b/Source/Core/Extensions/Connection.CreateCommand.cs @@ -2,13 +2,11 @@ public static partial class ConnectionExtensions { - const string EmptyOrWhiteSpace = "Command is empty or whitespace."; - // Shared by the Core and MSSqlClient CreateCommand overloads. internal static void CheckCommandText(string commandText) { if (commandText is null) throw new ArgumentNullException(nameof(commandText)); - if (string.IsNullOrWhiteSpace(commandText)) throw new ArgumentException(EmptyOrWhiteSpace, nameof(commandText)); + if (string.IsNullOrWhiteSpace(commandText)) throw new ArgumentException(CommandTextMessages.EmptyOrWhiteSpace, nameof(commandText)); } // A command that cannot be set up is never returned, so nobody else can dispose it: it is disposed here. diff --git a/Source/Core/Extensions/DataReader.cs b/Source/Core/Extensions/DataReader.cs index 1def227f..d4ec4a9c 100644 --- a/Source/Core/Extensions/DataReader.cs +++ b/Source/Core/Extensions/DataReader.cs @@ -6,7 +6,7 @@ namespace Open.Database.Extensions; /// Provides extension methods that read rows and result sets from an or . /// #pragma warning disable IDE0079 // Remove unnecessary suppression -[SuppressMessage("Design", "CA1068:CancellationToken parameters must come last", Justification = "Overload provided for convienience.")] +[SuppressMessage("Design", AnalyzerIds.CA1068, Justification = "Overload provided for convienience.")] [SuppressMessage("Reliability", "CA2016:Forward the 'CancellationToken' parameter to methods that take one", Justification = "Intentional to prevent cancellation exception.")] #pragma warning restore IDE0079 // Remove unnecessary suppression public static class DataReaderExtensions diff --git a/Source/Core/Extensions/Transaction.CreateCommand.cs b/Source/Core/Extensions/Transaction.CreateCommand.cs index f61cd4e6..95375dff 100644 --- a/Source/Core/Extensions/Transaction.CreateCommand.cs +++ b/Source/Core/Extensions/Transaction.CreateCommand.cs @@ -19,7 +19,7 @@ public static IDbCommand CreateCommand(this IDbTransaction transaction, { if (transaction is null) throw new ArgumentNullException(nameof(transaction)); ConnectionExtensions.CheckCommandText(commandText); - if (transaction.Connection is null) throw new InvalidOperationException("Transaction has no connection, for example after it completed. Create the command before the transaction commits or rolls back, from a transaction that was begun on a connection."); + if (transaction.Connection is null) throw new InvalidOperationException(TransactionMessages.NoConnection); Contract.EndContractBlock(); IDbCommand command = transaction.Connection.CreateCommand(type, commandText, secondsTimeout); @@ -72,7 +72,7 @@ public static DbCommand CreateCommand(this DbTransaction transaction, { if (transaction is null) throw new ArgumentNullException(nameof(transaction)); ConnectionExtensions.CheckCommandText(commandText); - if (transaction.Connection is null) throw new InvalidOperationException("Transaction has no connection, for example after it completed. Create the command before the transaction commits or rolls back, from a transaction that was begun on a connection."); + if (transaction.Connection is null) throw new InvalidOperationException(TransactionMessages.NoConnection); Contract.EndContractBlock(); DbCommand command = transaction.Connection.CreateCommand(type, commandText, secondsTimeout); diff --git a/Source/Core/Extensions/Transaction.cs b/Source/Core/Extensions/Transaction.cs index 9bf87346..d604a1d5 100644 --- a/Source/Core/Extensions/Transaction.cs +++ b/Source/Core/Extensions/Transaction.cs @@ -1,6 +1,6 @@ namespace Open.Database.Extensions; -[SuppressMessage("Design", "CA1068:CancellationToken parameters must come last", Justification = "Overload for easier consumption.")] +[SuppressMessage("Design", AnalyzerIds.CA1068, Justification = SuppressionJustifications.OverloadForEasierConsumption)] public static partial class TransactionExtensions { /// diff --git a/Source/Core/MappedDbQuery.cs b/Source/Core/MappedDbQuery.cs index 957e8f36..f768a986 100644 --- a/Source/Core/MappedDbQuery.cs +++ b/Source/Core/MappedDbQuery.cs @@ -454,13 +454,10 @@ public MappedQuery Using(IDbConnectionFactory facto /// public static class MappedDbQueryExtensions { - const string NotFromADefinition - = "AddParam after Map applies only to a query made from a DbQuery definition; for a command, call AddParam before Map."; - static DbQueryCall CallOf(MappedQuery query) => query.TryGetCall(out DbQueryCall call) ? call - : throw new InvalidOperationException(NotFromADefinition); + : throw new InvalidOperationException(MappedDbQueryMessages.NotFromADefinition); /// Adds a named parameter to the query. /// The type each row is mapped to. diff --git a/Source/Core/MappedQuery.cs b/Source/Core/MappedQuery.cs index 06d54862..5a576559 100644 --- a/Source/Core/MappedQuery.cs +++ b/Source/Core/MappedQuery.cs @@ -354,7 +354,7 @@ public MappedQueryCore WithSkip(int count) ? Checked(new( _command, _call, _source, _skip + count, _take, Options, Config, _captures)) - : throw new ArgumentOutOfRangeException(nameof(count), count, "Cannot be negative."); + : throw new ArgumentOutOfRangeException(nameof(count), count, ArgumentMessages.NotNegative); /// /// Returns the query limited to at most rows. @@ -369,7 +369,7 @@ public MappedQueryCore WithTake(int count) ? Checked(new( _command, _call, _source, _skip, count, Options, Config, _captures)) - : throw new ArgumentOutOfRangeException(nameof(count), count, "Cannot be negative."); + : throw new ArgumentOutOfRangeException(nameof(count), count, ArgumentMessages.NotNegative); /// /// Combines the token passed to a terminal with the command's own. diff --git a/Source/Core/OutputBinding.cs b/Source/Core/OutputBinding.cs index 1d50a090..7af22f32 100644 --- a/Source/Core/OutputBinding.cs +++ b/Source/Core/OutputBinding.cs @@ -30,6 +30,13 @@ interface IInputLookup /// static class OutputBinding { + /// How the messages name a command that is not a stored procedure. + public const string TextCommandName + = "the command text"; + + const string PrecisionAndScale + = "precision, scale"; + /// /// Names the command for the messages: a procedure's name, or the command text. /// @@ -39,7 +46,7 @@ static class OutputBinding public static string Where(CommandType type, string commandText) => type == CommandType.StoredProcedure ? commandText - : "the command text"; + : TextCommandName; /// /// Resolves the parameter each output member stands for, while the call is @@ -267,9 +274,9 @@ static InvalidOperationException NoOutputMatch( ? (member.Form == OutputForm.Capture ? "Pass one of those names last to " : "Pass one of those names to ") - + OutputArguments.ShapedCall(member.Form, "name", "precision, scale") + + OutputArguments.ShapedCall(member.Form, "name", PrecisionAndScale) + " or " - + OutputArguments.DecimalCall(member.Form, "name", "precision, scale") + + OutputArguments.DecimalCall(member.Form, "name", PrecisionAndScale) : $"Pass one of those names to {OutputArguments.NamedCall(member.Form, "T", "name")}"; return new( @@ -284,19 +291,20 @@ static InvalidOperationException NoOutputMatch( + "Change the [Column] name to one it declares, or add the parameter."); } + string noMatch = $"{member.Display} has no matching parameter on {where} (tried {string.Join(", ", ParameterNames.Candidates(member.Name))}; it declares: {declared}). "; if (member.ReceivedName is { } received) { // A model capture maps by its members: the name it was given (typed, // or its variable's) is not used. return new( - $"{member.Display} has no matching parameter on {where} (tried {string.Join(", ", ParameterNames.Candidates(member.Name))}; it declares: {declared}). " + noMatch + $"The name '{received}' was not used: a model is read by its members, not by a name. " + $"To read one value into that name, use a single-value type (CaptureOutput(out DbCapture x, \"{received}\")); " + "otherwise give the model members named after the parameters, or [Column(\"name\")]."); } return new( - $"{member.Display} has no matching parameter on {where} (tried {string.Join(", ", ParameterNames.Candidates(member.Name))}; it declares: {declared}). " + noMatch + $"Add a parameter named {member.Name} to {where}, or name the member's parameter with [Column(\"name\")]."); } diff --git a/Source/Core/OutputDbNonQuery.cs b/Source/Core/OutputDbNonQuery.cs index 0938757f..0b40cf06 100644 --- a/Source/Core/OutputDbNonQuery.cs +++ b/Source/Core/OutputDbNonQuery.cs @@ -36,7 +36,7 @@ public static DbQuery Model(DbQuery definition) string model = Shape.TypeName(typeof(TOut)); OutputLayout layout = Wrap( definition, - $"Output<{model}>()", + OutputArguments.ModelCall(OutputForm.Definition, model), static () => OutputLayout.Get(OutputForm.Definition)); if (layout.HasReturnValue && definition.Kind != CommandType.StoredProcedure) diff --git a/Source/Core/OutputLayout.cs b/Source/Core/OutputLayout.cs index db51f830..b89ca032 100644 --- a/Source/Core/OutputLayout.cs +++ b/Source/Core/OutputLayout.cs @@ -633,7 +633,7 @@ public static OutputLayout Get( form, Shape.TypeName(typeof(T)), $"\"{name}\""), - _ => $"The output parameter '{name}'", + _ => OutputArguments.OutputParameter(name), }; OutputWire wire = Wire ?? throw new InvalidOperationException( Message(name, display, form)); @@ -702,7 +702,7 @@ public static OutputLayout Shaped( ImmutableArray candidates = default) { Debug.Assert(Reason == OutputValueRefusal.DecimalNeedsShape); - display ??= $"The output parameter '{name}'"; + display ??= OutputArguments.OutputParameter(name); return new( new OutputMember( name, @@ -952,6 +952,14 @@ public static string ModelCall(OutputForm form, string model) _ => $"ExecuteOutputAsync<{model}>()", }; + /// + /// Names an output parameter for the messages. + /// + /// The parameter's name. + /// The name, as the messages write it. + public static string OutputParameter(string name) + => $"The output parameter '{name}'"; + /// /// Gets the call that reads one value by name, as a message tells the caller /// to write it. diff --git a/Source/Core/ParameterNames.cs b/Source/Core/ParameterNames.cs index 0d6ba248..190bc07e 100644 --- a/Source/Core/ParameterNames.cs +++ b/Source/Core/ParameterNames.cs @@ -115,7 +115,7 @@ internal string Real(ReadOnlySpan marker) internal static string LastMember(string expression) => TryScan(expression, null, out int start, out int length) ? expression.Substring(start, length) - : throw new ArgumentException($"Cannot derive a parameter name from the expression '{expression}'.", nameof(expression)); + : throw new ArgumentException(ParameterNameMessages.CannotDerive(expression), nameof(expression)); /// /// Gets the candidate names of a derivable expression, most specific (longest) first, then the final member name as written. @@ -130,7 +130,7 @@ internal static ImmutableArray Candidates(string expression) { var segments = new List(4); if (!TryScan(expression, segments, out int lastStart, out int lastLength)) - throw new ArgumentException($"Cannot derive a parameter name from the expression '{expression}'.", nameof(expression)); + throw new ArgumentException(ParameterNameMessages.CannotDerive(expression), nameof(expression)); string[] names = new string[segments.Count]; for (int i = 0; i < names.Length; i++) @@ -329,10 +329,10 @@ static bool ClosesAt(string s, int open, int close) /// The description. static string TierText(int tier) => tier switch { - 1 => "exactly", - 2 => "ignoring case", - 3 => "ignoring case and underscores", - _ => "ignoring case and underscores once one parameter prefix (p_, in_, i_, prm_, par_, v_ or a lone p) is removed from the real name", + 1 => ParameterNameMessages.TierExactly, + 2 => ParameterNameMessages.TierIgnoringCase, + 3 => ParameterNameMessages.TierIgnoringCaseAndUnderscores, + _ => ParameterNameMessages.TierWithoutPrefix, }; static string? Find(string expression, string procedure, string candidate, ImmutableArray parameterNames, ImmutableArray bareNames, string? subject, string? fix = null) diff --git a/Source/Core/PooledArray.cs b/Source/Core/PooledArray.cs index 8c2fead2..6acf153c 100644 --- a/Source/Core/PooledArray.cs +++ b/Source/Core/PooledArray.cs @@ -399,7 +399,7 @@ void ICollection.CopyTo(T[] array, int arrayIndex) if (arrayIndex < 0) { throw new ArgumentOutOfRangeException( - nameof(arrayIndex), arrayIndex, "Cannot be negative."); + nameof(arrayIndex), arrayIndex, ArgumentMessages.NotNegative); } if (array.Length - arrayIndex < count) diff --git a/Source/Core/ProcedureSchemaNames.cs b/Source/Core/ProcedureSchemaNames.cs index 7bd03edb..b1022ebb 100644 --- a/Source/Core/ProcedureSchemaNames.cs +++ b/Source/Core/ProcedureSchemaNames.cs @@ -16,6 +16,18 @@ static class ProcedureSchemaNames /// public const string Collection = "ProcedureParameters"; + /// + /// The query of the two SQL Server packages for the parameter names of a + /// procedure, in ordinal order: it takes the procedure's name as @procedure + /// and answers nothing for a name that has a database part. + /// + public const string SqlServerQuery + = "select name from sys.all_parameters " + + "where object_id = object_id(@procedure) " + + "and parsename(@procedure, 3) is null " + + "and parameter_id > 0 " + + "order by parameter_id"; + /// /// The column of the collection with a parameter's name. /// diff --git a/Source/Core/ReaderAbandon.cs b/Source/Core/ReaderAbandon.cs index ff0545ea..42c0a290 100644 --- a/Source/Core/ReaderAbandon.cs +++ b/Source/Core/ReaderAbandon.cs @@ -23,7 +23,8 @@ namespace Open.Database.Extensions.Core; /// internal sealed class ReaderAbandon { - const string Option = "CancelOnEarlyStop()"; + /// The name of the option, as the messages write it. + public const string Option = "CancelOnEarlyStop()"; // Read when this is made: a TransactionScope without async flow is not seen after an await or on another thread. readonly bool _ambient = System.Transactions.Transaction.Current is not null; diff --git a/Source/Core/RecycleBin.cs b/Source/Core/RecycleBin.cs index a91eeae8..33d7231d 100644 --- a/Source/Core/RecycleBin.cs +++ b/Source/Core/RecycleBin.cs @@ -163,7 +163,7 @@ public virtual PostResult TryPost(Work work) /// Starts the loop, without the caller's execution context. /// The task of the loop, which never ends by itself. - [SuppressMessage("Roslynator", "RCS1229:Use async/await when necessary")] + [SuppressMessage("Roslynator", AnalyzerIds.RCS1229)] Task StartLoop() { // Task.Run would capture the starter's ExecutionContext for the diff --git a/Source/Core/StallStream.cs b/Source/Core/StallStream.cs index 47975ac6..29bfb669 100644 --- a/Source/Core/StallStream.cs +++ b/Source/Core/StallStream.cs @@ -219,7 +219,7 @@ async IAsyncEnumerator Read(CancellationToken cancellationToken) } } - [SuppressMessage("Roslynator", "RCS1229:Use async/await when necessary")] + [SuppressMessage("Roslynator", AnalyzerIds.RCS1229)] Task StartProducer(ChannelWriter writer) { // StartNew plus Unwrap, not Task.Run: it keeps TaskScheduler.Current, as the buffered reads do. diff --git a/Source/Core/Synchronous/SyncTransactionExtensions.cs b/Source/Core/Synchronous/SyncTransactionExtensions.cs index 179efba3..ed276177 100644 --- a/Source/Core/Synchronous/SyncTransactionExtensions.cs +++ b/Source/Core/Synchronous/SyncTransactionExtensions.cs @@ -5,7 +5,7 @@ namespace Open.Database.Extensions.Synchronous; /// /// Blocking transaction helpers on a : they hold the calling thread until the transaction ends. /// -[SuppressMessage("Design", "CA1068:CancellationToken parameters must come last", Justification = "Overload for easier consumption.")] +[SuppressMessage("Design", AnalyzerIds.CA1068, Justification = SuppressionJustifications.OverloadForEasierConsumption)] public static class SyncTransactionExtensions { /// diff --git a/Source/Core/ValueMappingException.cs b/Source/Core/ValueMappingException.cs index 9c950c32..82173b78 100644 --- a/Source/Core/ValueMappingException.cs +++ b/Source/Core/ValueMappingException.cs @@ -29,7 +29,7 @@ /// /// The provider's or the conversion's error, if any. /// -[SuppressMessage("Roslynator", "RCS1194:Implement exception constructors")] +[SuppressMessage("Roslynator", AnalyzerIds.RCS1194)] public sealed class ValueMappingException(string message, string propertyName, string columnName, Type targetType, Exception? innerException = null) : DataException(message, innerException) { /// diff --git a/Source/MSSqlClient/ExpressiveSqlCommand.cs b/Source/MSSqlClient/ExpressiveSqlCommand.cs index 51da18b1..ca00bf6f 100644 --- a/Source/MSSqlClient/ExpressiveSqlCommand.cs +++ b/Source/MSSqlClient/ExpressiveSqlCommand.cs @@ -192,7 +192,7 @@ protected override async ValueTask> GetProcedureParameter SqlCommand ProcedureNamesCommand(SqlConnection connection, string procedure) { SqlCommand command = connection.CreateCommand(); - command.CommandText = "select name from sys.all_parameters where object_id = object_id(@procedure) and parsename(@procedure, 3) is null and parameter_id > 0 order by parameter_id"; + command.CommandText = ProcedureSchemaNames.SqlServerQuery; command.CommandTimeout = Timeout; // the command's own timeout (SetTimeout), not the provider's default command.Parameters.Add( "@procedure", SqlDbType.NVarChar, ProcedureNameLength) diff --git a/Source/MSSqlClient/Extensions/Transaction.CreateCommand.cs b/Source/MSSqlClient/Extensions/Transaction.CreateCommand.cs index 35d2d994..a578bb0e 100644 --- a/Source/MSSqlClient/Extensions/Transaction.CreateCommand.cs +++ b/Source/MSSqlClient/Extensions/Transaction.CreateCommand.cs @@ -16,7 +16,7 @@ public static SqlCommand CreateCommand(this SqlTransaction transaction, { if (transaction is null) throw new ArgumentNullException(nameof(transaction)); ConnectionExtensions.CheckCommandText(commandText); - if (transaction.Connection is null) throw new InvalidOperationException("Transaction has no connection, for example after it completed. Create the command before the transaction commits or rolls back, from a transaction that was begun on a connection."); + if (transaction.Connection is null) throw new InvalidOperationException(TransactionMessages.NoConnection); Contract.EndContractBlock(); SqlCommand command = transaction diff --git a/Source/MSSqlClient/Extensions/Transaction.cs b/Source/MSSqlClient/Extensions/Transaction.cs index b9658cc9..cae2077d 100644 --- a/Source/MSSqlClient/Extensions/Transaction.cs +++ b/Source/MSSqlClient/Extensions/Transaction.cs @@ -8,7 +8,7 @@ /// /// Provides Microsoft.Data.SqlClient specific extension methods that run work in a database transaction on a . /// -[SuppressMessage("Design", "CA1068:CancellationToken parameters must come last", Justification = "Overload for easier consumption.")] +[SuppressMessage("Design", AnalyzerIds.CA1068, Justification = SuppressionJustifications.OverloadForEasierConsumption)] public static partial class SqlTransactionExtensions { /// diff --git a/Source/MSSqlClient/Synchronous/SyncSqlTransactionExtensions.cs b/Source/MSSqlClient/Synchronous/SyncSqlTransactionExtensions.cs index d60cc905..ddf2484e 100644 --- a/Source/MSSqlClient/Synchronous/SyncSqlTransactionExtensions.cs +++ b/Source/MSSqlClient/Synchronous/SyncSqlTransactionExtensions.cs @@ -4,7 +4,7 @@ namespace Open.Database.Extensions.Synchronous; /// Blocking transaction helpers on a : they hold the calling thread until the transaction ends. /// Add using Open.Database.Extensions.Synchronous; to use them. /// -[SuppressMessage("Design", "CA1068:CancellationToken parameters must come last", Justification = "Overload for easier consumption.")] +[SuppressMessage("Design", AnalyzerIds.CA1068, Justification = SuppressionJustifications.OverloadForEasierConsumption)] public static class SyncSqlTransactionExtensions { /// diff --git a/Source/SqlClient/ExpressiveSqlCommand.cs b/Source/SqlClient/ExpressiveSqlCommand.cs index b591bd89..c0534aa7 100644 --- a/Source/SqlClient/ExpressiveSqlCommand.cs +++ b/Source/SqlClient/ExpressiveSqlCommand.cs @@ -176,7 +176,7 @@ protected override async ValueTask> GetProcedureParameter SqlCommand ProcedureNamesCommand(SqlConnection connection, string procedure) { SqlCommand command = connection.CreateCommand(); - command.CommandText = "select name from sys.all_parameters where object_id = object_id(@procedure) and parsename(@procedure, 3) is null and parameter_id > 0 order by parameter_id"; + command.CommandText = ProcedureSchemaNames.SqlServerQuery; command.CommandTimeout = Timeout; // the command's own timeout (SetTimeout), not the provider's default command.Parameters.Add("@procedure", SqlDbType.NVarChar, 776).Value = procedure; if (Transaction is SqlTransaction transaction) command.Transaction = transaction; diff --git a/Source/SqlClient/Extensions/Connection.CreateCommand.cs b/Source/SqlClient/Extensions/Connection.CreateCommand.cs index c54be60b..594af349 100644 --- a/Source/SqlClient/Extensions/Connection.CreateCommand.cs +++ b/Source/SqlClient/Extensions/Connection.CreateCommand.cs @@ -2,8 +2,6 @@ public static partial class SqlConnectionExtensions { - const string EmptyOrWhiteSpace = "Command is empty or whitespace."; - /// /// Creates a from a connection with the command type, text, and timeout already set. /// @@ -22,7 +20,7 @@ public static SqlCommand CreateCommand(this SqlConnection connection, { if (connection is null) throw new ArgumentNullException(nameof(connection)); if (commandText is null) throw new ArgumentNullException(nameof(commandText)); - if (string.IsNullOrWhiteSpace(commandText)) throw new ArgumentException(EmptyOrWhiteSpace, nameof(commandText)); + if (string.IsNullOrWhiteSpace(commandText)) throw new ArgumentException(CommandTextMessages.EmptyOrWhiteSpace, nameof(commandText)); Contract.EndContractBlock(); SqlCommand command = connection.CreateCommand(); diff --git a/Source/SqlClient/Extensions/Transaction.CreateCommand.cs b/Source/SqlClient/Extensions/Transaction.CreateCommand.cs index d54612a0..1f43cf68 100644 --- a/Source/SqlClient/Extensions/Transaction.CreateCommand.cs +++ b/Source/SqlClient/Extensions/Transaction.CreateCommand.cs @@ -17,7 +17,7 @@ public static SqlCommand CreateCommand(this SqlTransaction transaction, { if (transaction is null) throw new ArgumentNullException(nameof(transaction)); if (commandText is null) throw new ArgumentNullException(nameof(commandText)); - if (string.IsNullOrWhiteSpace(commandText)) throw new ArgumentException("Command is empty or whitespace.", nameof(commandText)); + if (string.IsNullOrWhiteSpace(commandText)) throw new ArgumentException(CommandTextMessages.EmptyOrWhiteSpace, nameof(commandText)); Contract.EndContractBlock(); SqlCommand command = transaction diff --git a/Source/SqlClient/Extensions/Transaction.cs b/Source/SqlClient/Extensions/Transaction.cs index efc8f5ec..b3ad0e74 100644 --- a/Source/SqlClient/Extensions/Transaction.cs +++ b/Source/SqlClient/Extensions/Transaction.cs @@ -7,7 +7,7 @@ /// /// System.Data.SqlClient specific extensions for database transactions. /// -[SuppressMessage("Design", "CA1068:CancellationToken parameters must come last", Justification = "Overload for easier consumption.")] +[SuppressMessage("Design", AnalyzerIds.CA1068, Justification = SuppressionJustifications.OverloadForEasierConsumption)] [Obsolete(SqlClientObsolete._message)] public static partial class SqlTransactionExtensions { diff --git a/Source/SqlClient/Synchronous/SyncSqlTransactionExtensions.cs b/Source/SqlClient/Synchronous/SyncSqlTransactionExtensions.cs index 7a9673a9..c2dd0565 100644 --- a/Source/SqlClient/Synchronous/SyncSqlTransactionExtensions.cs +++ b/Source/SqlClient/Synchronous/SyncSqlTransactionExtensions.cs @@ -6,7 +6,7 @@ namespace Open.Database.Extensions.Synchronous; /// Blocking transaction helpers on a : they hold the calling thread until the transaction ends. /// Add using Open.Database.Extensions.Synchronous; to use them. /// -[SuppressMessage("Design", "CA1068:CancellationToken parameters must come last", Justification = "Overload for easier consumption.")] +[SuppressMessage("Design", AnalyzerIds.CA1068, Justification = SuppressionJustifications.OverloadForEasierConsumption)] [Obsolete(SqlClientObsolete._message)] public static class SyncSqlTransactionExtensions { diff --git a/Tests/Open.Database.Extensions.Core.Tests/CancelOnEarlyStopStreamTests.cs b/Tests/Open.Database.Extensions.Core.Tests/CancelOnEarlyStopStreamTests.cs index 95e0839f..228094a2 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/CancelOnEarlyStopStreamTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/CancelOnEarlyStopStreamTests.cs @@ -305,10 +305,10 @@ public static async Task AReaderOrTableView_RefusesWhenItRuns(string view) : table.Map().Skip(0).CancelOnEarlyStop(); InvalidOperationException thrown = await Assert.ThrowsAsync(async () => await query.FirstOrDefaultAsync(Ct)); - Assert.StartsWith("CancelOnEarlyStop()", thrown.Message, StringComparison.Ordinal); + Assert.StartsWith(global::Open.Database.Extensions.Core.ReaderAbandon.Option, thrown.Message, StringComparison.Ordinal); Assert.Contains(view == "reader" ? "a data reader" : "a DataTable", thrown.Message, StringComparison.Ordinal); thrown = Assert.Throws(() => query.FirstOrDefault()); - Assert.StartsWith("CancelOnEarlyStop()", thrown.Message, StringComparison.Ordinal); + Assert.StartsWith(global::Open.Database.Extensions.Core.ReaderAbandon.Option, thrown.Message, StringComparison.Ordinal); // The caller's reader was not touched. Assert.True(reader.Read()); diff --git a/Tests/Open.Database.Extensions.Core.Tests/CancelOnEarlyStopTests.cs b/Tests/Open.Database.Extensions.Core.Tests/CancelOnEarlyStopTests.cs index c7a2e1c7..c33b42d9 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/CancelOnEarlyStopTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/CancelOnEarlyStopTests.cs @@ -18,7 +18,7 @@ public static class CancelOnEarlyStopTests static void AssertRefused(Exception thrown, DbTally tally, string names) { - Assert.StartsWith("CancelOnEarlyStop()", thrown.Message, StringComparison.Ordinal); + Assert.StartsWith(global::Open.Database.Extensions.Core.ReaderAbandon.Option, thrown.Message, StringComparison.Ordinal); Assert.Contains(names, thrown.Message, StringComparison.Ordinal); // The fix is named too. diff --git a/Tests/Open.Database.Extensions.Core.Tests/CaptureNameLocalDbTests.cs b/Tests/Open.Database.Extensions.Core.Tests/CaptureNameLocalDbTests.cs index d11330cf..f995f512 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/CaptureNameLocalDbTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/CaptureNameLocalDbTests.cs @@ -238,10 +238,10 @@ public static async Task ACaptureThatMatchesNoMarker_SaysTheCommandText_NotProce .CaptureOutput(out DbCapture nothing) .ToListAsync(Token)); - Assert.Contains("the command text", onCommand.Message); - Assert.Contains("of the command text", onCommand.Message); - Assert.Contains("the command text", onDefinition.Message); - Assert.Contains("of the command text", onDefinition.Message); + Assert.Contains(OutputBinding.TextCommandName, onCommand.Message); + Assert.Contains("of " + OutputBinding.TextCommandName, onCommand.Message); + Assert.Contains(OutputBinding.TextCommandName, onDefinition.Message); + Assert.Contains("of " + OutputBinding.TextCommandName, onDefinition.Message); } [Fact] diff --git a/Tests/Open.Database.Extensions.Core.Tests/CaptureTests.cs b/Tests/Open.Database.Extensions.Core.Tests/CaptureTests.cs index 53abdfb0..cf40e060 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/CaptureTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/CaptureTests.cs @@ -186,7 +186,7 @@ public static void ASynchronousTerminal_Throws_AndArmsNothing() () => command.ExecuteNonQuery()); Contains(ex, "captures only work with async terminals", - "ExecuteNonQueryAsync instead of ExecuteNonQuery"); + CaptureMessages.ExecuteNonQueryInstead); Assert.Equal(0, c.Executed); // Not armed: awaiting it would wait forever, so it throws. @@ -615,7 +615,7 @@ public static async Task ASynchronousTerminal_OnAQuery_Throws_AndArmsNothing() Contains( Assert.Throws(() => query.ToList()), "This query has CaptureOutput(out DbCapture total)", - "ToListAsync instead of ToList"); + CaptureMessages.ToListInstead); Assert.Throws(() => { _ = total.AsTask(); }); // Still unused: the async terminal runs it. diff --git a/Tests/Open.Database.Extensions.Core.Tests/CommandExecuteFailureTests.cs b/Tests/Open.Database.Extensions.Core.Tests/CommandExecuteFailureTests.cs index e15700e1..3977deb8 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/CommandExecuteFailureTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/CommandExecuteFailureTests.cs @@ -10,7 +10,7 @@ namespace Open.Database.Extensions.Tests; [ExcludeFromCodeCoverage] public static class CommandExecuteFailureTests { - [SuppressMessage("Roslynator", "RCS1194:Implement exception constructors", Justification = "Test Only")] + [SuppressMessage("Roslynator", AnalyzerIds.RCS1194, Justification = "Test Only")] sealed class ProviderFailed : Exception; // An IDbCommand that is not a DbCommand: the extensions take their synchronous path with it. diff --git a/Tests/Open.Database.Extensions.Core.Tests/ConstructorBindingTests.cs b/Tests/Open.Database.Extensions.Core.Tests/ConstructorBindingTests.cs index e1915162..ff928efc 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/ConstructorBindingTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/ConstructorBindingTests.cs @@ -604,7 +604,7 @@ public static void APropertySetterThatThrows_AfterTheConstructor_IsReportedAsAVa NullAssert.Check("Unable to map row 0 to 'ThrowingSetter'.", ex); } - [SuppressMessage("Roslynator", "RCS1194:Implement exception constructors")] + [SuppressMessage("Roslynator", AnalyzerIds.RCS1194)] sealed class ProviderFailure : DbException { public ProviderFailure() : base("the provider failed") { } diff --git a/Tests/Open.Database.Extensions.Core.Tests/DbQueryBindingTests.cs b/Tests/Open.Database.Extensions.Core.Tests/DbQueryBindingTests.cs index cad8b78c..0e2b0028 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/DbQueryBindingTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/DbQueryBindingTests.cs @@ -275,7 +275,7 @@ static void M(DbConnection c, DbQueryCall call, ExpressiveCommand today) // A command binds the one extension on IExecuteReader. INamedTypeSymbol extensions = compilation.GetTypeByMetadataName( - "Open.Database.Extensions.CoreExtensions")!; + typeof(CoreExtensions).FullName!)!; for (int i = 8; i < bound.Length; i++) { IMethodSymbol definition = (bound[i].ReducedFrom ?? bound[i]).OriginalDefinition; diff --git a/Tests/Open.Database.Extensions.Core.Tests/DerivedNamesEveryRunCostTests.cs b/Tests/Open.Database.Extensions.Core.Tests/DerivedNamesEveryRunCostTests.cs index 2028dfcd..3737bdcc 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/DerivedNamesEveryRunCostTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/DerivedNamesEveryRunCostTests.cs @@ -67,7 +67,7 @@ public Action Sync(ExpressiveDbCommand command) _db.Sent.Clear(); }; - [SuppressMessage("Roslynator", "RCS1047:Non-asynchronous method name should not end with 'Async'")] + [SuppressMessage("Roslynator", AnalyzerIds.RCS1047)] public Action Async(ExpressiveDbCommand command) => () => { diff --git a/Tests/Open.Database.Extensions.Core.Tests/DerivedParameterNameTests.cs b/Tests/Open.Database.Extensions.Core.Tests/DerivedParameterNameTests.cs index a26ecfc1..8a4a0631 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/DerivedParameterNameTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/DerivedParameterNameTests.cs @@ -403,7 +403,7 @@ public static void ExplicitNameThatMatchesADerivedOne_Throws() // ---- async ---- // What a server's rejection looks like. - [SuppressMessage("Roslynator", "RCS1194:Implement exception constructors")] + [SuppressMessage("Roslynator", AnalyzerIds.RCS1194)] internal sealed class ServerError(string message = "rejected by the server") : DbException(message); internal sealed class OpenDbConnection(DbCommand command) : DbConnection diff --git a/Tests/Open.Database.Extensions.Core.Tests/ExecuteScalarNullTests.cs b/Tests/Open.Database.Extensions.Core.Tests/ExecuteScalarNullTests.cs index 4f73a408..b4eabbc8 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/ExecuteScalarNullTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/ExecuteScalarNullTests.cs @@ -37,7 +37,7 @@ public override void Close() { } protected override DbCommand CreateDbCommand() => command; } - [SuppressMessage("Roslynator", "RCS1047:Non-asynchronous method name should not end with 'Async'")] + [SuppressMessage("Roslynator", AnalyzerIds.RCS1047)] internal static ExpressiveDbCommand Async(object? scalar) { DbCommand command = Substitute.For(); diff --git a/Tests/Open.Database.Extensions.Core.Tests/GeneratedRowMapTests.cs b/Tests/Open.Database.Extensions.Core.Tests/GeneratedRowMapTests.cs index 65febffc..1b702cda 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/GeneratedRowMapTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/GeneratedRowMapTests.cs @@ -648,7 +648,7 @@ public void A_map_made_from_a_generated_map_is_the_runtime_s() /// A provider's own failure. [ExcludeFromCodeCoverage] -[SuppressMessage("Roslynator", "RCS1194:Implement exception constructors")] +[SuppressMessage("Roslynator", AnalyzerIds.RCS1194)] internal sealed class TestDbFailure(string message) : DbException(message); /// An that is not a : the runtime's interface-call route. diff --git a/Tests/Open.Database.Extensions.Core.Tests/LeakMatrixTests.cs b/Tests/Open.Database.Extensions.Core.Tests/LeakMatrixTests.cs index c4e6ae16..30db796f 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/LeakMatrixTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/LeakMatrixTests.cs @@ -23,7 +23,7 @@ sealed class Row public string? Name { get; set; } } - [SuppressMessage("Roslynator", "RCS1194:Implement exception constructors", Justification = "Test Only")] + [SuppressMessage("Roslynator", AnalyzerIds.RCS1194, Justification = "Test Only")] sealed class ExecuteFailed : Exception; public enum Outcome @@ -58,7 +58,7 @@ static Terminal Sync(string name, Traits traits, Fu return Task.CompletedTask; }); - [SuppressMessage("Roslynator", "RCS1047:Non-asynchronous method name should not end with 'Async'")] + [SuppressMessage("Roslynator", AnalyzerIds.RCS1047)] static Terminal Async(string name, Traits traits, Func> run) => new(name, traits | Traits.Async, async (c, ct) => await run(c, ct)); diff --git a/Tests/Open.Database.Extensions.Core.Tests/MappedDbQueryTests.cs b/Tests/Open.Database.Extensions.Core.Tests/MappedDbQueryTests.cs index 4a07e8c5..50c89faa 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/MappedDbQueryTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/MappedDbQueryTests.cs @@ -473,7 +473,7 @@ public static void ParamsAfterUsing_OnAViewNotMadeFromADefinition_Throw() MappedQuery classic = c.Command("select 1").Map(); const string expected - = "AddParam after Map applies only to a query made from a DbQuery definition; for a command, call AddParam before Map."; + = MappedDbQueryMessages.NotFromADefinition; const int a = 1; Assert.Equal(expected, Assert.Throws(() => classic.AddParam("a", 1)).Message); diff --git a/Tests/Open.Database.Extensions.Core.Tests/MappingCharacterizationTests.cs b/Tests/Open.Database.Extensions.Core.Tests/MappingCharacterizationTests.cs index cd72912d..9cebaac1 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/MappingCharacterizationTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/MappingCharacterizationTests.cs @@ -217,7 +217,7 @@ public static void AnUnknownName_ThrowsArgumentException_EvenWithANullColumn_Wit public static void ANullPropertyName_AndAnEmptyColumnName_Throw() { var noName = Assert.Throws(() => new RowMap([new(null!, "x")])); - Assert.StartsWith("A mapping has no property name.", noName.Message); + Assert.StartsWith(RowMapMessages.NoPropertyName, noName.Message); var empty = Assert.Throws(() => new RowMap([new(nameof(Post.Title), "")])); Assert.StartsWith("The property 'Title' is mapped to an empty column name. Use null to ignore it.", empty.Message); @@ -404,7 +404,7 @@ public sealed class ThrowingConstructor public ThrowingConstructor() => throw Failure!; } - [SuppressMessage("Roslynator", "RCS1194:Implement exception constructors")] + [SuppressMessage("Roslynator", AnalyzerIds.RCS1194)] sealed class ProviderFailure : DbException { public ProviderFailure() : base("the provider failed") { } diff --git a/Tests/Open.Database.Extensions.Core.Tests/NullRuleRouteTests.cs b/Tests/Open.Database.Extensions.Core.Tests/NullRuleRouteTests.cs index 495980c8..8eced46f 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/NullRuleRouteTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/NullRuleRouteTests.cs @@ -167,7 +167,7 @@ internal sealed class NotADbDataReader(DbDataReader inner) : IDataReader public bool Read() => inner.Read(); } - [SuppressMessage("Roslynator", "RCS1194:Implement exception constructors")] + [SuppressMessage("Roslynator", AnalyzerIds.RCS1194)] sealed class ProviderFailure() : DbException("the provider failed"); // A reader whose typed read of Id fails as the provider would. diff --git a/Tests/Open.Database.Extensions.Core.Tests/OutputParameterTests.cs b/Tests/Open.Database.Extensions.Core.Tests/OutputParameterTests.cs index eba09511..1e6abe50 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/OutputParameterTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/OutputParameterTests.cs @@ -364,7 +364,7 @@ public static async Task AnOutputThatNeverArrived_Throws_NeverReadsAsNull() // On a text command the message names the command text. c = new OutputConnection(); ex = await Assert.ThrowsAsync(async () => await c.Command("set @Count = 1").ExecuteOutputAsync(Token)); - Assert.Contains("NotMappedOnly.Count has no value after the command text ran", ex.Message); + Assert.Contains($"NotMappedOnly.Count has no value after {OutputBinding.TextCommandName} ran", ex.Message); } // "Not delivered" is decided before any value is converted: the model is never half built from what did arrive. diff --git a/Tests/Open.Database.Extensions.Core.Tests/ParameterNameMessageTests.cs b/Tests/Open.Database.Extensions.Core.Tests/ParameterNameMessageTests.cs index a5396929..14fa6ab7 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/ParameterNameMessageTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/ParameterNameMessageTests.cs @@ -28,10 +28,10 @@ public static void Ambiguity_SaysWhatYouWrote_TheCandidate_TheTier_AndWhatThePro } [Theory] - [InlineData("exactly", new[] { "@x", "@x" }, "x")] - [InlineData("ignoring case", new[] { "@customerid", "@CUSTOMERID" }, "CustomerId")] - [InlineData("ignoring case and underscores", new[] { "@customer_id", "@customer__id" }, "CustomerId")] - [InlineData("ignoring case and underscores once one parameter prefix (p_, in_, i_, prm_, par_, v_ or a lone p) is removed from the real name", new[] { "@p_author", "@in_author" }, "Author")] + [InlineData(ParameterNameMessages.TierExactly, new[] { "@x", "@x" }, "x")] + [InlineData(ParameterNameMessages.TierIgnoringCase, new[] { "@customerid", "@CUSTOMERID" }, "CustomerId")] + [InlineData(ParameterNameMessages.TierIgnoringCaseAndUnderscores, new[] { "@customer_id", "@customer__id" }, "CustomerId")] + [InlineData(ParameterNameMessages.TierWithoutPrefix, new[] { "@p_author", "@in_author" }, "Author")] public static void Ambiguity_NamesTheTierThatMatchedMoreThanOneParameter(string tier, string[] real, string expression) { var ex = Assert.Throws(() => new SyncNameRun(real).Add(expression)); @@ -62,7 +62,7 @@ public static void Collision_NamesBothArguments_AsTheyWereWritten_AndWhatTheProc Assert.StartsWith("Two parameters resolve to '@region': the argument 'filter.Region' and the argument 'other.Region'.", ex.Message); Assert.Contains("The procedure 'dbo.names", ex.Message); Assert.Contains("declares: @region, @mode.", ex.Message); - Assert.Contains("Name one of them explicitly: AddParam(\"name\", value).", ex.Message); + Assert.Contains(ParameterNameMessages.NameOneExplicitly, ex.Message); } [Fact] @@ -96,7 +96,7 @@ public static void Collision_WithoutTheProceduresNames_SaysTheyAreNotKnown() .AddParam(value: 2, expression: "customer.Id"))); Assert.StartsWith("Two parameters resolve to 'Id': the argument 'order.Id' and the argument 'customer.Id'.", ex.Message); - Assert.Contains("The parameter names are not known, so each argument is used under its last member as written.", ex.Message); + Assert.Contains(ParameterNameMessages.NotKnown, ex.Message); Assert.DoesNotContain("declares", ex.Message); Assert.Equal(0, run.Lookups); } diff --git a/Tests/Open.Database.Extensions.Core.Tests/PooledBufferAsAsyncEnumerableTests.cs b/Tests/Open.Database.Extensions.Core.Tests/PooledBufferAsAsyncEnumerableTests.cs index 98400290..5336382b 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/PooledBufferAsAsyncEnumerableTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/PooledBufferAsAsyncEnumerableTests.cs @@ -54,7 +54,7 @@ static async Task> ReadAll(IAsyncEnumerable source, Cancel } // Starts the call on a thread that has the context: its first await that waits is made there. - [SuppressMessage("Roslynator", "RCS1229:Use async/await when necessary")] + [SuppressMessage("Roslynator", AnalyzerIds.RCS1229)] static Task Under(SynchronizationContext context, Func call) { SynchronizationContext? prior = SynchronizationContext.Current; diff --git a/Tests/Open.Database.Extensions.Core.Tests/ProcedureSchemaNamesTests.cs b/Tests/Open.Database.Extensions.Core.Tests/ProcedureSchemaNamesTests.cs index 67af27d9..f1713302 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/ProcedureSchemaNamesTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/ProcedureSchemaNamesTests.cs @@ -10,7 +10,7 @@ namespace Open.Database.Extensions.Tests; [ExcludeFromCodeCoverage] public static class ProcedureSchemaNamesTests { - [SuppressMessage("Roslynator", "RCS1194:Implement exception constructors")] + [SuppressMessage("Roslynator", AnalyzerIds.RCS1194)] sealed class ProviderFailure(string message) : DbException(message); sealed class SchemaConnection(DataTable? table, Exception? failure) : DbConnection diff --git a/Tests/Open.Database.Extensions.Core.Tests/RequiredMemberTests.cs b/Tests/Open.Database.Extensions.Core.Tests/RequiredMemberTests.cs index a6e3e16d..735d2eaa 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/RequiredMemberTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/RequiredMemberTests.cs @@ -337,8 +337,8 @@ public static void WhenTheConstructorSetsRequiredMembers_ARequiredFieldIsNotAnEr // The test project is net11.0, whose framework has both attributes, so these models are built at run time with attributes of the same full names that are NOT the framework's types // (declared in a dynamic assembly), the way a consumer's polyfill on netstandard2.0 would be. - const string RequiredName = "System.Runtime.CompilerServices.RequiredMemberAttribute"; - const string SetsName = "System.Diagnostics.CodeAnalysis.SetsRequiredMembersAttribute"; + const string RequiredName = Shape.RequiredMemberAttributeName; + const string SetsName = Shape.SetsRequiredMembersAttributeName; static Type Polyfilled(string requiredAttribute, string? setsAttribute = null) { diff --git a/Tests/Open.Database.Extensions.Core.Tests/RowMapperTests.cs b/Tests/Open.Database.Extensions.Core.Tests/RowMapperTests.cs index 4432e9e7..11ebc5f0 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/RowMapperTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/RowMapperTests.cs @@ -269,7 +269,7 @@ public static void ProviderExceptions_AreNotWrapped() sealed class ThrowingReader() : TypedReader([("Id", typeof(int)), ("Name", typeof(string))], [[1, "x"]]) { - [SuppressMessage("Roslynator", "RCS1194:Implement exception constructors", Justification = "Test Only")] + [SuppressMessage("Roslynator", AnalyzerIds.RCS1194, Justification = "Test Only")] internal sealed class ProviderFailure : System.Data.Common.DbException; public override int GetInt32(int ordinal) => throw new ProviderFailure(); } diff --git a/Tests/Open.Database.Extensions.Core.Tests/SqlServerPackageTests.cs b/Tests/Open.Database.Extensions.Core.Tests/SqlServerPackageTests.cs index 3190ff0d..b83bb311 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/SqlServerPackageTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/SqlServerPackageTests.cs @@ -18,7 +18,7 @@ namespace Open.Database.Extensions.Tests; [Collection("LocalDB DDL")] public static class SqlServerPackageTests { - [SuppressMessage("Roslynator", "RCS1194:Implement exception constructors", Justification = "Test Only")] + [SuppressMessage("Roslynator", AnalyzerIds.RCS1194, Justification = "Test Only")] sealed class ProbeException : Exception; // A connection that is never opened: nothing here touches the network. @@ -493,7 +493,7 @@ public static void CreateCommand_OnATransactionWithNoConnection_Throws() var transaction = (SqlTransaction)System.Runtime.CompilerServices.RuntimeHelpers.GetUninitializedObject(typeof(SqlTransaction)); Assert.Null(transaction.Connection); - Assert.Equal("Transaction has no connection, for example after it completed. Create the command before the transaction commits or rolls back, from a transaction that was begun on a connection.", Assert.Throws(() => SqlTx.CreateCommand(transaction, CommandType.Text, "select 1")).Message); + Assert.Equal(TransactionMessages.NoConnection, Assert.Throws(() => SqlTx.CreateCommand(transaction, CommandType.Text, "select 1")).Message); Assert.Throws(() => SqlTx.CreateTextCommand(transaction, "select 1")); Assert.Throws(() => SqlTx.CreateStoredProcedureCommand(transaction, "dbo.p")); } diff --git a/Tests/Open.Database.Extensions.Core.Tests/TestHelpers/MultiSetReader.cs b/Tests/Open.Database.Extensions.Core.Tests/TestHelpers/MultiSetReader.cs index d9eac11a..e10471e4 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/TestHelpers/MultiSetReader.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/TestHelpers/MultiSetReader.cs @@ -6,7 +6,7 @@ namespace Open.Database.Extensions.Tests; /// The provider's failure when a later statement of a batch fails. [ExcludeFromCodeCoverage] -[SuppressMessage("Roslynator", "RCS1194:Implement exception constructors")] +[SuppressMessage("Roslynator", AnalyzerIds.RCS1194)] internal sealed class LaterSetFailure(string message) : DbException(message); /// diff --git a/Tests/Open.Database.Extensions.Core.Tests/TestHelpers/NullAssert.cs b/Tests/Open.Database.Extensions.Core.Tests/TestHelpers/NullAssert.cs index d3b9a209..5e888440 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/TestHelpers/NullAssert.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/TestHelpers/NullAssert.cs @@ -62,8 +62,7 @@ public static async Task NoRowsAsync(string method, Fu static ValueMappingException CheckNoRows(string method, ValueMappingException ex) { - string type = Shape.TypeName(typeof(T)); - Assert.Equal($"The query returned no rows; {method}<{type}> needs a value. Ask for {type}? and use ?? for a default.", ex.Message); + Assert.Equal(RowErrors.NoRowsScalar(typeof(T), method), ex.Message); Assert.Equal(typeof(T), ex.TargetType); Assert.Equal("", ex.PropertyName); Assert.Equal("", ex.ColumnName); diff --git a/Tests/Open.Database.Extensions.Core.Tests/UnmappableTypeTests.cs b/Tests/Open.Database.Extensions.Core.Tests/UnmappableTypeTests.cs index d45bc1bb..5f712606 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/UnmappableTypeTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/UnmappableTypeTests.cs @@ -115,13 +115,13 @@ public struct StructWithPrivateConstructor } static string Single(string name) - => $"'{name}' is a single value, not a row model. On a command use Map(), which reads the first column; else ExecuteScalar()."; - static string NotConcrete(string name, string kind) => $"'{name}' cannot be mapped: it is {kind}. Map to a class or struct, or use Map(selector)."; - static string NoConstructor(string name) => $"'{name}' cannot be mapped: it has no public constructor."; - static string Ambiguous(string name, int count, string signatures) => $"'{name}' cannot be mapped: it has {count} public constructors, {signatures}, and none without parameters. Make one of them non-public, or use Map(selector)."; - static string ByReference(string name, string parameter) => $"'{name}' cannot be mapped: its constructor parameter '{parameter}' is passed by reference or is a pointer. Use Map(selector)."; - static string RequiredField(string name, string field) => $"'{name}' cannot be mapped: its required field '{field}' cannot be set. Make it a property."; - static string Bag(string name) => $"'{name}' cannot be mapped: it is a dictionary or a dynamic object, which has no properties to set from the columns. Map to a class or record, use AsDictionaryRows() for the values with their column names, or use Map(selector)."; + => RowMapMessages.Single(name); + static string NotConcrete(string name, string kind) => RowMapMessages.NotConcrete(name, kind); + static string NoConstructor(string name) => RowMapMessages.NoConstructor(name); + static string Ambiguous(string name, int count, string signatures) => RowMapMessages.Ambiguous(name, count, signatures); + static string ByReference(string name, string parameter) => RowMapMessages.ByReference(name, parameter); + static string RequiredField(string name, string field) => RowMapMessages.RequiredField(name, field); + static string Bag(string name) => RowMapMessages.Bag(name); // A dictionary or a dynamic object is not a row model: it has no properties to set, so a map of it used to build one empty row and say nothing. Each of these kinds is reached by a different interface. public sealed class DictionaryOfMine : Dictionary; @@ -184,10 +184,10 @@ static void AssertUnmappable( // ---- the type-shape rules ---- [Fact] - public static void Interface_IsRejected() => AssertUnmappable(NotConcrete("IShapeless", "an interface")); + public static void Interface_IsRejected() => AssertUnmappable(NotConcrete("IShapeless", RowMapMessages.Interface)); [Fact] - public static void AbstractClass_IsRejected() => AssertUnmappable(NotConcrete("AbstractShape", "an abstract class")); + public static void AbstractClass_IsRejected() => AssertUnmappable(NotConcrete("AbstractShape", RowMapMessages.AbstractClass)); [Fact] public static void Delegate_IsRejected() => AssertUnmappable(NotConcrete("ShapeCallback", "a delegate")); @@ -293,9 +293,9 @@ public static void ADictionaryOrADynamicObject_IsRejected_AtTheCall_WhateverInte [Fact] public static void AnInterfaceOrAbstractDictionaryType_KeepsItsOwnReason() { - AssertUnmappable>(NotConcrete("IDictionary`2", "an interface")); - AssertUnmappable>(NotConcrete("IReadOnlyDictionary`2", "an interface")); - AssertUnmappable(NotConcrete("IDynamicMetaObjectProvider", "an interface")); + AssertUnmappable>(NotConcrete("IDictionary`2", RowMapMessages.Interface)); + AssertUnmappable>(NotConcrete("IReadOnlyDictionary`2", RowMapMessages.Interface)); + AssertUnmappable(NotConcrete("IDynamicMetaObjectProvider", RowMapMessages.Interface)); } [Fact] @@ -349,7 +349,7 @@ static Task Run(Action call) public static async Task EveryEntryPoint_Throws_ForAnUnmappableType_WithAnEmptyResult(string name) { InvalidOperationException ex = await Assert.ThrowsAsync(() => Calls[name]().WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken)); - Assert.Equal(NotConcrete("IShapeless", "an interface"), ex.Message); + Assert.Equal(NotConcrete("IShapeless", RowMapMessages.Interface), ex.Message); } // T17: a required public field, over the same entry points, with an empty result: the same exception at the call. @@ -429,7 +429,7 @@ public static async Task AnUnmappableType_Fails_BeforeAnythingIsExecutedOrRead(s { var touched = new Touched(); InvalidOperationException ex = await Assert.ThrowsAsync(() => BeforeExecution[name](touched).WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken)); - Assert.Equal(NotConcrete("IShapeless", "an interface"), ex.Message); + Assert.Equal(NotConcrete("IShapeless", RowMapMessages.Interface), ex.Message); Assert.Equal(0, touched.Count()); // No command was executed, no connection opened, no reader read: the failure had no side effect. } diff --git a/Tests/Open.Database.Extensions.Generator.Tests/Harness.cs b/Tests/Open.Database.Extensions.Generator.Tests/Harness.cs index 04f99734..6b05a7c0 100644 --- a/Tests/Open.Database.Extensions.Generator.Tests/Harness.cs +++ b/Tests/Open.Database.Extensions.Generator.Tests/Harness.cs @@ -236,7 +236,7 @@ public override bool Read() } /// A provider's own failure: a , which the runtime map lets through untouched. -[System.Diagnostics.CodeAnalysis.SuppressMessage("Roslynator", "RCS1194:Implement exception constructors")] +[System.Diagnostics.CodeAnalysis.SuppressMessage("Roslynator", AnalyzerIds.RCS1194)] internal sealed class TestDbException(string message) : DbException(message); /// A reader that forwards to another and calls before each cell is read. From 3a3736c6f62ef493f015fb1715af1a69a4027c85 Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Fri, 4 Dec 2026 09:33:33 -0800 Subject: [PATCH 5/9] Review fixes for the message sweep RowMapMessages.Bag is now DictionaryOrDynamic, after the check it describes. The message holders end with a newline and have a blank line above their first const, as the constants in the other holders do (also CaptureMessages, OutputBinding, ReaderAbandon and Shape); long lines and summaries in the code the sweep added are wrapped to about 80 columns. AnyAsync and CountAsync put the second call of the chain on its own line. The AddParam-after-Map message returns to MappedDbQueryExtensions as an internal const (its naming rule gives it the underscore prefix), and the file that held it alone is removed. DerivedNameCostTests now uses ParameterNameMessages for the three texts it copied. No message text changed word for word, and the public API is unchanged. Co-Authored-By: Claude Sonnet 5.5 --- Source/Core/AnyCount.cs | 6 +- Source/Core/Capture.cs | 9 ++- Source/Core/Core/AnalyzerIds.cs | 33 +++++++--- Source/Core/Core/ArgumentMessages.cs | 3 +- Source/Core/Core/MappedDbQueryMessages.cs | 13 ---- Source/Core/Core/ParameterNameMessages.cs | 29 +++++++-- Source/Core/Core/RowMap.cs | 18 ++++-- Source/Core/Core/RowMapMessages.cs | 64 +++++++++++++------ Source/Core/Core/SuppressionJustifications.cs | 7 +- Source/Core/Core/TransactionMessages.cs | 7 +- Source/Core/MappedDbQuery.cs | 6 +- Source/Core/OutputBinding.cs | 9 ++- Source/Core/ProcedureSchemaNames.cs | 4 +- Source/Core/ReaderAbandon.cs | 1 + .../DerivedNameCostTests.cs | 8 +-- .../MappedDbQueryTests.cs | 2 +- .../UnmappableTypeTests.cs | 18 +++--- 17 files changed, 157 insertions(+), 80 deletions(-) delete mode 100644 Source/Core/Core/MappedDbQueryMessages.cs diff --git a/Source/Core/AnyCount.cs b/Source/Core/AnyCount.cs index 515ebe36..c7fdc15b 100644 --- a/Source/Core/AnyCount.cs +++ b/Source/Core/AnyCount.cs @@ -22,7 +22,8 @@ public static partial class CoreExtensions public static ValueTask AnyAsync( this IExecuteReader command, CancellationToken cancellationToken = default) - => command.AsObjectArrays().AnyAsync(cancellationToken); + => command.AsObjectArrays() + .AnyAsync(cancellationToken); /// /// Asynchronously counts the rows the query returns, with no model to map them to. @@ -44,5 +45,6 @@ public static ValueTask AnyAsync( public static ValueTask CountAsync( this IExecuteReader command, CancellationToken cancellationToken = default) - => command.AsObjectArrays().CountAsync(cancellationToken); + => command.AsObjectArrays() + .CountAsync(cancellationToken); } diff --git a/Source/Core/Capture.cs b/Source/Core/Capture.cs index ea303946..62242b22 100644 --- a/Source/Core/Capture.cs +++ b/Source/Core/Capture.cs @@ -1014,11 +1014,16 @@ public static CaptureSource Return() /// static class CaptureMessages { - /// The async form of a query terminal, named in the message of a sync call. + + /// + /// The async form of a query terminal, named in the message of a sync call. + /// public const string ToListInstead = "ToListAsync instead of ToList"; - /// The async form of a command terminal, named in the message of a sync call. + /// + /// The async form of a command terminal, named in the message of a sync call. + /// public const string ExecuteNonQueryInstead = "ExecuteNonQueryAsync instead of ExecuteNonQuery"; diff --git a/Source/Core/Core/AnalyzerIds.cs b/Source/Core/Core/AnalyzerIds.cs index a7732752..3087377a 100644 --- a/Source/Core/Core/AnalyzerIds.cs +++ b/Source/Core/Core/AnalyzerIds.cs @@ -6,23 +6,35 @@ namespace Open.Database.Extensions; /// internal static class AnalyzerIds { - /// Roslynator: an exception type does not implement the standard constructors. + + /// + /// Roslynator: an exception type does not implement the standard constructors. + /// public const string RCS1194 = "RCS1194:Implement exception constructors"; - /// Roslynator: a method with a name that ends in Async is not asynchronous. + /// + /// Roslynator: a method with a name that ends in Async is not asynchronous. + /// public const string RCS1047 = "RCS1047:Non-asynchronous method name should not end with 'Async'"; - /// Roslynator: a method returns a task without async and await. + /// + /// Roslynator: a method returns a task without async and await. + /// public const string RCS1229 = "RCS1229:Use async/await when necessary"; - /// Roslynator: a static member of a generic type does not use the type parameter. + /// + /// Roslynator: a static member of a generic type does not use the type + /// parameter. + /// public const string RCS1158 = "RCS1158:Static member in generic type should use a type parameter"; - /// Design: a parameter of the type CancellationToken is not the last. + /// + /// Design: a parameter of the type CancellationToken is not the last. + /// public const string CA1068 = "CA1068:CancellationToken parameters must come last"; @@ -30,11 +42,16 @@ public const string CA1068 public const string CA1064 = "CA1064:Exceptions should be public"; - /// Design: an exception type does not implement the standard constructors. + /// + /// Design: an exception type does not implement the standard constructors. + /// public const string CA1032 = "CA1032:Implement standard exception constructors"; - /// Usage: an argument exception names a parameter that is not one of the method. + /// + /// Usage: an argument exception names a parameter that is not one of the + /// method. + /// public const string CA2208 = "CA2208:Instantiate argument exceptions correctly"; -} \ No newline at end of file +} diff --git a/Source/Core/Core/ArgumentMessages.cs b/Source/Core/Core/ArgumentMessages.cs index 69469526..1f510e51 100644 --- a/Source/Core/Core/ArgumentMessages.cs +++ b/Source/Core/Core/ArgumentMessages.cs @@ -6,7 +6,8 @@ namespace Open.Database.Extensions; /// internal static class ArgumentMessages { + /// A count or an index is below zero. public const string NotNegative = "Cannot be negative."; -} \ No newline at end of file +} diff --git a/Source/Core/Core/MappedDbQueryMessages.cs b/Source/Core/Core/MappedDbQueryMessages.cs deleted file mode 100644 index e044b954..00000000 --- a/Source/Core/Core/MappedDbQueryMessages.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace Open.Database.Extensions; - -/// -/// The messages of the checks on a query mapped from a definition: one text for each fact, -/// used by every place that makes the check. -/// -internal static class MappedDbQueryMessages -{ - /// A parameter is added after Map to a query that does not come from a definition. - public const string NotFromADefinition - = "AddParam after Map applies only to a query made from a DbQuery definition; " - + "for a command, call AddParam before Map."; -} \ No newline at end of file diff --git a/Source/Core/Core/ParameterNameMessages.cs b/Source/Core/Core/ParameterNameMessages.cs index 463b2f82..0b4baf97 100644 --- a/Source/Core/Core/ParameterNameMessages.cs +++ b/Source/Core/Core/ParameterNameMessages.cs @@ -15,7 +15,10 @@ public const string Blank public const string NullOnlyForReturn = "Parameter names can only be null for a return parameter."; - /// The names of a procedure's parameters are not known, so a collision is explained without them. + /// + /// The names of a procedure's parameters are not known, so a collision is + /// explained without them. + /// public const string NotKnown = "The parameter names are not known, " + "so each argument is used under its last member as written."; @@ -34,22 +37,34 @@ public const string NotSupplied public const string TierExactly = "exactly"; - /// A tier of the name match: the names are the same ignoring case. + /// + /// A tier of the name match: the names are the same ignoring case. + /// public const string TierIgnoringCase = "ignoring case"; - /// A tier of the name match: the names are the same ignoring case and underscores. + /// + /// A tier of the name match: the names are the same ignoring case and + /// underscores. + /// public const string TierIgnoringCaseAndUnderscores = "ignoring case and underscores"; - /// A tier of the name match: the names are the same ignoring case and underscores, once a common prefix is removed. + /// + /// A tier of the name match: the names are the same ignoring case and + /// underscores, once a common prefix is removed. + /// public const string TierWithoutPrefix = "ignoring case and underscores once one parameter prefix " - + "(p_, in_, i_, prm_, par_, v_ or a lone p) is removed from the real name"; + + "(p_, in_, i_, prm_, par_, v_ or a lone p) " + + "is removed from the real name"; - /// A parameter name cannot be derived from an expression. + /// + /// A parameter name cannot be derived from an expression. + /// /// The text of the expression. /// The message. public static string CannotDerive(string expression) - => $"Cannot derive a parameter name from the expression '{expression}'."; + => $"Cannot derive a parameter name from the expression " + + $"'{expression}'."; } diff --git a/Source/Core/Core/RowMap.cs b/Source/Core/Core/RowMap.cs index 04427dc3..15dcd6da 100644 --- a/Source/Core/Core/RowMap.cs +++ b/Source/Core/Core/RowMap.cs @@ -1025,7 +1025,10 @@ bool[] Declare(ReadOnlySpan> mappings, string?[] c bool[] named = new bool[columns.Length]; foreach (KeyValuePair pair in mappings) { - if (pair.Key is null) throw new ArgumentException(RowMapMessages.NoPropertyName, paramName); + if (pair.Key is null) + { + throw new ArgumentException(RowMapMessages.NoPropertyName, paramName); + } bool known = TryFindSlot(pair.Key, out int index); if (known) @@ -2731,8 +2734,12 @@ static NullDeclaration Of(IList attributes) /// sealed class Shape { - public const string RequiredMemberAttributeName = "System.Runtime.CompilerServices.RequiredMemberAttribute"; - public const string SetsRequiredMembersAttributeName = "System.Diagnostics.CodeAnalysis.SetsRequiredMembersAttribute"; + + public const string RequiredMemberAttributeName + = "System.Runtime.CompilerServices.RequiredMemberAttribute"; + + public const string SetsRequiredMembersAttributeName + = "System.Diagnostics.CodeAnalysis.SetsRequiredMembersAttribute"; Shape(string? error, ConstructorInfo? constructor, bool setsRequiredMembers) { @@ -2775,7 +2782,7 @@ public void ThrowIfUnmappable() if (IsScalar(type)) return RowMapMessages.Single(name); if (NotConcrete(type) is { } kind) return RowMapMessages.NotConcrete(name, kind); - if (IsDictionaryOrDynamic(type)) return RowMapMessages.Bag(name); + if (IsDictionaryOrDynamic(type)) return RowMapMessages.DictionaryOrDynamic(name); return Choose(type, name, out constructor, out setsRequiredMembers) ?? (setsRequiredMembers ? null : RequiredField(type, name)); } @@ -2851,7 +2858,8 @@ static bool IsDictionaryOrDynamic(Type type) if (constructors.Length > 1) { string[] signatures = [.. constructors.Select(c => Signature(name, c)).OrderBy(s => s, StringComparer.Ordinal)]; - return RowMapMessages.Ambiguous(name, constructors.Length, $"{string.Join(", ", signatures, 0, signatures.Length - 1)} and {signatures[^1]}"); + string listed = $"{string.Join(", ", signatures, 0, signatures.Length - 1)} and {signatures[^1]}"; + return RowMapMessages.Ambiguous(name, constructors.Length, listed); } foreach (ParameterInfo parameter in constructors[0].GetParameters()) diff --git a/Source/Core/Core/RowMapMessages.cs b/Source/Core/Core/RowMapMessages.cs index 157bb6cb..bbd80976 100644 --- a/Source/Core/Core/RowMapMessages.cs +++ b/Source/Core/Core/RowMapMessages.cs @@ -1,16 +1,23 @@ namespace Open.Database.Extensions; /// -/// The messages of the checks on a row map and on the type it builds: one text for each fact, -/// used by every place that makes the check. +/// The messages of the checks on a row map and on the type it builds: +/// one text for each fact, used by every place that makes the check. /// internal static class RowMapMessages { - /// What a type is when it is an interface, in the message of a type that cannot be created. + + /// + /// What a type is when it is an interface, + /// in the message of a type that cannot be created. + /// public const string Interface = "an interface"; - /// What a type is when it is an abstract class, in the message of a type that cannot be created. + /// + /// What a type is when it is an abstract class, + /// in the message of a type that cannot be created. + /// public const string AbstractClass = "an abstract class"; @@ -18,7 +25,9 @@ public const string AbstractClass public const string NoPropertyName = "A mapping has no property name."; - /// The type is a single value, so it is a column, not a row model. + /// + /// The type is a single value, so it is a column, not a row model. + /// /// The type's name. /// The message. public static string Single(string name) @@ -34,13 +43,18 @@ public static string NotConcrete(string name, string kind) => $"'{name}' cannot be mapped: it is {kind}. " + "Map to a class or struct, or use Map(selector)."; - /// The type is a dictionary or a dynamic object, which has no properties to set. + /// + /// The type is a dictionary or a dynamic object, + /// which has no properties to set. + /// /// The type's name. /// The message. - public static string Bag(string name) - => $"'{name}' cannot be mapped: it is a dictionary or a dynamic object, " + public static string DictionaryOrDynamic(string name) + => $"'{name}' cannot be mapped: " + + "it is a dictionary or a dynamic object, " + "which has no properties to set from the columns. " - + "Map to a class or record, use AsDictionaryRows() for the values with their column names, " + + "Map to a class or record, " + + "use AsDictionaryRows() for the values with their column names, " + "or use Map(selector)."; /// The type has no public constructor. @@ -49,29 +63,43 @@ public static string Bag(string name) public static string NoConstructor(string name) => $"'{name}' cannot be mapped: it has no public constructor."; - /// The type has more than one public constructor and none without parameters. + /// + /// The type has more than one public constructor + /// and none without parameters. + /// /// The type's name. /// The number of public constructors. - /// The signatures, joined as the message lists them. + /// + /// The signatures, joined as the message lists them. + /// /// The message. public static string Ambiguous(string name, int count, string signatures) - => $"'{name}' cannot be mapped: it has {count} public constructors, {signatures}, " + => $"'{name}' cannot be mapped: " + + $"it has {count} public constructors, {signatures}, " + "and none without parameters. " + "Make one of them non-public, or use Map(selector)."; - /// A parameter of the type's constructor is passed by reference or is a pointer. + /// + /// A parameter of the type's constructor is passed by reference + /// or is a pointer. + /// /// The type's name. /// The parameter's name. /// The message. public static string ByReference(string name, string? parameter) - => $"'{name}' cannot be mapped: its constructor parameter '{parameter}' " - + "is passed by reference or is a pointer. Use Map(selector)."; + => $"'{name}' cannot be mapped: " + + $"its constructor parameter '{parameter}' " + + "is passed by reference or is a pointer. " + + "Use Map(selector)."; - /// A required public field cannot be set, because fields are not mapped. + /// + /// A required public field cannot be set, because fields are not mapped. + /// /// The type's name. /// The field's name. /// The message. public static string RequiredField(string name, string field) - => $"'{name}' cannot be mapped: its required field '{field}' cannot be set. " + => $"'{name}' cannot be mapped: " + + $"its required field '{field}' cannot be set. " + "Make it a property."; -} \ No newline at end of file +} diff --git a/Source/Core/Core/SuppressionJustifications.cs b/Source/Core/Core/SuppressionJustifications.cs index 1586b2e1..32eb31a4 100644 --- a/Source/Core/Core/SuppressionJustifications.cs +++ b/Source/Core/Core/SuppressionJustifications.cs @@ -1,11 +1,12 @@ namespace Open.Database.Extensions; /// -/// The reasons the code gives for a suppression that more than one place makes: -/// one text for each reason. +/// The reasons the code gives for a suppression that more than one place +/// makes: one text for each reason. /// internal static class SuppressionJustifications { + /// An overload that takes the token before the other arguments. public const string OverloadForEasierConsumption = "Overload for easier consumption."; @@ -13,4 +14,4 @@ public const string OverloadForEasierConsumption /// An exception type that only the row readers create. public const string InternalRowWrapper = "Internal wrapper: only the row readers create it."; -} \ No newline at end of file +} diff --git a/Source/Core/Core/TransactionMessages.cs b/Source/Core/Core/TransactionMessages.cs index e70f6e7b..cbf411f4 100644 --- a/Source/Core/Core/TransactionMessages.cs +++ b/Source/Core/Core/TransactionMessages.cs @@ -6,9 +6,12 @@ namespace Open.Database.Extensions; /// internal static class TransactionMessages { - /// A transaction has no connection, for example because it completed. + + /// + /// A transaction has no connection, for example because it completed. + /// public const string NoConnection = "Transaction has no connection, for example after it completed. " + "Create the command before the transaction commits or rolls back, " + "from a transaction that was begun on a connection."; -} \ No newline at end of file +} diff --git a/Source/Core/MappedDbQuery.cs b/Source/Core/MappedDbQuery.cs index f768a986..76932092 100644 --- a/Source/Core/MappedDbQuery.cs +++ b/Source/Core/MappedDbQuery.cs @@ -454,10 +454,14 @@ public MappedQuery Using(IDbConnectionFactory facto /// public static class MappedDbQueryExtensions { + + internal const string _notFromADefinition + = "AddParam after Map applies only to a query made from a DbQuery definition; " + + "for a command, call AddParam before Map."; static DbQueryCall CallOf(MappedQuery query) => query.TryGetCall(out DbQueryCall call) ? call - : throw new InvalidOperationException(MappedDbQueryMessages.NotFromADefinition); + : throw new InvalidOperationException(_notFromADefinition); /// Adds a named parameter to the query. /// The type each row is mapped to. diff --git a/Source/Core/OutputBinding.cs b/Source/Core/OutputBinding.cs index 7af22f32..957b2dd4 100644 --- a/Source/Core/OutputBinding.cs +++ b/Source/Core/OutputBinding.cs @@ -30,7 +30,10 @@ interface IInputLookup /// static class OutputBinding { - /// How the messages name a command that is not a stored procedure. + + /// + /// How the messages name a command that is not a stored procedure. + /// public const string TextCommandName = "the command text"; @@ -291,7 +294,9 @@ static InvalidOperationException NoOutputMatch( + "Change the [Column] name to one it declares, or add the parameter."); } - string noMatch = $"{member.Display} has no matching parameter on {where} (tried {string.Join(", ", ParameterNames.Candidates(member.Name))}; it declares: {declared}). "; + string noMatch = $"{member.Display} has no matching parameter on {where} " + + $"(tried {string.Join(", ", ParameterNames.Candidates(member.Name))}; " + + $"it declares: {declared}). "; if (member.ReceivedName is { } received) { // A model capture maps by its members: the name it was given (typed, diff --git a/Source/Core/ProcedureSchemaNames.cs b/Source/Core/ProcedureSchemaNames.cs index b1022ebb..75f9b8e3 100644 --- a/Source/Core/ProcedureSchemaNames.cs +++ b/Source/Core/ProcedureSchemaNames.cs @@ -18,8 +18,8 @@ static class ProcedureSchemaNames /// /// The query of the two SQL Server packages for the parameter names of a - /// procedure, in ordinal order: it takes the procedure's name as @procedure - /// and answers nothing for a name that has a database part. + /// procedure, in ordinal order: it takes the procedure's name as + /// @procedure and answers nothing for a name that has a database part. /// public const string SqlServerQuery = "select name from sys.all_parameters " diff --git a/Source/Core/ReaderAbandon.cs b/Source/Core/ReaderAbandon.cs index 42c0a290..83a5083c 100644 --- a/Source/Core/ReaderAbandon.cs +++ b/Source/Core/ReaderAbandon.cs @@ -23,6 +23,7 @@ namespace Open.Database.Extensions.Core; /// internal sealed class ReaderAbandon { + /// The name of the option, as the messages write it. public const string Option = "CancelOnEarlyStop()"; diff --git a/Tests/Open.Database.Extensions.Core.Tests/DerivedNameCostTests.cs b/Tests/Open.Database.Extensions.Core.Tests/DerivedNameCostTests.cs index 868e8af0..5652f701 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/DerivedNameCostTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/DerivedNameCostTests.cs @@ -607,7 +607,7 @@ public static void Collision_MessagesArePinned() { var rig = new ProcRig("@region"); const int region = 1, Region = 2; - string tail = $" The procedure '{rig.Procedure}' declares: @region. Name one of them explicitly: AddParam(\"name\", value)."; + string tail = $" The procedure '{rig.Procedure}' declares: @region. {ParameterNameMessages.NameOneExplicitly}"; var twoArguments = Assert.Throws(() => rig.Run(c => c.AddParam(region).AddParam(Region))); Assert.Equal("Two parameters resolve to '@region': the argument 'region' and the argument 'Region'." + tail, twoArguments.Message); @@ -647,7 +647,7 @@ public static void ObjectMemberThatCannotBeDerived_ThrowsArgumentException_OnEve { var ex = Assert.Throws(() => rig.Run(c => c.AddParams(item))); Assert.Equal("expression", ex.ParamName); - Assert.Equal("Cannot derive a parameter name from the expression 'default'. (Parameter 'expression')", ex.Message); + Assert.Equal(ParameterNameMessages.CannotDerive("default") + " (Parameter 'expression')", ex.Message); } } @@ -663,8 +663,8 @@ public static void TextCommandWithoutMarkers_CollisionMessageSaysTheNamesAreNotK () => new ExpressiveDbCommand(connection, CommandType.Text, "select 1").AddParam(region).AddParam(Region).ExecuteNonQuery()); Assert.Equal( "Two parameters resolve to 'region': the argument 'region' and the argument 'Region'. " - + "The parameter names are not known, so each argument is used under its last member as written. " - + "Name one of them explicitly: AddParam(\"name\", value).", + + ParameterNameMessages.NotKnown + " " + + ParameterNameMessages.NameOneExplicitly, ex.Message); } diff --git a/Tests/Open.Database.Extensions.Core.Tests/MappedDbQueryTests.cs b/Tests/Open.Database.Extensions.Core.Tests/MappedDbQueryTests.cs index 50c89faa..b9031642 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/MappedDbQueryTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/MappedDbQueryTests.cs @@ -473,7 +473,7 @@ public static void ParamsAfterUsing_OnAViewNotMadeFromADefinition_Throw() MappedQuery classic = c.Command("select 1").Map(); const string expected - = MappedDbQueryMessages.NotFromADefinition; + = MappedDbQueryExtensions._notFromADefinition; const int a = 1; Assert.Equal(expected, Assert.Throws(() => classic.AddParam("a", 1)).Message); diff --git a/Tests/Open.Database.Extensions.Core.Tests/UnmappableTypeTests.cs b/Tests/Open.Database.Extensions.Core.Tests/UnmappableTypeTests.cs index 5f712606..741c590d 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/UnmappableTypeTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/UnmappableTypeTests.cs @@ -121,7 +121,7 @@ static string Single(string name) static string Ambiguous(string name, int count, string signatures) => RowMapMessages.Ambiguous(name, count, signatures); static string ByReference(string name, string parameter) => RowMapMessages.ByReference(name, parameter); static string RequiredField(string name, string field) => RowMapMessages.RequiredField(name, field); - static string Bag(string name) => RowMapMessages.Bag(name); + static string DictionaryOrDynamic(string name) => RowMapMessages.DictionaryOrDynamic(name); // A dictionary or a dynamic object is not a row model: it has no properties to set, so a map of it used to build one empty row and say nothing. Each of these kinds is reached by a different interface. public sealed class DictionaryOfMine : Dictionary; @@ -280,14 +280,14 @@ public static void ARequiredPublicField_IsRejected_AtTheCall_AnInheritedOneToo() [Fact] public static void ADictionaryOrADynamicObject_IsRejected_AtTheCall_WhateverInterfaceMakesItOne() { - AssertUnmappable>(Bag("Dictionary`2")); - AssertUnmappable>(Bag("ImmutableDictionary`2")); // it has no public constructor either: this is the reason given - AssertUnmappable(Bag("Hashtable")); // the non-generic IDictionary - AssertUnmappable(Bag("DictionaryOfMine")); // a type derived from one - AssertUnmappable(Bag("OnlyReadOnlyDictionary")); // IReadOnlyDictionary<,> alone - AssertUnmappable(Bag("ExpandoObject")); - AssertUnmappable(Bag("DynamicBag")); // a DynamicObject - AssertUnmappable(Bag("OnlyMetaObjectProvider")); // IDynamicMetaObjectProvider alone + AssertUnmappable>(DictionaryOrDynamic("Dictionary`2")); + AssertUnmappable>(DictionaryOrDynamic("ImmutableDictionary`2")); // it has no public constructor either: this is the reason given + AssertUnmappable(DictionaryOrDynamic("Hashtable")); // the non-generic IDictionary + AssertUnmappable(DictionaryOrDynamic("DictionaryOfMine")); // a type derived from one + AssertUnmappable(DictionaryOrDynamic("OnlyReadOnlyDictionary")); // IReadOnlyDictionary<,> alone + AssertUnmappable(DictionaryOrDynamic("ExpandoObject")); + AssertUnmappable(DictionaryOrDynamic("DynamicBag")); // a DynamicObject + AssertUnmappable(DictionaryOrDynamic("OnlyMetaObjectProvider")); // IDynamicMetaObjectProvider alone } [Fact] From 2172e4c09b11aa73769b1ea4410c1b48c10276d0 Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Fri, 4 Dec 2026 10:07:56 -0800 Subject: [PATCH 6/9] Second review round of the message sweep: one text for each fact, and the fix in every message Messages may change here, by the owner's rules. A message that says what is wrong now also says what to do, and a text is written once. - The empty-command text of CreateCommand (Core, SqlClient, and Transaction.CreateCommand) is CommandTextMessages.Blank; EmptyOrWhiteSpace is gone. - One "cannot derive a parameter name" text, ParameterNameMessages.CannotDerive, with the fix and filter.AuthorId as the example, used by DbQueryCall, ExpressiveCommandBase and ParameterNames. - The DataReaderExtensions justification reads SuppressionJustifications.OverloadForEasierConsumption. - ArgumentMessages.NotNegative, RowMapMessages.NoConstructor and RowMapMessages.NoPropertyName now say what to do; docsite/articles/mapping.md shows the new constructor text. - New homes for texts the tests copied: the collision and ambiguity of parameter names (ParameterNameMessages), the empty column name (RowMapMessages.EmptyColumn), the capture sync-call fact (CaptureMessages.OnlyAsyncTerminals), the delivered-output fix (OutputRun.ReadToTheEnd), and the sources named by the CancelOnEarlyStop refusal (ReaderAbandon). The tests reference them. - Four sentences that Capture.cs wrote twice are consts of CaptureMessages. The public API is unchanged. Co-Authored-By: Claude Sonnet 5.5 --- Source/Core/Capture.cs | 53 +++++-- Source/Core/Core/ArgumentMessages.cs | 2 +- Source/Core/Core/CommandTextMessages.cs | 5 +- Source/Core/Core/ParameterNameMessages.cs | 136 +++++++++++++++++- Source/Core/Core/RowMap.cs | 8 +- Source/Core/Core/RowMapMessages.cs | 15 +- Source/Core/DbQueryBinding.cs | 9 +- Source/Core/DbQueryCall.cs | 2 +- Source/Core/ExpressiveCommandBase.cs | 16 ++- .../Extensions/Connection.CreateCommand.cs | 2 +- Source/Core/Extensions/DataReader.cs | 2 +- Source/Core/OutputBinding.cs | 3 +- Source/Core/OutputLayout.cs | 11 +- Source/Core/ParameterNames.cs | 14 +- Source/Core/ReaderAbandon.cs | 13 +- .../Extensions/Connection.CreateCommand.cs | 2 +- .../Extensions/Transaction.CreateCommand.cs | 2 +- .../AddParamIfConditionTests.cs | 2 +- .../CancelOnEarlyStopStreamTests.cs | 7 +- .../CaptureDefinitionLocalDbTests.cs | 2 +- .../CaptureStreamTests.cs | 2 +- .../CaptureTests.cs | 2 +- .../ConstructorBindingTests.cs | 2 +- .../DbQueryTests.cs | 6 +- .../DerivedNameCostTests.cs | 32 ++++- .../DerivedNamesEveryRunTests.cs | 2 +- .../DerivedParameterNameTests.cs | 12 +- .../MappingCharacterizationTests.cs | 2 +- .../OutputParameterTests.cs | 2 +- .../ParameterNameAddParamsTests.cs | 16 ++- .../ParameterNameEndToEndTests.cs | 6 +- .../ParameterNameExplicitTests.cs | 10 +- .../ParameterNameMatrixTests.cs | 6 +- .../ParameterNameMessageTests.cs | 16 +-- .../ParameterNamePrefixTests.cs | 8 +- .../SqlTextDerivedNamesTests.cs | 4 +- docsite/articles/mapping.md | 2 +- 37 files changed, 334 insertions(+), 102 deletions(-) diff --git a/Source/Core/Capture.cs b/Source/Core/Capture.cs index 62242b22..8eef33d5 100644 --- a/Source/Core/Capture.cs +++ b/Source/Core/Capture.cs @@ -1027,6 +1027,35 @@ public const string ToListInstead public const string ExecuteNonQueryInstead = "ExecuteNonQueryAsync instead of ExecuteNonQuery"; + /// + /// Why a text command cannot give a return code, in the messages that + /// need a stored procedure. + /// + public const string NoReturnCodeInText + = "a text command has no return code, " + + "and the provider would report 0. "; + + /// The fix of a message that needs a stored procedure. + public const string CallByName + = "Call the procedure by name with StoredProcedure(…), "; + + /// The last resort of a message about a capture. + public const string OrRemoveTheCapture + = "or remove the capture."; + + /// + /// The last resort of a message about a capture that has no command to fill. + /// + public const string OrReadWithExecuteOutputAsync + = "or read the outputs with ExecuteOutputAsync."; + + /// + /// The fact a sync call of a command with a capture runs into, + /// in the message of that call. + /// + public const string OnlyAsyncTerminals + = "captures only work with async terminals"; + public static string NotStarted(string display) => $"{display} has not started: " + "the query it belongs to has not been run, " @@ -1054,11 +1083,11 @@ public static string StreamOpen(string display) public static string Sync(CaptureSet set) => $"This {set.Noun} has {set.Displays}, " - + "and captures only work with async terminals. " + + $"and {OnlyAsyncTerminals}. " + $"Use the async form of this call (for example {(set.OnQuery ? ToListInstead : ExecuteNonQueryInstead)}), " - + "or remove the capture."; + + OrRemoveTheCapture; public static string SecondRun(CaptureSet set) { @@ -1101,16 +1130,14 @@ public static string CancelOnEarlyStop(CaptureSet set) public static string NotProcedure(ICaptureSource source) => source.Kind == CaptureKind.Return ? $"{source.Display} needs a stored procedure: " - + "a text command has no return code, " - + "and the provider would report 0. " - + "Call the procedure by name with StoredProcedure(…), " - + "or remove the capture." + + NoReturnCodeInText + + CallByName + + OrRemoveTheCapture : $"{source.Display} reads the return code into the ReturnValue " + $"member of {source.Model}, " + "which needs a stored procedure: " - + "a text command has no return code, " - + "and the provider would report 0. " - + "Call the procedure by name with StoredProcedure(…), " + + NoReturnCodeInText + + CallByName + "or give the member [Column(\"name\")] to read an output " + "parameter instead."; @@ -1120,9 +1147,7 @@ public static string NotDelivered(ICaptureSource source) : $"The output parameters of {source.Display} were never delivered") + ": the response ended without them (a later statement failed, " + "or the call was cut short). The procedure may still have run. " - + "Read the results to the end without stopping early, " - + "check the procedure for an error raised after its result sets, " - + "and treat the call as possibly committed."; + + OutputRun.ReadToTheEnd; public static string NotRun(ICaptureSource source) => $"{source.Display} has no value: " @@ -1149,14 +1174,14 @@ public static string NotFromCommand(ICaptureSource source, Type reader) + "which adds the output parameters; " + $"this query reads from {reader.Name}, which cannot. " + "Build it from an expressive command, " - + "or read the outputs with ExecuteOutputAsync."; + + OrReadWithExecuteOutputAsync; public static string ReplacedReader(string display, Type command) => $"{display} reads through the library's reader, " + $"which {command.Name} replaces by re-implementing IExecuteReader, " + "so the outputs would never be read. " + "Capture on a command that does not re-implement IExecuteReader, " - + "or read the outputs with ExecuteOutputAsync."; + + OrReadWithExecuteOutputAsync; public static string ReplacementUnknown(Type command, string reason) => $"Could not tell whether {command.Name} re-implements " diff --git a/Source/Core/Core/ArgumentMessages.cs b/Source/Core/Core/ArgumentMessages.cs index 1f510e51..b9212965 100644 --- a/Source/Core/Core/ArgumentMessages.cs +++ b/Source/Core/Core/ArgumentMessages.cs @@ -9,5 +9,5 @@ internal static class ArgumentMessages /// A count or an index is below zero. public const string NotNegative - = "Cannot be negative."; + = "Cannot be negative. Pass zero or more."; } diff --git a/Source/Core/Core/CommandTextMessages.cs b/Source/Core/Core/CommandTextMessages.cs index 2a8a7af9..efd78bbc 100644 --- a/Source/Core/Core/CommandTextMessages.cs +++ b/Source/Core/Core/CommandTextMessages.cs @@ -6,12 +6,9 @@ namespace Open.Database.Extensions; /// 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."; - - /// A command's text is empty or white space, in the check that names the argument. - public const string EmptyOrWhiteSpace - = "Command is empty or whitespace."; } diff --git a/Source/Core/Core/ParameterNameMessages.cs b/Source/Core/Core/ParameterNameMessages.cs index 0b4baf97..7a99e7ab 100644 --- a/Source/Core/Core/ParameterNameMessages.cs +++ b/Source/Core/Core/ParameterNameMessages.cs @@ -6,6 +6,7 @@ namespace Open.Database.Extensions; /// 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. " @@ -15,6 +16,19 @@ public const string Blank public const string NullOnlyForReturn = "Parameter names can only be null for a return parameter."; + /// + /// The words before the names a procedure declares, in the message of an + /// argument that matches none of them. + /// + public const string ProcedureDeclares + = "The procedure declares"; + + /// + /// The call that names a parameter, as the fix of a message writes it. + /// + public const string AddParamWithName + = "AddParam(\"name\", value)"; + /// /// The names of a procedure's parameters are not known, so a collision is /// explained without them. @@ -25,13 +39,20 @@ public const string NotKnown /// The fix of a collision between two parameters. public const string NameOneExplicitly - = "Name one of them explicitly: AddParam(\"name\", value)."; + = "Name one of them explicitly: " + AddParamWithName + "."; + + /// + /// The fix of an argument that matches none of the parameters + /// or more than one. + /// + public const string NameParameterExplicitly + = "Name the parameter explicitly: " + AddParamWithName + "."; /// The compiler did not supply the text of an argument. public const string NotSupplied = "The compiler did not supply the argument's text " + "(deriving a name needs C# 10 or newer). " - + "Pass the name explicitly: AddParam(\"name\", value)."; + + "Pass the name explicitly: " + AddParamWithName + "."; /// A tier of the name match: the names are the same. public const string TierExactly @@ -60,11 +81,114 @@ public const string TierWithoutPrefix + "is removed from the real name"; /// - /// A parameter name cannot be derived from an expression. + /// The start of the message of two parameters that resolve to one name. + /// + public const string TwoParametersResolveTo + = "Two parameters resolve to"; + + /// + /// A parameter name cannot be derived from an argument. /// - /// The text of the expression. + /// The text of the argument. /// The message. public static string CannotDerive(string expression) - => $"Cannot derive a parameter name from the expression " - + $"'{expression}'."; + => $"Cannot derive a parameter name from {WrittenAsArgument(expression)}. " + + "Pass a variable or a chain of members such as filter.AuthorId, " + + $"or name the parameter: {AddParamWithName}."; + + /// + /// Two parameters resolve to one name, in a message that does not say + /// what the caller wrote for each. + /// + /// The name. + /// The first sentence of the message. + public static string Collision(string name) + => $"{TwoParametersResolveTo} '{name}'."; + + /// + /// Two parameters resolve to one name, saying what the caller wrote for each. + /// + /// The name. + /// What was written for the first parameter. + /// What was written for the second parameter. + /// The first sentence of the message. + public static string Collision(string name, string first, string second) + => $"{TwoParametersResolveTo} '{name}': {first} and {second}."; + + /// What was written for a parameter: an argument. + /// The text of the argument. + /// The description. + public static string WrittenAsArgument(string expression) + => $"the argument '{expression}'"; + + /// + /// What was written for a parameter: a member of an object passed to + /// AddParams. + /// + /// The member. + /// The description. + public static string WrittenAsMember(string member) + => $"the member '{member}' of the AddParams object"; + + /// What was written for a parameter: a name. + /// The name. + /// The description. + public static string WrittenAsName(string name) + => $"the name '{name}' you passed"; + + /// The subject of a message about an argument. + /// The text of the argument. + /// The subject. + public static string TheArgument(string expression) + => $"The argument '{expression}'"; + + /// + /// The fix of a member that fits more than one parameter, + /// when it can carry its own name. + /// + /// The member. + /// The fix. + public static string NameWithColumn(string subject) + => "Name its parameter exactly with [Column(\"name\")] on " + + $"{subject}."; + + /// An argument fits more than one parameter. + /// What was written, as the message starts. + /// The first parameter it fits. + /// The second parameter it fits. + /// The procedure. + /// The candidate name that fits both. + /// How the candidate fits them. + /// The parameters the procedure declares. + /// What to do. + /// The message. + public static string Ambiguous( + string subject, + string first, + string second, + string procedure, + string candidate, + string tier, + string declared, + string fix) + => $"{subject} matches both '{first}' and '{second}' of '{procedure}'. " + + $"Its candidate name '{candidate}' fits each of them {tier}. " + + $"The procedure declares: {declared}. {fix}"; + + /// An argument fits none of the parameters. + /// The text of the argument. + /// The command text or the procedure. + /// The candidate names that were tried. + /// The words before the declared names. + /// The parameters the owner declares. + /// The message. + public static string NoMatch( + string expression, + string owner, + string tried, + string declares, + string declared) + => $"{TheArgument(expression)} matches none of the parameters " + + $"of '{owner}' (tried {tried}). " + + $"{declares}: {declared}. {NameParameterExplicitly}"; } diff --git a/Source/Core/Core/RowMap.cs b/Source/Core/Core/RowMap.cs index 15dcd6da..be325b96 100644 --- a/Source/Core/Core/RowMap.cs +++ b/Source/Core/Core/RowMap.cs @@ -1037,7 +1037,13 @@ bool[] Declare(ReadOnlySpan> mappings, string?[] c named[index] = true; } - if (pair.Value is { Length: 0 }) throw new ArgumentException($"The property '{pair.Key}' is mapped to an empty column name. Use null to ignore it.", paramName); + if (pair.Value is { Length: 0 }) + { + throw new ArgumentException( + RowMapMessages.EmptyColumn(pair.Key), + paramName); + } + if (!known) throw new ArgumentException(UnknownMember(pair.Key), paramName); if (pair.Value is null && _slots[index].Required) throw new ArgumentException($"The property '{_slots[index].Name}' is required, so it cannot be mapped to null. Map it to a column.", paramName); diff --git a/Source/Core/Core/RowMapMessages.cs b/Source/Core/Core/RowMapMessages.cs index bbd80976..fb5d6d1d 100644 --- a/Source/Core/Core/RowMapMessages.cs +++ b/Source/Core/Core/RowMapMessages.cs @@ -23,7 +23,17 @@ public const string AbstractClass /// A mapping pair has no property name. public const string NoPropertyName - = "A mapping has no property name."; + = "A mapping has no property name. " + + "Give each pair the name of a property, or remove the pair."; + + /// + /// A property is mapped to an empty column name. + /// + /// The property's name. + /// The message. + public static string EmptyColumn(string property) + => $"The property '{property}' is mapped to an empty column name. " + + "Use null to ignore it."; /// /// The type is a single value, so it is a column, not a row model. @@ -61,7 +71,8 @@ public static string DictionaryOrDynamic(string name) /// The type's name. /// The message. public static string NoConstructor(string name) - => $"'{name}' cannot be mapped: it has no public constructor."; + => $"'{name}' cannot be mapped: it has no public constructor. " + + "Give it a public constructor, or use Map(selector)."; /// /// The type has more than one public constructor diff --git a/Source/Core/DbQueryBinding.cs b/Source/Core/DbQueryBinding.cs index 8fdf2e6a..30149aeb 100644 --- a/Source/Core/DbQueryBinding.cs +++ b/Source/Core/DbQueryBinding.cs @@ -294,7 +294,7 @@ static InvalidOperationException Collision( string name, DbQuery definition, NameSet? names) - => new($"Two parameters resolve to '{name}'. " + => new(ParameterNameMessages.Collision(name) + " " + (Known(names) ? $"'{definition.CommandText}' declares: {string.Join(", ", names!.Names)}." : ParameterNameMessages.NotKnown) @@ -307,5 +307,10 @@ public static InvalidOperationException NoMatch( string owner, string declares, ImmutableArray declared) - => new($"The argument '{expression}' matches none of the parameters of '{owner}' (tried {string.Join(", ", ParameterNames.Candidates(expression))}). {declares}: {string.Join(", ", declared)}. Name the parameter explicitly: AddParam(\"name\", value)."); + => new(ParameterNameMessages.NoMatch( + expression, + owner, + string.Join(", ", ParameterNames.Candidates(expression)), + declares, + string.Join(", ", declared))); } diff --git a/Source/Core/DbQueryCall.cs b/Source/Core/DbQueryCall.cs index 4a29ca7f..47264444 100644 --- a/Source/Core/DbQueryCall.cs +++ b/Source/Core/DbQueryCall.cs @@ -213,7 +213,7 @@ internal static ParameterNames.DerivedExpression CheckedExpression( ParameterNameMessages.NotSupplied, "value") : new ArgumentException( - $"Cannot derive a parameter name from the argument '{expression}'. Pass a variable or a chain of members such as filter.AuthorId, or name the parameter: AddParam(\"name\", value).", + ParameterNameMessages.CannotDerive(expression), "value")); /// diff --git a/Source/Core/ExpressiveCommandBase.cs b/Source/Core/ExpressiveCommandBase.cs index e27a1bb3..6730160e 100644 --- a/Source/Core/ExpressiveCommandBase.cs +++ b/Source/Core/ExpressiveCommandBase.cs @@ -605,7 +605,7 @@ TThis AddDerivedParam(object? value, string? expression, Type clrType) static ArgumentException NotDerivable(string? expression) => expression is null ? new(ParameterNameMessages.NotSupplied, "value") - : new($"Cannot derive a parameter name from the argument '{expression}'. Pass a variable or a chain of members such as filter.CompanySerialNum, or name the parameter: AddParam(\"name\", value).", "value"); + : new(ParameterNameMessages.CannotDerive(expression), "value"); /// /// Conditionally adds a parameter to the params list. @@ -1212,11 +1212,17 @@ void Apply( /// The description. static string Written(Param original) => original.Expression is { } expression - ? original.FromObject ? $"the member '{expression}' of the AddParams object" : $"the argument '{expression}'" - : $"the name '{original.Name}' you passed"; + ? original.FromObject + ? ParameterNameMessages.WrittenAsMember(expression) + : ParameterNameMessages.WrittenAsArgument(expression) + : ParameterNameMessages.WrittenAsName(original.Name); InvalidOperationException Collision(string name, Param first, Param second, ImmutableArray real) - => new($"Two parameters resolve to '{name}': {Written(first)} and {Written(second)}. " + => new(ParameterNameMessages.Collision( + name, + Written(first), + Written(second)) + + " " + (real.IsDefaultOrEmpty ? ParameterNameMessages.NotKnown : $"The procedure '{Command}' declares: {string.Join(", ", real)}.") @@ -1224,7 +1230,7 @@ InvalidOperationException Collision(string name, Param first, Param second, Immu InvalidOperationException NoMatch(string expression, ImmutableArray real) => DbQueryBinding.NoMatch( - expression, Command, "The procedure declares", real); + expression, Command, ParameterNameMessages.ProcedureDeclares, real); #endregion diff --git a/Source/Core/Extensions/Connection.CreateCommand.cs b/Source/Core/Extensions/Connection.CreateCommand.cs index dc1c3f28..6065ebc3 100644 --- a/Source/Core/Extensions/Connection.CreateCommand.cs +++ b/Source/Core/Extensions/Connection.CreateCommand.cs @@ -6,7 +6,7 @@ public static partial class ConnectionExtensions internal static void CheckCommandText(string commandText) { if (commandText is null) throw new ArgumentNullException(nameof(commandText)); - if (string.IsNullOrWhiteSpace(commandText)) throw new ArgumentException(CommandTextMessages.EmptyOrWhiteSpace, nameof(commandText)); + if (string.IsNullOrWhiteSpace(commandText)) throw new ArgumentException(CommandTextMessages.Blank, nameof(commandText)); } // A command that cannot be set up is never returned, so nobody else can dispose it: it is disposed here. diff --git a/Source/Core/Extensions/DataReader.cs b/Source/Core/Extensions/DataReader.cs index d4ec4a9c..1a1f9d60 100644 --- a/Source/Core/Extensions/DataReader.cs +++ b/Source/Core/Extensions/DataReader.cs @@ -6,7 +6,7 @@ namespace Open.Database.Extensions; /// Provides extension methods that read rows and result sets from an or . /// #pragma warning disable IDE0079 // Remove unnecessary suppression -[SuppressMessage("Design", AnalyzerIds.CA1068, Justification = "Overload provided for convienience.")] +[SuppressMessage("Design", AnalyzerIds.CA1068, Justification = SuppressionJustifications.OverloadForEasierConsumption)] [SuppressMessage("Reliability", "CA2016:Forward the 'CancellationToken' parameter to methods that take one", Justification = "Intentional to prevent cancellation exception.")] #pragma warning restore IDE0079 // Remove unnecessary suppression public static class DataReaderExtensions diff --git a/Source/Core/OutputBinding.cs b/Source/Core/OutputBinding.cs index 957b2dd4..c23b71be 100644 --- a/Source/Core/OutputBinding.cs +++ b/Source/Core/OutputBinding.cs @@ -358,7 +358,8 @@ public static void Add( IDbDataParameter parameter = FindParameter(command, inputName) ?? throw new InvalidOperationException( $"{member.Display} reads back the parameter '{inputName}', which was given a value, but the command's provider did not add it to the command under that name, so there is nothing to read. " - + "Give the value under the name the provider keeps (AddParam(\"name\", value)), or do not give it a value so it is sent as an output only."); + + $"Give the value under the name the provider keeps ({ParameterNameMessages.AddParamWithName}), " + + "or do not give it a value so it is sent as an output only."); parameter.Direction = ParameterDirection.InputOutput; if (!typed) parameter.DbType = wire.Type; wire.Apply(parameter); diff --git a/Source/Core/OutputLayout.cs b/Source/Core/OutputLayout.cs index b89ca032..8e7eaf12 100644 --- a/Source/Core/OutputLayout.cs +++ b/Source/Core/OutputLayout.cs @@ -776,6 +776,15 @@ static string Message(string name, string display, OutputForm form) // the same path. class OutputRun(OutputLayout layout) { + + /// + /// What to do when an output was not delivered, as the message says it. + /// + public const string ReadToTheEnd + = "Read the results to the end without stopping early, " + + "check the procedure for an error raised after its result sets, " + + "and treat the call as possibly committed."; + /// What the call reads. public readonly OutputLayout Layout = layout; @@ -829,7 +838,7 @@ public void Snapshot() string which = member.IsReturnValue ? "the return code was" : $"the output parameter '{Names![index]}' was"; throw new InvalidOperationException( $"{member.Display} has no value after {Where} ran: {which} not delivered, because the response did not complete (as when a statement after the outputs are set fails). Nothing is read as NULL. " - + "Read the results to the end without stopping early, check the procedure for an error raised after its result sets, and treat the call as possibly committed."); + + ReadToTheEnd); } return value; diff --git a/Source/Core/ParameterNames.cs b/Source/Core/ParameterNames.cs index 190bc07e..d08a493b 100644 --- a/Source/Core/ParameterNames.cs +++ b/Source/Core/ParameterNames.cs @@ -348,9 +348,17 @@ static bool ClosesAt(string s, int open, int close) if (found is not null) { throw new InvalidOperationException( - $"{subject ?? $"The argument '{expression}'"} matches both '{found}' and '{real}' of '{procedure}'. " - + $"Its candidate name '{candidate}' fits each of them {TierText(tier)}. " - + $"The procedure declares: {string.Join(", ", parameterNames)}. {fix ?? (subject is null ? "Name the parameter explicitly: AddParam(\"name\", value)." : $"Name its parameter exactly with [Column(\"name\")] on {subject}.")}"); + ParameterNameMessages.Ambiguous( + subject ?? ParameterNameMessages.TheArgument(expression), + found, + real, + procedure, + candidate, + TierText(tier), + string.Join(", ", parameterNames), + fix ?? (subject is null + ? ParameterNameMessages.NameParameterExplicitly + : ParameterNameMessages.NameWithColumn(subject)))); } found = real; diff --git a/Source/Core/ReaderAbandon.cs b/Source/Core/ReaderAbandon.cs index 83a5083c..57015e5d 100644 --- a/Source/Core/ReaderAbandon.cs +++ b/Source/Core/ReaderAbandon.cs @@ -27,6 +27,16 @@ internal sealed class ReaderAbandon /// The name of the option, as the messages write it. public const string Option = "CancelOnEarlyStop()"; + /// + /// A source that has no command, as the message of a refusal names it. + /// + public const string DataReaderSource = "a data reader"; + + /// + /// A source that has no command, as the message of a refusal names it. + /// + public const string DataTableSource = "a DataTable"; + // Read when this is made: a TransactionScope without async flow is not seen after an await or on another thread. readonly bool _ambient = System.Transactions.Transaction.Current is not null; @@ -143,7 +153,8 @@ void RequireArmed() /// /// The exception. public static InvalidOperationException NoCommand() - => new(Option + " needs the command, and this source does not hand one out (a data reader, a DataTable or your own IExecuteReader)." + => new(Option + " needs the command, and this source does not hand one out (" + + DataReaderSource + ", " + DataTableSource + " or your own IExecuteReader)." + " Remove " + Option + ", or map a DbQuery, an expressive command or an IDbCommand."); // The one predicate: it refuses the command before it runs, and is what the cancel asserts. diff --git a/Source/SqlClient/Extensions/Connection.CreateCommand.cs b/Source/SqlClient/Extensions/Connection.CreateCommand.cs index 594af349..215233a3 100644 --- a/Source/SqlClient/Extensions/Connection.CreateCommand.cs +++ b/Source/SqlClient/Extensions/Connection.CreateCommand.cs @@ -20,7 +20,7 @@ public static SqlCommand CreateCommand(this SqlConnection connection, { if (connection is null) throw new ArgumentNullException(nameof(connection)); if (commandText is null) throw new ArgumentNullException(nameof(commandText)); - if (string.IsNullOrWhiteSpace(commandText)) throw new ArgumentException(CommandTextMessages.EmptyOrWhiteSpace, nameof(commandText)); + if (string.IsNullOrWhiteSpace(commandText)) throw new ArgumentException(CommandTextMessages.Blank, nameof(commandText)); Contract.EndContractBlock(); SqlCommand command = connection.CreateCommand(); diff --git a/Source/SqlClient/Extensions/Transaction.CreateCommand.cs b/Source/SqlClient/Extensions/Transaction.CreateCommand.cs index 1f43cf68..94ada360 100644 --- a/Source/SqlClient/Extensions/Transaction.CreateCommand.cs +++ b/Source/SqlClient/Extensions/Transaction.CreateCommand.cs @@ -17,7 +17,7 @@ public static SqlCommand CreateCommand(this SqlTransaction transaction, { if (transaction is null) throw new ArgumentNullException(nameof(transaction)); if (commandText is null) throw new ArgumentNullException(nameof(commandText)); - if (string.IsNullOrWhiteSpace(commandText)) throw new ArgumentException(CommandTextMessages.EmptyOrWhiteSpace, nameof(commandText)); + if (string.IsNullOrWhiteSpace(commandText)) throw new ArgumentException(CommandTextMessages.Blank, nameof(commandText)); Contract.EndContractBlock(); SqlCommand command = transaction diff --git a/Tests/Open.Database.Extensions.Core.Tests/AddParamIfConditionTests.cs b/Tests/Open.Database.Extensions.Core.Tests/AddParamIfConditionTests.cs index 07d9a026..b7e076ec 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/AddParamIfConditionTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/AddParamIfConditionTests.cs @@ -78,7 +78,7 @@ static void Throws(Action add) { var ex = Assert.Throws(add); Assert.Equal("value", ex.ParamName); - Assert.Contains("AddParam(\"name\", value)", ex.Message); + Assert.Contains(ParameterNameMessages.AddParamWithName, ex.Message); } Throws(() => classic.AddParamIf(true, 1)); diff --git a/Tests/Open.Database.Extensions.Core.Tests/CancelOnEarlyStopStreamTests.cs b/Tests/Open.Database.Extensions.Core.Tests/CancelOnEarlyStopStreamTests.cs index 228094a2..41550640 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/CancelOnEarlyStopStreamTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/CancelOnEarlyStopStreamTests.cs @@ -306,7 +306,12 @@ public static async Task AReaderOrTableView_RefusesWhenItRuns(string view) InvalidOperationException thrown = await Assert.ThrowsAsync(async () => await query.FirstOrDefaultAsync(Ct)); Assert.StartsWith(global::Open.Database.Extensions.Core.ReaderAbandon.Option, thrown.Message, StringComparison.Ordinal); - Assert.Contains(view == "reader" ? "a data reader" : "a DataTable", thrown.Message, StringComparison.Ordinal); + Assert.Contains( + view == "reader" + ? global::Open.Database.Extensions.Core.ReaderAbandon.DataReaderSource + : global::Open.Database.Extensions.Core.ReaderAbandon.DataTableSource, + thrown.Message, + StringComparison.Ordinal); thrown = Assert.Throws(() => query.FirstOrDefault()); Assert.StartsWith(global::Open.Database.Extensions.Core.ReaderAbandon.Option, thrown.Message, StringComparison.Ordinal); diff --git a/Tests/Open.Database.Extensions.Core.Tests/CaptureDefinitionLocalDbTests.cs b/Tests/Open.Database.Extensions.Core.Tests/CaptureDefinitionLocalDbTests.cs index 0932ac5a..08c69592 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/CaptureDefinitionLocalDbTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/CaptureDefinitionLocalDbTests.cs @@ -180,7 +180,7 @@ public static async Task ASynchronousTerminal_WithACapture_IsRefusedAndClaimsNot var ex = Assert.Throws(() => query.ToList()); - Assert.Contains("captures only work with async terminals", ex.Message); + Assert.Contains(CaptureMessages.OnlyAsyncTerminals, ex.Message); // Nothing was claimed: the async terminal still runs it. await query.ToListAsync(Token); Assert.Equal(new Page(31, 3), await page); diff --git a/Tests/Open.Database.Extensions.Core.Tests/CaptureStreamTests.cs b/Tests/Open.Database.Extensions.Core.Tests/CaptureStreamTests.cs index 4bca471f..4132cadc 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/CaptureStreamTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/CaptureStreamTests.cs @@ -782,7 +782,7 @@ public static void ACommandCapture_OnAReimplementingCommand_RefusesSync() Contains( Assert.Throws(() => query.ToList()), - "captures only work with async terminals"); + CaptureMessages.OnlyAsyncTerminals); Assert.Equal(0, command.OwnReads); Assert.Equal(0, c.Executed); Contains( diff --git a/Tests/Open.Database.Extensions.Core.Tests/CaptureTests.cs b/Tests/Open.Database.Extensions.Core.Tests/CaptureTests.cs index cf40e060..49987d02 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/CaptureTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/CaptureTests.cs @@ -185,7 +185,7 @@ public static void ASynchronousTerminal_Throws_AndArmsNothing() var ex = Assert.Throws( () => command.ExecuteNonQuery()); Contains(ex, - "captures only work with async terminals", + CaptureMessages.OnlyAsyncTerminals, CaptureMessages.ExecuteNonQueryInstead); Assert.Equal(0, c.Executed); diff --git a/Tests/Open.Database.Extensions.Core.Tests/ConstructorBindingTests.cs b/Tests/Open.Database.Extensions.Core.Tests/ConstructorBindingTests.cs index ff928efc..2a88f55a 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/ConstructorBindingTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/ConstructorBindingTests.cs @@ -449,7 +449,7 @@ public static void TwoParametersOnOneColumn_Throw_NamingBothAndTheColumn() public static void AnEmptyColumnName_AndANullName_StillThrow_ForAParameter() { var empty = Assert.Throws(() => new RowMap([new(nameof(Post.Title), "")])); - Assert.StartsWith("The property 'Title' is mapped to an empty column name. Use null to ignore it.", empty.Message); + Assert.StartsWith(RowMapMessages.EmptyColumn("Title"), empty.Message); Assert.Throws(() => new RowMap([new(null!, "x")])); } diff --git a/Tests/Open.Database.Extensions.Core.Tests/DbQueryTests.cs b/Tests/Open.Database.Extensions.Core.Tests/DbQueryTests.cs index 38f8d2ee..fb8627c8 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/DbQueryTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/DbQueryTests.cs @@ -188,7 +188,7 @@ public static void AdHoc_AnExpressionThatIsNotAVariableIsRefused() ArgumentException ex = Assert.Throws( () => Posts.Using(c).AddParam(n + 1)); Assert.Contains("n + 1", ex.Message); - Assert.Contains("AddParam(\"name\", value)", ex.Message); + Assert.Contains(ParameterNameMessages.AddParamWithName, ex.Message); } [Fact] @@ -400,7 +400,7 @@ public static async Task TwoArgumentsThatResolveToOneParameter_AreRefused() .Map() .ToListAsync(TestContext.Current.CancellationToken)); - Assert.Contains("Two parameters resolve to", ex.Message); + Assert.Contains(ParameterNameMessages.TwoParametersResolveTo, ex.Message); } [Fact] @@ -487,7 +487,7 @@ public static async Task TwoMembersOfOneName_Collide() .Map() .ToListAsync(TestContext.Current.CancellationToken)); - Assert.Contains("Two parameters resolve to", ex.Message); + Assert.Contains(ParameterNameMessages.TwoParametersResolveTo, ex.Message); } // ---- immutable ---- diff --git a/Tests/Open.Database.Extensions.Core.Tests/DerivedNameCostTests.cs b/Tests/Open.Database.Extensions.Core.Tests/DerivedNameCostTests.cs index 5652f701..265d53ea 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/DerivedNameCostTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/DerivedNameCostTests.cs @@ -561,8 +561,15 @@ public static void AmbiguousArgument_ThrowsOnEveryCall() { var ex = Assert.Throws(() => rig.Run(c => c.AddParam(companySerialNum))); Assert.Equal( - $"The argument 'companySerialNum' matches both '@company_serial_num' and '@companyserial_num' of '{rig.Procedure}'. Its candidate name 'companySerialNum' fits each of them ignoring case and underscores. " - + "The procedure declares: @company_serial_num, @companyserial_num. Name the parameter explicitly: AddParam(\"name\", value).", + ParameterNameMessages.Ambiguous( + ParameterNameMessages.TheArgument("companySerialNum"), + "@company_serial_num", + "@companyserial_num", + rig.Procedure, + "companySerialNum", + ParameterNameMessages.TierIgnoringCaseAndUnderscores, + "@company_serial_num, @companyserial_num", + ParameterNameMessages.NameParameterExplicitly), ex.Message); } } @@ -610,13 +617,13 @@ public static void Collision_MessagesArePinned() string tail = $" The procedure '{rig.Procedure}' declares: @region. {ParameterNameMessages.NameOneExplicitly}"; var twoArguments = Assert.Throws(() => rig.Run(c => c.AddParam(region).AddParam(Region))); - Assert.Equal("Two parameters resolve to '@region': the argument 'region' and the argument 'Region'." + tail, twoArguments.Message); + Assert.Equal(ParameterNameMessages.Collision("@region", ParameterNameMessages.WrittenAsArgument("region"), ParameterNameMessages.WrittenAsArgument("Region")) + tail, twoArguments.Message); var named = Assert.Throws(() => rig.Run(c => c.AddParam("@REGION", 1).AddParam(region))); - Assert.Equal("Two parameters resolve to '@REGION': the name '@REGION' you passed and the argument 'region'." + tail, named.Message); + Assert.Equal(ParameterNameMessages.Collision("@REGION", ParameterNameMessages.WrittenAsName("@REGION"), ParameterNameMessages.WrittenAsArgument("region")) + tail, named.Message); var member = Assert.Throws(() => rig.Run(c => c.AddParams(new Regional()).AddParams(new Regional()))); - Assert.Equal("Two parameters resolve to '@region': the member 'Region' of the AddParams object and the member 'Region' of the AddParams object." + tail, member.Message); + Assert.Equal(ParameterNameMessages.Collision("@region", ParameterNameMessages.WrittenAsMember("Region"), ParameterNameMessages.WrittenAsMember("Region")) + tail, member.Message); } // The message of an argument that matches nothing. @@ -627,7 +634,14 @@ public static void NoMatch_MessageIsPinned() const int orderId = 1; var ex = Assert.Throws(() => rig.Run(c => c.AddParam(orderId))); - Assert.Equal($"The argument 'orderId' matches none of the parameters of '{rig.Procedure}' (tried orderId). The procedure declares: @a, @b. Name the parameter explicitly: AddParam(\"name\", value).", ex.Message); + Assert.Equal( + ParameterNameMessages.NoMatch( + "orderId", + rig.Procedure, + "orderId", + ParameterNameMessages.ProcedureDeclares, + "@a, @b"), + ex.Message); } sealed class Keyword @@ -662,7 +676,11 @@ public static void TextCommandWithoutMarkers_CollisionMessageSaysTheNamesAreNotK var ex = Assert.Throws( () => new ExpressiveDbCommand(connection, CommandType.Text, "select 1").AddParam(region).AddParam(Region).ExecuteNonQuery()); Assert.Equal( - "Two parameters resolve to 'region': the argument 'region' and the argument 'Region'. " + ParameterNameMessages.Collision( + "region", + ParameterNameMessages.WrittenAsArgument("region"), + ParameterNameMessages.WrittenAsArgument("Region")) + + " " + ParameterNameMessages.NotKnown + " " + ParameterNameMessages.NameOneExplicitly, ex.Message); diff --git a/Tests/Open.Database.Extensions.Core.Tests/DerivedNamesEveryRunTests.cs b/Tests/Open.Database.Extensions.Core.Tests/DerivedNamesEveryRunTests.cs index 06d80f69..5815c321 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/DerivedNamesEveryRunTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/DerivedNamesEveryRunTests.cs @@ -536,7 +536,7 @@ public static void ACollision_Throws_ThenTheNextRunIsFine() rig.Use("a"); var ex = Assert.Throws( () => command.ExecuteNonQuery()); - Assert.Contains("Two parameters resolve to", ex.Message); + Assert.Contains(ParameterNameMessages.TwoParametersResolveTo, ex.Message); // Nothing is left behind: Params is still the caller's, as added. Assert.Same(command.Callers, command.Params); diff --git a/Tests/Open.Database.Extensions.Core.Tests/DerivedParameterNameTests.cs b/Tests/Open.Database.Extensions.Core.Tests/DerivedParameterNameTests.cs index 8a4a0631..ecddce18 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/DerivedParameterNameTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/DerivedParameterNameTests.cs @@ -360,7 +360,7 @@ public static void NoMatch_Throws_NamingTheProcedureWhatWasTriedAndWhatItExpects Assert.Contains("dbo.search", ex.Message); Assert.Contains("orderCustomerId, CustomerId, Id", ex.Message); Assert.Contains("@a, @b", ex.Message); - Assert.Contains("AddParam(\"name\", value)", ex.Message); + Assert.Contains(ParameterNameMessages.AddParamWithName, ex.Message); Assert.Empty(probe.Parameters); // nothing was sent } @@ -386,7 +386,7 @@ public static void TwoArgumentsResolvingToOneParameter_Throws() proc.AddParam(filter.Region).AddParam(other.Region); var ex = Assert.Throws(() => proc.ExecuteNonQuery()); - Assert.Contains("Two parameters resolve to '@region'", ex.Message); + Assert.Contains($"{ParameterNameMessages.TwoParametersResolveTo} '@region'", ex.Message); } [Fact] @@ -526,7 +526,7 @@ void Throws(Action add, string expression) var ex = Assert.Throws(add); Assert.Equal("value", ex.ParamName); Assert.Contains(expression, ex.Message); - Assert.Contains("AddParam(\"name\", value)", ex.Message); + Assert.Contains(ParameterNameMessages.AddParamWithName, ex.Message); } Throws(() => cmd.AddParam(filter.EndDate?.AddDays(1)), "filter.EndDate?.AddDays(1)"); // a call @@ -562,13 +562,13 @@ public static void ExpressionNull_SaysTheCompilerDidNotSupplyTheText_AndShowsThe var ex = Assert.Throws(call); Assert.Equal("value", ex.ParamName); Assert.Contains("C# 10", ex.Message); - Assert.Contains("AddParam(\"name\", value)", ex.Message); + Assert.Contains(ParameterNameMessages.AddParamWithName, ex.Message); Assert.DoesNotContain("Cannot derive", ex.Message); } // Text that is present but not derivable keeps its own message. var other = Assert.Throws(() => cmd.AddParam(value: 1, expression: "")); - Assert.Contains("Cannot derive a parameter name from the argument ''", other.Message); + Assert.Contains(ParameterNameMessages.CannotDerive(""), other.Message); Assert.DoesNotContain("C# 10", other.Message); Assert.Empty(cmd.Params); } @@ -890,7 +890,7 @@ public static void AddParams_TwoMembersThatResolveToOneParameter_Throws() proc.AddParams(new TwoSpellings()); var ex = Assert.Throws(() => proc.ExecuteNonQuery()); - Assert.Contains("Two parameters resolve to '@foo_bar'", ex.Message); + Assert.Contains($"{ParameterNameMessages.TwoParametersResolveTo} '@foo_bar'", ex.Message); } sealed class TwoSpellings diff --git a/Tests/Open.Database.Extensions.Core.Tests/MappingCharacterizationTests.cs b/Tests/Open.Database.Extensions.Core.Tests/MappingCharacterizationTests.cs index 9cebaac1..e19cf0c7 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/MappingCharacterizationTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/MappingCharacterizationTests.cs @@ -220,7 +220,7 @@ public static void ANullPropertyName_AndAnEmptyColumnName_Throw() Assert.StartsWith(RowMapMessages.NoPropertyName, noName.Message); var empty = Assert.Throws(() => new RowMap([new(nameof(Post.Title), "")])); - Assert.StartsWith("The property 'Title' is mapped to an empty column name. Use null to ignore it.", empty.Message); + Assert.StartsWith(RowMapMessages.EmptyColumn("Title"), empty.Message); } [Fact] diff --git a/Tests/Open.Database.Extensions.Core.Tests/OutputParameterTests.cs b/Tests/Open.Database.Extensions.Core.Tests/OutputParameterTests.cs index 1e6abe50..62391fa9 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/OutputParameterTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/OutputParameterTests.cs @@ -351,7 +351,7 @@ public static async Task AnOutputThatNeverArrived_Throws_NeverReadsAsNull() var ex = await Assert.ThrowsAsync(async () => await c.StoredProcedure("dbo.AddPost").ExecuteOutputAsync(Token)); Assert.Contains("NewPost.Id has no value after dbo.AddPost ran: the output parameter 'Id' was not delivered", ex.Message); - Assert.Contains("Read the results to the end without stopping early, check the procedure for an error raised after its result sets, and treat the call as possibly committed.", ex.Message); + Assert.Contains(OutputRun.ReadToTheEnd, ex.Message); ex = await Assert.ThrowsAsync(async () => await c.StoredProcedure("dbo.AddPost").ExecuteOutputAsync("Id", Token)); Assert.Contains("The output parameter 'Id' has no value after dbo.AddPost ran", ex.Message); diff --git a/Tests/Open.Database.Extensions.Core.Tests/ParameterNameAddParamsTests.cs b/Tests/Open.Database.Extensions.Core.Tests/ParameterNameAddParamsTests.cs index ebfcf7f8..345fe5be 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/ParameterNameAddParamsTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/ParameterNameAddParamsTests.cs @@ -214,10 +214,10 @@ public static void EveryPublicGetter_IsReadWhenAddParamsIsCalled_EvenOneTheProce public static void TwoObjectsWithTheSameMember_Collide_AndTheMessageSaysSo() { var named = Assert.Throws(() => new SyncNameRun("@id").Run(c => c.AddParams(new { Id = 1 }).AddParams(new { Id = 2 }))); - Assert.StartsWith("Two parameters resolve to '@id': the member 'Id' of the AddParams object and the member 'Id' of the AddParams object.", named.Message); + Assert.StartsWith(ParameterNameMessages.Collision("@id", ParameterNameMessages.WrittenAsMember("Id"), ParameterNameMessages.WrittenAsMember("Id")), named.Message); var written = Assert.Throws(() => TextCommand().Run(c => c.AddParams(new { Id = 1 }).AddParams(new { Id = 2 }))); - Assert.StartsWith("Two parameters resolve to 'Id': the member 'Id' of the AddParams object and the member 'Id' of the AddParams object.", written.Message); + Assert.StartsWith(ParameterNameMessages.Collision("Id", ParameterNameMessages.WrittenAsMember("Id"), ParameterNameMessages.WrittenAsMember("Id")), written.Message); } // ---- what a caller can see of the names that were sent ---- @@ -380,9 +380,15 @@ public static void Match_AnAmbiguity_QuotesWhatWasWritten_TheCandidate_TheTierAn var ex = Assert.Throws(() => Match(["orderCustomerId", "CustomerId"], ["@customer_id", "@customer__id"], "order.Customer.Id", "dbo.p")); Assert.Equal( - "The argument 'order.Customer.Id' matches both '@customer_id' and '@customer__id' of 'dbo.p'. " - + "Its candidate name 'CustomerId' fits each of them ignoring case and underscores. " - + "The procedure declares: @customer_id, @customer__id. Name the parameter explicitly: AddParam(\"name\", value).", + ParameterNameMessages.Ambiguous( + ParameterNameMessages.TheArgument("order.Customer.Id"), + "@customer_id", + "@customer__id", + "dbo.p", + "CustomerId", + ParameterNameMessages.TierIgnoringCaseAndUnderscores, + "@customer_id, @customer__id", + ParameterNameMessages.NameParameterExplicitly), ex.Message); } } diff --git a/Tests/Open.Database.Extensions.Core.Tests/ParameterNameEndToEndTests.cs b/Tests/Open.Database.Extensions.Core.Tests/ParameterNameEndToEndTests.cs index 78ac0498..e21a7f68 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/ParameterNameEndToEndTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/ParameterNameEndToEndTests.cs @@ -414,10 +414,10 @@ sealed class Nothing public static void AddParams_TwoMembersThatResolveToOneParameter_Throw() { var ex = Assert.Throws(() => new SyncNameRun("@author").Run(c => c.AddParams(new Collide()))); - Assert.Contains("Two parameters resolve to '@author'", ex.Message); + Assert.Contains($"{ParameterNameMessages.TwoParametersResolveTo} '@author'", ex.Message); ex = Assert.Throws(() => new SyncNameRun("@author").Run(c => c.AddParams(new CollideUnderscore()))); - Assert.Contains("Two parameters resolve to '@author'", ex.Message); + Assert.Contains($"{ParameterNameMessages.TwoParametersResolveTo} '@author'", ex.Message); } [Fact] @@ -425,7 +425,7 @@ public static async Task AddParams_TwoMembersThatResolveToOneParameter_Throw_Asy { var ex = await Assert.ThrowsAsync(() => new AsyncNameRun("@author").RunAsync(c => c.AddParams(new Collide()))); - Assert.Contains("Two parameters resolve to '@author'", ex.Message); + Assert.Contains($"{ParameterNameMessages.TwoParametersResolveTo} '@author'", ex.Message); } [Fact] diff --git a/Tests/Open.Database.Extensions.Core.Tests/ParameterNameExplicitTests.cs b/Tests/Open.Database.Extensions.Core.Tests/ParameterNameExplicitTests.cs index 93094996..2e3a16f2 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/ParameterNameExplicitTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/ParameterNameExplicitTests.cs @@ -167,11 +167,11 @@ public static void ExplicitAndDerivedResolvingToTheSameParameter_Throw_InEitherO var run = new SyncNameRun(real); var first = Assert.Throws(() => run.Run(c => c.AddParam(explicitName, 1).AddParam(value: 2, expression: expression))); - Assert.Contains("Two parameters resolve to", first.Message); - Assert.Contains("Name one of them explicitly", first.Message); + Assert.Contains(ParameterNameMessages.TwoParametersResolveTo, first.Message); + Assert.Contains(ParameterNameMessages.NameOneExplicitly, first.Message); var second = Assert.Throws(() => run.Run(c => c.AddParam(value: 2, expression: expression).AddParam(explicitName, 1))); - Assert.Contains("Two parameters resolve to", second.Message); + Assert.Contains(ParameterNameMessages.TwoParametersResolveTo, second.Message); Assert.Empty(run.Probe.Parameters); } @@ -182,10 +182,10 @@ public static async Task ExplicitAndDerivedResolvingToTheSameParameter_Throw_InE var run = new AsyncNameRun(real); var first = await Assert.ThrowsAsync(() => run.RunAsync(c => c.AddParam(explicitName, 1).AddParam(value: 2, expression: expression))); - Assert.Contains("Two parameters resolve to", first.Message); + Assert.Contains(ParameterNameMessages.TwoParametersResolveTo, first.Message); var second = await Assert.ThrowsAsync(() => run.RunAsync(c => c.AddParam(value: 2, expression: expression).AddParam(explicitName, 1))); - Assert.Contains("Two parameters resolve to", second.Message); + Assert.Contains(ParameterNameMessages.TwoParametersResolveTo, second.Message); } [Fact] diff --git a/Tests/Open.Database.Extensions.Core.Tests/ParameterNameMatrixTests.cs b/Tests/Open.Database.Extensions.Core.Tests/ParameterNameMatrixTests.cs index a6c3caf4..326251eb 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/ParameterNameMatrixTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/ParameterNameMatrixTests.cs @@ -222,7 +222,7 @@ public static void Ambiguous_Throws_NamingBothParameters(string expression, stri Assert.Contains("matches both", ex.Message); Assert.Contains($"'{first}'", ex.Message); Assert.Contains($"'{second}'", ex.Message); - Assert.Contains("AddParam(\"name\", value)", ex.Message); + Assert.Contains(ParameterNameMessages.AddParamWithName, ex.Message); // The order the provider lists them in does not matter. var reversed = Assert.Throws(() => new SyncNameRun(second, first).Add(expression)); @@ -270,7 +270,7 @@ public static void TwoArgumentsResolvingToOneParameter_Throw(string first, strin var ex = Assert.Throws(() => run.Run(c => c.AddParam(value: 1, expression: first).AddParam(value: 2, expression: second))); - Assert.Contains($"Two parameters resolve to '{real}'", ex.Message); + Assert.Contains($"{ParameterNameMessages.TwoParametersResolveTo} '{real}'", ex.Message); Assert.Empty(run.Probe.Parameters); } @@ -282,7 +282,7 @@ public static async Task TwoArgumentsResolvingToOneParameter_Throw_Async(string var ex = await Assert.ThrowsAsync(() => run.RunAsync(c => c.AddParam(value: 1, expression: first).AddParam(value: 2, expression: second))); - Assert.Contains($"Two parameters resolve to '{real}'", ex.Message); + Assert.Contains($"{ParameterNameMessages.TwoParametersResolveTo} '{real}'", ex.Message); } // ---- optional parameters the call does not mention stay unsent ---- diff --git a/Tests/Open.Database.Extensions.Core.Tests/ParameterNameMessageTests.cs b/Tests/Open.Database.Extensions.Core.Tests/ParameterNameMessageTests.cs index 14fa6ab7..2deba880 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/ParameterNameMessageTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/ParameterNameMessageTests.cs @@ -21,10 +21,10 @@ public static void Ambiguity_SaysWhatYouWrote_TheCandidate_TheTier_AndWhatThePro // order.Customer.Id: the first candidate (orderCustomerId) matches nothing; the second (CustomerId) fits both parameters once underscores are ignored. var ex = Assert.Throws(() => new SyncNameRun("@customer_id", "@customer__id", "@name").Add("order.Customer.Id")); - Assert.StartsWith("The argument 'order.Customer.Id' matches both '@customer_id' and '@customer__id' of 'dbo.names", ex.Message); + Assert.StartsWith(ParameterNameMessages.TheArgument("order.Customer.Id") + " matches both '@customer_id' and '@customer__id' of 'dbo.names", ex.Message); Assert.Contains("Its candidate name 'CustomerId' fits each of them ignoring case and underscores.", ex.Message); Assert.Contains("The procedure declares: @customer_id, @customer__id, @name.", ex.Message); - Assert.Contains("Name the parameter explicitly: AddParam(\"name\", value).", ex.Message); + Assert.Contains(ParameterNameMessages.NameParameterExplicitly, ex.Message); } [Theory] @@ -45,7 +45,7 @@ public static async Task Ambiguity_SaysTheSame_OnTheAsyncPath() { var ex = await Assert.ThrowsAsync(() => new AsyncNameRun("@p_author", "@in_author").AddAsync("search.Author")); - Assert.StartsWith("The argument 'search.Author' matches both '@p_author' and '@in_author' of 'dbo.names", ex.Message); + Assert.StartsWith(ParameterNameMessages.TheArgument("search.Author") + " matches both '@p_author' and '@in_author' of 'dbo.names", ex.Message); Assert.Contains("Its candidate name 'Author' fits each of them", ex.Message); Assert.Contains("The procedure declares: @p_author, @in_author.", ex.Message); } @@ -59,7 +59,7 @@ public static void Collision_NamesBothArguments_AsTheyWereWritten_AndWhatTheProc .AddParam(value: 1, expression: "filter.Region") .AddParam(value: 2, expression: "other.Region"))); - Assert.StartsWith("Two parameters resolve to '@region': the argument 'filter.Region' and the argument 'other.Region'.", ex.Message); + Assert.StartsWith(ParameterNameMessages.Collision("@region", ParameterNameMessages.WrittenAsArgument("filter.Region"), ParameterNameMessages.WrittenAsArgument("other.Region")), ex.Message); Assert.Contains("The procedure 'dbo.names", ex.Message); Assert.Contains("declares: @region, @mode.", ex.Message); Assert.Contains(ParameterNameMessages.NameOneExplicitly, ex.Message); @@ -72,7 +72,7 @@ public static void Collision_OfANamedParameterAndAnArgument_SaysWhichWasWhich() .AddParam("@REGION", "x") .AddParam(value: 1, expression: "filter.Region"))); - Assert.StartsWith("Two parameters resolve to '@REGION': the name '@REGION' you passed and the argument 'filter.Region'.", ex.Message); // the name of the first of the two + Assert.StartsWith(ParameterNameMessages.Collision("@REGION", ParameterNameMessages.WrittenAsName("@REGION"), ParameterNameMessages.WrittenAsArgument("filter.Region")), ex.Message); // the name of the first of the two } [Fact] @@ -80,7 +80,7 @@ public static void Collision_OfTwoMembersOfAnObject_NamesTheMembers() { var ex = Assert.Throws(() => new SyncNameRun("@foo_bar").Run(c => c.AddParams(new FooBars()))); - Assert.StartsWith("Two parameters resolve to '@foo_bar': the member '", ex.Message); + Assert.StartsWith($"{ParameterNameMessages.TwoParametersResolveTo} '@foo_bar': the member '", ex.Message); Assert.Contains("the member 'FooBar' of the AddParams object", ex.Message); Assert.Contains("the member 'Foo_Bar' of the AddParams object", ex.Message); } @@ -95,7 +95,7 @@ public static void Collision_WithoutTheProceduresNames_SaysTheyAreNotKnown() .AddParam(value: 1, expression: "order.Id") .AddParam(value: 2, expression: "customer.Id"))); - Assert.StartsWith("Two parameters resolve to 'Id': the argument 'order.Id' and the argument 'customer.Id'.", ex.Message); + Assert.StartsWith(ParameterNameMessages.Collision("Id", ParameterNameMessages.WrittenAsArgument("order.Id"), ParameterNameMessages.WrittenAsArgument("customer.Id")), ex.Message); Assert.Contains(ParameterNameMessages.NotKnown, ex.Message); Assert.DoesNotContain("declares", ex.Message); Assert.Equal(0, run.Lookups); @@ -110,7 +110,7 @@ public static async Task Collision_SaysTheSame_OnTheAsyncPath() .AddParam(value: 1, expression: "filter.Region") .AddParam(value: 2, expression: "other.Region"))); - Assert.StartsWith("Two parameters resolve to '@region': the argument 'filter.Region' and the argument 'other.Region'.", ex.Message); + Assert.StartsWith(ParameterNameMessages.Collision("@region", ParameterNameMessages.WrittenAsArgument("filter.Region"), ParameterNameMessages.WrittenAsArgument("other.Region")), ex.Message); Assert.Contains("declares: @region.", ex.Message); } diff --git a/Tests/Open.Database.Extensions.Core.Tests/ParameterNamePrefixTests.cs b/Tests/Open.Database.Extensions.Core.Tests/ParameterNamePrefixTests.cs index ea45f1b8..298ff250 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/ParameterNamePrefixTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/ParameterNamePrefixTests.cs @@ -213,7 +213,7 @@ public static void AddParams_TwoMembersThatResolveToOneParameter_ThroughAPrefix_ // Author and m_author are both "author": one real @p_author is claimed twice. var ex = Assert.Throws(() => new SyncNameRun("@p_author").Run(c => c.AddParams(new PrefixCollide()))); - Assert.Contains("Two parameters resolve to '@p_author'", ex.Message); + Assert.Contains($"{ParameterNameMessages.TwoParametersResolveTo} '@p_author'", ex.Message); } sealed class Source @@ -502,7 +502,7 @@ public static void TwoArgumentsResolvingToOneParameter_ThroughAPrefix_Throw() string real = pair[2]; var ex = Assert.Throws(() => new SyncNameRun(real).Run(c => c.AddParam(value: 1, expression: pair[0]).AddParam(value: 2, expression: pair[1]))); - Assert.Contains($"Two parameters resolve to '{real}'", ex.Message); + Assert.Contains($"{ParameterNameMessages.TwoParametersResolveTo} '{real}'", ex.Message); } } @@ -513,11 +513,11 @@ public static void ExplicitAndDerivedResolvingToTheSameParameter_ThroughAPrefix_ // The explicit name is the real name, written out; the derived argument finds it through the prefix. var first = Assert.Throws(() => run.Run(c => c.AddParam("p_author", 1).AddParam(value: 2, expression: "author"))); - Assert.Contains("Two parameters resolve to", first.Message); + Assert.Contains(ParameterNameMessages.TwoParametersResolveTo, first.Message); Assert.Contains("p_author", first.Message); var second = Assert.Throws(() => run.Run(c => c.AddParam(value: 2, expression: "author").AddParam("@P_AUTHOR", 1))); - Assert.Contains("Two parameters resolve to", second.Message); + Assert.Contains(ParameterNameMessages.TwoParametersResolveTo, second.Message); Assert.Contains("p_author", second.Message); } diff --git a/Tests/Open.Database.Extensions.Core.Tests/SqlTextDerivedNamesTests.cs b/Tests/Open.Database.Extensions.Core.Tests/SqlTextDerivedNamesTests.cs index b8f72002..8a801611 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/SqlTextDerivedNamesTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/SqlTextDerivedNamesTests.cs @@ -96,7 +96,7 @@ public static async Task Ambiguity_Throws() { foreach (InvalidOperationException ex in await AllFail("select 1 where a = @customer_id and b = @customer__id", "order.Customer.Id")) { - Assert.StartsWith("The argument 'order.Customer.Id' matches both '@customer_id' and '@customer__id' of '", ex.Message); + Assert.StartsWith(ParameterNameMessages.TheArgument("order.Customer.Id") + " matches both '@customer_id' and '@customer__id' of '", ex.Message); Assert.Contains("Its candidate name 'CustomerId' fits each of them ignoring case and underscores.", ex.Message); } } @@ -123,7 +123,7 @@ public static async Task ANameOnlyInAStringOrAComment_IsNotDeclared() public static async Task TwoArgumentsThatFindTheSameToken_Collide() { foreach (InvalidOperationException ex in await AllFail("select 1 where a = @region_id", "filter.RegionId", "other.RegionId")) - Assert.StartsWith("Two parameters resolve to '@region_id': the argument 'filter.RegionId' and the argument 'other.RegionId'.", ex.Message); + Assert.StartsWith(ParameterNameMessages.Collision("@region_id", ParameterNameMessages.WrittenAsArgument("filter.RegionId"), ParameterNameMessages.WrittenAsArgument("other.RegionId")), ex.Message); } // ---- no token: nothing that works today changes ---- diff --git a/docsite/articles/mapping.md b/docsite/articles/mapping.md index 64cdbb6e..7d51d440 100644 --- a/docsite/articles/mapping.md +++ b/docsite/articles/mapping.md @@ -117,7 +117,7 @@ A type that cannot be mapped throws `InvalidOperationException` at the call, bef | An abstract class or a delegate | The same, with `it is an abstract class` or `it is a delegate` | | A dictionary (`Dictionary<,>`, `IDictionary<,>`, `IReadOnlyDictionary<,>`) or a dynamic object (`ExpandoObject`) | ``'Dictionary`2' cannot be mapped: it is a dictionary or a dynamic object, which has no properties to set from the columns. Map to a class or record, use AsDictionaryRows() for the values with their column names, or use Map(selector).`` | | A single value (`int`, `string`, ...) passed to a method that maps rows to a model (`RowMap`, `ToListAsync`, ...) | `'Int32' is a single value, not a row model. On a command use Map(), which reads the first column; else ExecuteScalar().` | -| No public constructor | `'Post' cannot be mapped: it has no public constructor.` | +| No public constructor | `'Post' cannot be mapped: it has no public constructor. Give it a public constructor, or use Map(selector).` | | Two or more public constructors, none without parameters | `'PostCard' cannot be mapped: it has 2 public constructors, PostCard(String title) and PostCard(String title, String body), and none without parameters. Make one of them non-public, or use Map(selector).` | | A `required` public field | `'Post' cannot be mapped: its required field 'Title' cannot be set. Make it a property.` | | A constructor parameter that is `ref`, `in`, `out` or a pointer | `'Post' cannot be mapped: its constructor parameter 'id' is passed by reference or is a pointer. Use Map(selector).` | From 65d74f4163f4baa9248582ba45c8b0e877b20345 Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Fri, 4 Dec 2026 10:16:41 -0800 Subject: [PATCH 7/9] Third review round of the message sweep: one collision method, no double guard, no DbConnectionProvider - ParameterNameMessages.Collision builds the whole collision text, joining spaces included; DbQueryBinding and ExpressiveCommandBase call it, and so do the pinned tests. - The CreateCommand overloads on a transaction (Core, MSSqlClient, SqlClient) no longer check commandText: the connection overload they call checks it the same way. - DbConnectionProvider is deleted: its last use went with ConnectionProvider. Its message is a private const of ExpressiveCommandBase, its only user. Two tests that existed only for the class are deleted. - The brace indent of RowMap.Declare is fixed. - The legacy-compiler CI step fails a target framework whose TRX file counts no tests. The public API is unchanged. Co-Authored-By: Claude Sonnet 5.5 --- .github/workflows/tests.yml | 9 +- Source/Core/Core/DbConnectionProvider.cs | 93 ------------------- Source/Core/Core/ParameterNameMessages.cs | 33 +++++++ Source/Core/Core/RowMap.cs | 6 +- Source/Core/DbQueryBinding.cs | 11 ++- Source/Core/ExpressiveCommandBase.cs | 26 ++++-- .../Extensions/Transaction.CreateCommand.cs | 2 - .../Extensions/Transaction.CreateCommand.cs | 1 - .../Extensions/Transaction.CreateCommand.cs | 2 - .../ConnectionSourceScopeTests.cs | 39 -------- .../DerivedNameCostTests.cs | 37 ++++++-- 11 files changed, 93 insertions(+), 166 deletions(-) delete mode 100644 Source/Core/Core/DbConnectionProvider.cs diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index db9057b4..ba2e79e6 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -120,11 +120,14 @@ jobs: foreach ($framework in $frameworks) { dotnet test $project -c Release --no-build -f $framework --logger "trx;LogFilePrefix=legacy-compiler-$framework" --results-directory TestResults/legacy-compiler $exitCode = $LASTEXITCODE - # `dotnet test --no-build -f` exits 0 without running anything for a target framework that was not built, so a missing TRX file is a failure too. + # `dotnet test --no-build -f` exits 0 without running anything for a target framework that was not built, so a missing TRX file is a failure too, + # and so is a TRX file that counts no tests. $results = @(Get-ChildItem TestResults/legacy-compiler -Filter "legacy-compiler-${framework}_*.trx" -ErrorAction SilentlyContinue | Where-Object LastWriteTime -ge $started) - if ($exitCode -ne 0 -or -not $results) { + $total = 0 + foreach ($result in $results) { $total += [int]([xml](Get-Content -Raw $result.FullName)).TestRun.ResultSummary.Counters.total } + if ($exitCode -ne 0 -or -not $results -or $total -eq 0) { $failed += $framework - Write-Host "::error::The LegacyCompiler tests failed on $framework (exit code $exitCode, $($results.Count) result file(s))." + Write-Host "::error::The LegacyCompiler tests failed on $framework (exit code $exitCode, $($results.Count) result file(s), $total test(s))." } } if ($failed) { throw "The LegacyCompiler tests failed on: $($failed -join ', ')." } diff --git a/Source/Core/Core/DbConnectionProvider.cs b/Source/Core/Core/DbConnectionProvider.cs deleted file mode 100644 index 3c2faa11..00000000 --- a/Source/Core/Core/DbConnectionProvider.cs +++ /dev/null @@ -1,93 +0,0 @@ -namespace Open.Database.Extensions.Core; - -/// -/// Hands out one connection and takes it back as it was found. -/// -/// -/// closes the connection when it needed -/// opening at the time of , so whoever opened it for the -/// caller closes it again. -/// The connection can be taken by one caller at a time. -/// -/// The type of the connection. -/// The connection to hand out. -internal class DbConnectionProvider(TConnection connection) - : IDbConnectionPool - where TConnection : class, IDbConnection -{ - private TConnection Connection { get; } = connection ?? throw new ArgumentNullException(nameof(connection)); - - private ConnectionState? _takenConnectionState; - - /// - /// - /// The connection was taken and not given back. - /// - public TConnection Take() - { - if (_takenConnectionState.HasValue) - { - throw new InvalidOperationException( - DbConnectionProvider.ConcurrentUseMessage); - } - - _takenConnectionState = Connection.State; - return Connection; - } - - IDbConnection IDbConnectionPool.Take() => Take(); - - /// - /// - /// is . - /// - /// - /// is not the connection this provider hands out. - /// - public void Give(IDbConnection connection) - { - if (connection is null) - throw new ArgumentNullException(nameof(connection)); - if (connection != Connection) - throw new ArgumentException("Does not belong to this provider.", nameof(connection)); - Contract.EndContractBlock(); - - // Not usable as it was found: whoever opened it for the caller closes it again. - if (_takenConnectionState is { } taken - && ConnectionExtensions.NeedsOpen(taken)) - { - connection.Close(); - } - - _takenConnectionState = null; - } -} - -/// -/// Creates instances. -/// -internal static class DbConnectionProvider -{ - /// - /// The message of the exception for a connection that is taken while it is - /// in use, whoever guards it (this provider, or a command's own guard). - /// - public const string ConcurrentUseMessage = - "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."; - - /// - /// Creates a provider that hands out . - /// - /// The type of the connection. - /// The connection to hand out. - /// A new . - /// - /// is . - /// - public static DbConnectionProvider Create(TConnection connection) - where TConnection : class, IDbConnection - => new(connection); -} diff --git a/Source/Core/Core/ParameterNameMessages.cs b/Source/Core/Core/ParameterNameMessages.cs index 7a99e7ab..68e06886 100644 --- a/Source/Core/Core/ParameterNameMessages.cs +++ b/Source/Core/Core/ParameterNameMessages.cs @@ -115,6 +115,39 @@ public static string Collision(string name) public static string Collision(string name, string first, string second) => $"{TwoParametersResolveTo} '{name}': {first} and {second}."; + /// + /// Two parameters resolve to one name: the whole message, with what the + /// owner declares or that the names are not known, and the fix. + /// + /// The name. + /// + /// What was written for the first parameter, or + /// when the message does not say. + /// + /// + /// What was written for the second parameter, or + /// when the message does not say. + /// + /// What declares the names, as the message starts. + /// + /// The names the owner declares; empty when they are not known. + /// + /// The message. + public static string Collision( + string name, + string? first, + string? second, + string owner, + ImmutableArray declared) + => (first is not null && second is not null + ? Collision(name, first, second) + : Collision(name)) + + " " + + (declared.IsDefaultOrEmpty + ? NotKnown + : $"{owner} declares: {string.Join(", ", declared)}.") + + " " + NameOneExplicitly; + /// What was written for a parameter: an argument. /// The text of the argument. /// The description. diff --git a/Source/Core/Core/RowMap.cs b/Source/Core/Core/RowMap.cs index be325b96..08958118 100644 --- a/Source/Core/Core/RowMap.cs +++ b/Source/Core/Core/RowMap.cs @@ -1026,9 +1026,9 @@ bool[] Declare(ReadOnlySpan> mappings, string?[] c foreach (KeyValuePair pair in mappings) { if (pair.Key is null) - { - throw new ArgumentException(RowMapMessages.NoPropertyName, paramName); - } + { + throw new ArgumentException(RowMapMessages.NoPropertyName, paramName); + } bool known = TryFindSlot(pair.Key, out int index); if (known) diff --git a/Source/Core/DbQueryBinding.cs b/Source/Core/DbQueryBinding.cs index 30149aeb..dfbbb923 100644 --- a/Source/Core/DbQueryBinding.cs +++ b/Source/Core/DbQueryBinding.cs @@ -294,11 +294,12 @@ static InvalidOperationException Collision( string name, DbQuery definition, NameSet? names) - => new(ParameterNameMessages.Collision(name) + " " - + (Known(names) - ? $"'{definition.CommandText}' declares: {string.Join(", ", names!.Names)}." - : ParameterNameMessages.NotKnown) - + " " + ParameterNameMessages.NameOneExplicitly); + => new(ParameterNameMessages.Collision( + name, + null, + null, + $"'{definition.CommandText}'", + Known(names) ? names!.Names : default)); // The one text of "matches none", for a command and for a query: the owner // is the command text or procedure name, declares the words before the names. diff --git a/Source/Core/ExpressiveCommandBase.cs b/Source/Core/ExpressiveCommandBase.cs index 6730160e..d87605ad 100644 --- a/Source/Core/ExpressiveCommandBase.cs +++ b/Source/Core/ExpressiveCommandBase.cs @@ -1219,14 +1219,11 @@ static string Written(Param original) InvalidOperationException Collision(string name, Param first, Param second, ImmutableArray real) => new(ParameterNameMessages.Collision( - name, - Written(first), - Written(second)) - + " " - + (real.IsDefaultOrEmpty - ? ParameterNameMessages.NotKnown - : $"The procedure '{Command}' declares: {string.Join(", ", real)}.") - + " " + ParameterNameMessages.NameOneExplicitly); + name, + Written(first), + Written(second), + $"The procedure '{Command}'", + real)); InvalidOperationException NoMatch(string expression, ImmutableArray real) => DbQueryBinding.NoMatch( @@ -1496,6 +1493,16 @@ TResult ExecuteDirect(TConnection single, TState state, Func + /// The message of the exception for a single connection that another run + /// holds. + /// + const string ConcurrentUseMessage + = "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."; + // The guard is what the run holds while it uses the connection, and disposing it lets the next run in; a connection that was closed when the run began is closed again by its own scope, before this lets go. /// /// Takes the guard of a single connection, which is for one run at a time. @@ -1506,8 +1513,7 @@ Busy EnterDirect() { if (Interlocked.CompareExchange(ref _busy, 1, 0) != 0) { - throw new InvalidOperationException( - DbConnectionProvider.ConcurrentUseMessage); + throw new InvalidOperationException(ConcurrentUseMessage); } return new Busy(this); diff --git a/Source/Core/Extensions/Transaction.CreateCommand.cs b/Source/Core/Extensions/Transaction.CreateCommand.cs index 95375dff..feca49f9 100644 --- a/Source/Core/Extensions/Transaction.CreateCommand.cs +++ b/Source/Core/Extensions/Transaction.CreateCommand.cs @@ -18,7 +18,6 @@ public static IDbCommand CreateCommand(this IDbTransaction transaction, CommandType type, string commandText, int secondsTimeout = CommandTimeout.DEFAULT_SECONDS) { if (transaction is null) throw new ArgumentNullException(nameof(transaction)); - ConnectionExtensions.CheckCommandText(commandText); if (transaction.Connection is null) throw new InvalidOperationException(TransactionMessages.NoConnection); Contract.EndContractBlock(); @@ -71,7 +70,6 @@ public static DbCommand CreateCommand(this DbTransaction transaction, CommandType type, string commandText, int secondsTimeout = CommandTimeout.DEFAULT_SECONDS) { if (transaction is null) throw new ArgumentNullException(nameof(transaction)); - ConnectionExtensions.CheckCommandText(commandText); if (transaction.Connection is null) throw new InvalidOperationException(TransactionMessages.NoConnection); Contract.EndContractBlock(); diff --git a/Source/MSSqlClient/Extensions/Transaction.CreateCommand.cs b/Source/MSSqlClient/Extensions/Transaction.CreateCommand.cs index a578bb0e..d907c328 100644 --- a/Source/MSSqlClient/Extensions/Transaction.CreateCommand.cs +++ b/Source/MSSqlClient/Extensions/Transaction.CreateCommand.cs @@ -15,7 +15,6 @@ public static SqlCommand CreateCommand(this SqlTransaction transaction, CommandType type, string commandText, int secondsTimeout = CommandTimeout.DEFAULT_SECONDS) { if (transaction is null) throw new ArgumentNullException(nameof(transaction)); - ConnectionExtensions.CheckCommandText(commandText); if (transaction.Connection is null) throw new InvalidOperationException(TransactionMessages.NoConnection); Contract.EndContractBlock(); diff --git a/Source/SqlClient/Extensions/Transaction.CreateCommand.cs b/Source/SqlClient/Extensions/Transaction.CreateCommand.cs index 94ada360..75eb759a 100644 --- a/Source/SqlClient/Extensions/Transaction.CreateCommand.cs +++ b/Source/SqlClient/Extensions/Transaction.CreateCommand.cs @@ -16,8 +16,6 @@ public static SqlCommand CreateCommand(this SqlTransaction transaction, CommandType type, string commandText, int secondsTimeout = CommandTimeout.DEFAULT_SECONDS) { if (transaction is null) throw new ArgumentNullException(nameof(transaction)); - if (commandText is null) throw new ArgumentNullException(nameof(commandText)); - if (string.IsNullOrWhiteSpace(commandText)) throw new ArgumentException(CommandTextMessages.Blank, nameof(commandText)); Contract.EndContractBlock(); SqlCommand command = transaction diff --git a/Tests/Open.Database.Extensions.Core.Tests/ConnectionSourceScopeTests.cs b/Tests/Open.Database.Extensions.Core.Tests/ConnectionSourceScopeTests.cs index 44025443..ff9f4200 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/ConnectionSourceScopeTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/ConnectionSourceScopeTests.cs @@ -271,45 +271,6 @@ public static void APool_LeavesAnOpenConnectionToThePool_AndSaysSo() Assert.Equal(["give"], connection.Log); } - [Fact] - public static async Task APoolThatRestoresTheState_ClosesWhatTheScopeOpened_AndLeavesTheRest() - { - // The pool a single connection makes (DbConnectionProvider): giving back closes it - // again if it was found closed, and leaves it open if it was found open. - var closed = new ConnectionScopeTests.ScopeConnection(); - var pool = Open.Database.Extensions.Core.DbConnectionProvider.Create(closed); - - using (pool.EnsureOpenScope()) - Assert.Equal(ConnectionState.Open, closed.State); - - Assert.Equal(ConnectionState.Closed, closed.State); - - var open = new ConnectionScopeTests.ScopeConnection(); - open.SetState(ConnectionState.Open); - pool = Open.Database.Extensions.Core.DbConnectionProvider.Create(open); - - await using (await pool.EnsureOpenScopeAsync(Ct)) { } - - Assert.Equal(ConnectionState.Open, open.State); - Assert.Equal(["open", "close"], closed.Log); - Assert.Empty(open.Log); - } - - [Fact] - public static void APoolOfOneConnection_TakenTwice_SaysWhatIsWrongAndTheFix() - { - var pool = Open.Database.Extensions.Core.DbConnectionProvider.Create( - new ConnectionScopeTests.ScopeConnection()); - _ = pool.Take(); - - InvalidOperationException ex - = Assert.Throws(pool.Take); - Assert.Equal( - Open.Database.Extensions.Core.DbConnectionProvider - .ConcurrentUseMessage, - ex.Message); - } - [Theory] [InlineData(false)] [InlineData(true)] diff --git a/Tests/Open.Database.Extensions.Core.Tests/DerivedNameCostTests.cs b/Tests/Open.Database.Extensions.Core.Tests/DerivedNameCostTests.cs index 265d53ea..cf46226d 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/DerivedNameCostTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/DerivedNameCostTests.cs @@ -614,16 +614,38 @@ public static void Collision_MessagesArePinned() { var rig = new ProcRig("@region"); const int region = 1, Region = 2; - string tail = $" The procedure '{rig.Procedure}' declares: @region. {ParameterNameMessages.NameOneExplicitly}"; + string owner = $"The procedure '{rig.Procedure}'"; + ImmutableArray declared = ["@region"]; var twoArguments = Assert.Throws(() => rig.Run(c => c.AddParam(region).AddParam(Region))); - Assert.Equal(ParameterNameMessages.Collision("@region", ParameterNameMessages.WrittenAsArgument("region"), ParameterNameMessages.WrittenAsArgument("Region")) + tail, twoArguments.Message); + Assert.Equal( + ParameterNameMessages.Collision( + "@region", + ParameterNameMessages.WrittenAsArgument("region"), + ParameterNameMessages.WrittenAsArgument("Region"), + owner, + declared), + twoArguments.Message); var named = Assert.Throws(() => rig.Run(c => c.AddParam("@REGION", 1).AddParam(region))); - Assert.Equal(ParameterNameMessages.Collision("@REGION", ParameterNameMessages.WrittenAsName("@REGION"), ParameterNameMessages.WrittenAsArgument("region")) + tail, named.Message); + Assert.Equal( + ParameterNameMessages.Collision( + "@REGION", + ParameterNameMessages.WrittenAsName("@REGION"), + ParameterNameMessages.WrittenAsArgument("region"), + owner, + declared), + named.Message); var member = Assert.Throws(() => rig.Run(c => c.AddParams(new Regional()).AddParams(new Regional()))); - Assert.Equal(ParameterNameMessages.Collision("@region", ParameterNameMessages.WrittenAsMember("Region"), ParameterNameMessages.WrittenAsMember("Region")) + tail, member.Message); + Assert.Equal( + ParameterNameMessages.Collision( + "@region", + ParameterNameMessages.WrittenAsMember("Region"), + ParameterNameMessages.WrittenAsMember("Region"), + owner, + declared), + member.Message); } // The message of an argument that matches nothing. @@ -679,10 +701,9 @@ public static void TextCommandWithoutMarkers_CollisionMessageSaysTheNamesAreNotK ParameterNameMessages.Collision( "region", ParameterNameMessages.WrittenAsArgument("region"), - ParameterNameMessages.WrittenAsArgument("Region")) - + " " - + ParameterNameMessages.NotKnown + " " - + ParameterNameMessages.NameOneExplicitly, + ParameterNameMessages.WrittenAsArgument("Region"), + "The command", + default), ex.Message); } From 25f2ce2e6b0aad88ff5b92d3f62e6fdca5131c5b Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Fri, 4 Dec 2026 10:18:33 -0800 Subject: [PATCH 8/9] Group the arguments of the message calls that the style scan flagged Calls to ParameterNameMessages.Ambiguous and ParameterNameMessages.Collision had one argument per line; the arguments that belong together now share a line. No text changes. Co-Authored-By: Claude Sonnet 5.5 --- Source/Core/ParameterNames.cs | 8 ++------ .../DerivedNameCostTests.cs | 18 ++++++------------ .../ParameterNameAddParamsTests.cs | 6 ++---- 3 files changed, 10 insertions(+), 22 deletions(-) diff --git a/Source/Core/ParameterNames.cs b/Source/Core/ParameterNames.cs index d08a493b..48c3b9d8 100644 --- a/Source/Core/ParameterNames.cs +++ b/Source/Core/ParameterNames.cs @@ -350,12 +350,8 @@ static bool ClosesAt(string s, int open, int close) throw new InvalidOperationException( ParameterNameMessages.Ambiguous( subject ?? ParameterNameMessages.TheArgument(expression), - found, - real, - procedure, - candidate, - TierText(tier), - string.Join(", ", parameterNames), + found, real, procedure, candidate, + TierText(tier), string.Join(", ", parameterNames), fix ?? (subject is null ? ParameterNameMessages.NameParameterExplicitly : ParameterNameMessages.NameWithColumn(subject)))); diff --git a/Tests/Open.Database.Extensions.Core.Tests/DerivedNameCostTests.cs b/Tests/Open.Database.Extensions.Core.Tests/DerivedNameCostTests.cs index cf46226d..30ea0f68 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/DerivedNameCostTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/DerivedNameCostTests.cs @@ -563,10 +563,8 @@ public static void AmbiguousArgument_ThrowsOnEveryCall() Assert.Equal( ParameterNameMessages.Ambiguous( ParameterNameMessages.TheArgument("companySerialNum"), - "@company_serial_num", - "@companyserial_num", - rig.Procedure, - "companySerialNum", + "@company_serial_num", "@companyserial_num", + rig.Procedure, "companySerialNum", ParameterNameMessages.TierIgnoringCaseAndUnderscores, "@company_serial_num, @companyserial_num", ParameterNameMessages.NameParameterExplicitly), @@ -623,8 +621,7 @@ public static void Collision_MessagesArePinned() "@region", ParameterNameMessages.WrittenAsArgument("region"), ParameterNameMessages.WrittenAsArgument("Region"), - owner, - declared), + owner, declared), twoArguments.Message); var named = Assert.Throws(() => rig.Run(c => c.AddParam("@REGION", 1).AddParam(region))); @@ -633,8 +630,7 @@ public static void Collision_MessagesArePinned() "@REGION", ParameterNameMessages.WrittenAsName("@REGION"), ParameterNameMessages.WrittenAsArgument("region"), - owner, - declared), + owner, declared), named.Message); var member = Assert.Throws(() => rig.Run(c => c.AddParams(new Regional()).AddParams(new Regional()))); @@ -643,8 +639,7 @@ public static void Collision_MessagesArePinned() "@region", ParameterNameMessages.WrittenAsMember("Region"), ParameterNameMessages.WrittenAsMember("Region"), - owner, - declared), + owner, declared), member.Message); } @@ -702,8 +697,7 @@ public static void TextCommandWithoutMarkers_CollisionMessageSaysTheNamesAreNotK "region", ParameterNameMessages.WrittenAsArgument("region"), ParameterNameMessages.WrittenAsArgument("Region"), - "The command", - default), + "The command", default), ex.Message); } diff --git a/Tests/Open.Database.Extensions.Core.Tests/ParameterNameAddParamsTests.cs b/Tests/Open.Database.Extensions.Core.Tests/ParameterNameAddParamsTests.cs index 345fe5be..7dcf18f0 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/ParameterNameAddParamsTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/ParameterNameAddParamsTests.cs @@ -382,10 +382,8 @@ public static void Match_AnAmbiguity_QuotesWhatWasWritten_TheCandidate_TheTierAn Assert.Equal( ParameterNameMessages.Ambiguous( ParameterNameMessages.TheArgument("order.Customer.Id"), - "@customer_id", - "@customer__id", - "dbo.p", - "CustomerId", + "@customer_id", "@customer__id", + "dbo.p", "CustomerId", ParameterNameMessages.TierIgnoringCaseAndUnderscores, "@customer_id, @customer__id", ParameterNameMessages.NameParameterExplicitly), From 4efbe0b2b07f8b691f131c4f58ebdff157796aa6 Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Fri, 4 Dec 2026 10:18:44 -0800 Subject: [PATCH 9/9] Group the arguments of the last no-match message call that the style scan flagged No text changes. Co-Authored-By: Claude Sonnet 5.5 --- .../DerivedNameCostTests.cs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/Tests/Open.Database.Extensions.Core.Tests/DerivedNameCostTests.cs b/Tests/Open.Database.Extensions.Core.Tests/DerivedNameCostTests.cs index 30ea0f68..0efe4eb3 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/DerivedNameCostTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/DerivedNameCostTests.cs @@ -653,9 +653,7 @@ public static void NoMatch_MessageIsPinned() var ex = Assert.Throws(() => rig.Run(c => c.AddParam(orderId))); Assert.Equal( ParameterNameMessages.NoMatch( - "orderId", - rig.Procedure, - "orderId", + "orderId", rig.Procedure, "orderId", ParameterNameMessages.ProcedureDeclares, "@a, @b"), ex.Message);