diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 2e70c6e0..ba2e79e6 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,35 @@ 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, + # 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) + $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), $total test(s))." + } + } + if ($failed) { throw "The LegacyCompiler tests failed on: $($failed -join ', ')." } - name: Upload the TRX files if: always() diff --git a/Source/Core/AnyCount.cs b/Source/Core/AnyCount.cs index 0ff0b454..c7fdc15b 100644 --- a/Source/Core/AnyCount.cs +++ b/Source/Core/AnyCount.cs @@ -17,17 +17,13 @@ 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) + => command.AsObjectArrays() .AnyAsync(cancellationToken); - } /// /// Asynchronously counts the rows the query returns, with no model to map them to. @@ -44,14 +40,11 @@ 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) + => command.AsObjectArrays() .CountAsync(cancellationToken); - } } diff --git a/Source/Core/Capture.cs b/Source/Core/Capture.cs index 163695a6..8eef33d5 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,48 @@ 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"; + + /// + /// 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, " @@ -1037,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 - ? "ToListAsync instead of ToList" - : "ExecuteNonQueryAsync instead of ExecuteNonQuery")}), " - + "or remove the capture."; + ? ToListInstead + : ExecuteNonQueryInstead)}), " + + OrRemoveTheCapture; public static string SecondRun(CaptureSet set) { @@ -1057,7 +1103,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. " @@ -1084,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."; @@ -1103,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: " @@ -1132,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/CaptureNames.cs b/Source/Core/CaptureNames.cs index 3873c975..138481ca 100644 --- a/Source/Core/CaptureNames.cs +++ b/Source/Core/CaptureNames.cs @@ -121,7 +121,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..3087377a --- /dev/null +++ b/Source/Core/Core/AnalyzerIds.cs @@ -0,0 +1,57 @@ +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"; +} diff --git a/Source/Core/Core/ArgumentMessages.cs b/Source/Core/Core/ArgumentMessages.cs new file mode 100644 index 00000000..b9212965 --- /dev/null +++ b/Source/Core/Core/ArgumentMessages.cs @@ -0,0 +1,13 @@ +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. Pass zero or more."; +} 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..efd78bbc 100644 --- a/Source/Core/Core/CommandTextMessages.cs +++ b/Source/Core/Core/CommandTextMessages.cs @@ -6,6 +6,7 @@ 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. " 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 6960c052..68e06886 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. " @@ -14,4 +15,213 @@ 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 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. + /// + 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: " + 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: " + AddParamWithName + "."; + + /// 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"; + + /// + /// 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 argument. + /// The message. + public static string CannotDerive(string 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}."; + + /// + /// 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. + 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/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..08958118 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,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("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) @@ -1034,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); @@ -2731,8 +2740,12 @@ 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 +2786,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.DictionaryOrDynamic(name); return Choose(type, name, out constructor, out setsRequiredMembers) ?? (setsRequiredMembers ? null : RequiredField(type, name)); } @@ -2820,10 +2833,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 +2859,19 @@ 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)."; + 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()) { 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 +2890,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..fb5d6d1d --- /dev/null +++ b/Source/Core/Core/RowMapMessages.cs @@ -0,0 +1,116 @@ +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. " + + "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. + /// + /// 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 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, " + + "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. " + + "Give it a public constructor, or use Map(selector)."; + + /// + /// 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."; +} diff --git a/Source/Core/Core/SuppressionJustifications.cs b/Source/Core/Core/SuppressionJustifications.cs new file mode 100644 index 00000000..32eb31a4 --- /dev/null +++ b/Source/Core/Core/SuppressionJustifications.cs @@ -0,0 +1,17 @@ +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."; +} diff --git a/Source/Core/Core/TransactionMessages.cs b/Source/Core/Core/TransactionMessages.cs new file mode 100644 index 00000000..cbf411f4 --- /dev/null +++ b/Source/Core/Core/TransactionMessages.cs @@ -0,0 +1,17 @@ +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."; +} diff --git a/Source/Core/DbQueryBinding.cs b/Source/Core/DbQueryBinding.cs index 7a1a34b6..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($"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)."); + => 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. @@ -307,5 +308,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 b749d75e..47264444 100644 --- a/Source/Core/DbQueryCall.cs +++ b/Source/Core/DbQueryCall.cs @@ -204,16 +204,16 @@ 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).", + ParameterNameMessages.CannotDerive(expression), "value")); /// diff --git a/Source/Core/ExpressiveCommandBase.cs b/Source/Core/ExpressiveCommandBase.cs index 8d99c587..d87605ad 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. /// @@ -624,11 +601,11 @@ 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($"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.NotSupplied, "value") + : new(ParameterNameMessages.CannotDerive(expression), "value"); /// /// Conditionally adds a parameter to the params list. @@ -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 @@ -1235,19 +1212,22 @@ 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)}. " - + (real.IsDefaultOrEmpty - ? "The parameter names are not known, so each argument is used under its last member as written." - : $"The procedure '{Command}' declares: {string.Join(", ", real)}.") - + " Name one of them explicitly: AddParam(\"name\", value)."); + => new(ParameterNameMessages.Collision( + name, + Written(first), + Written(second), + $"The procedure '{Command}'", + real)); InvalidOperationException NoMatch(string expression, ImmutableArray real) => DbQueryBinding.NoMatch( - expression, Command, "The procedure declares", real); + expression, Command, ParameterNameMessages.ProcedureDeclares, real); #endregion @@ -1328,7 +1308,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) @@ -1513,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. @@ -1523,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/Connection.CreateCommand.cs b/Source/Core/Extensions/Connection.CreateCommand.cs index 2dfd61a0..6065ebc3 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.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 1def227f..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", "CA1068:CancellationToken parameters must come last", 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/Extensions/Transaction.CreateCommand.cs b/Source/Core/Extensions/Transaction.CreateCommand.cs index f61cd4e6..feca49f9 100644 --- a/Source/Core/Extensions/Transaction.CreateCommand.cs +++ b/Source/Core/Extensions/Transaction.CreateCommand.cs @@ -18,8 +18,7 @@ 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("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); @@ -71,8 +70,7 @@ 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("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..76932092 100644 --- a/Source/Core/MappedDbQuery.cs +++ b/Source/Core/MappedDbQuery.cs @@ -454,13 +454,14 @@ 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."; + 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(NotFromADefinition); + : throw new InvalidOperationException(_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..c23b71be 100644 --- a/Source/Core/OutputBinding.cs +++ b/Source/Core/OutputBinding.cs @@ -30,6 +30,16 @@ 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 +49,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 +277,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 +294,22 @@ 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\")]."); } @@ -345,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/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..8e7eaf12 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, @@ -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; @@ -952,6 +961,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..48c3b9d8 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) @@ -348,9 +348,13 @@ 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/PooledArray.cs b/Source/Core/PooledArray.cs index 5d6c7976..9b77d6e6 100644 --- a/Source/Core/PooledArray.cs +++ b/Source/Core/PooledArray.cs @@ -401,7 +401,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..75f9b8e3 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/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/Source/Core/ReaderAbandon.cs b/Source/Core/ReaderAbandon.cs index ff0545ea..57015e5d 100644 --- a/Source/Core/ReaderAbandon.cs +++ b/Source/Core/ReaderAbandon.cs @@ -23,7 +23,19 @@ 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()"; + + /// + /// 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; @@ -141,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/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..d907c328 100644 --- a/Source/MSSqlClient/Extensions/Transaction.CreateCommand.cs +++ b/Source/MSSqlClient/Extensions/Transaction.CreateCommand.cs @@ -15,8 +15,7 @@ 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("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..215233a3 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.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 d54612a0..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("Command is empty or whitespace.", 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/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 95e0839f..41550640 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/CancelOnEarlyStopStreamTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/CancelOnEarlyStopStreamTests.cs @@ -305,10 +305,15 @@ 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.Contains(view == "reader" ? "a data reader" : "a DataTable", thrown.Message, StringComparison.Ordinal); + Assert.StartsWith(global::Open.Database.Extensions.Core.ReaderAbandon.Option, 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("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/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/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/CaptureStreamTests.cs b/Tests/Open.Database.Extensions.Core.Tests/CaptureStreamTests.cs index 921a548a..4d9e995e 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/CaptureStreamTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/CaptureStreamTests.cs @@ -784,7 +784,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 903c3269..466a1591 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/CaptureTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/CaptureTests.cs @@ -186,8 +186,8 @@ public static void ASynchronousTerminal_Throws_AndArmsNothing() var ex = Assert.Throws( () => command.ExecuteNonQuery()); Contains(ex, - "captures only work with async terminals", - "ExecuteNonQueryAsync instead of ExecuteNonQuery"); + CaptureMessages.OnlyAsyncTerminals, + CaptureMessages.ExecuteNonQueryInstead); Assert.Equal(0, c.Executed); // Not armed: awaiting it would wait forever, so it throws. @@ -619,7 +619,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/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/ConstructorBindingTests.cs b/Tests/Open.Database.Extensions.Core.Tests/ConstructorBindingTests.cs index e1915162..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")])); } @@ -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/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 868e8af0..0efe4eb3 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/DerivedNameCostTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/DerivedNameCostTests.cs @@ -561,8 +561,13 @@ 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); } } @@ -607,16 +612,35 @@ 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 owner = $"The procedure '{rig.Procedure}'"; + ImmutableArray declared = ["@region"]; 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"), + owner, declared), + 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"), + owner, declared), + 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"), + owner, declared), + member.Message); } // The message of an argument that matches nothing. @@ -627,7 +651,12 @@ 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 @@ -647,7 +676,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); } } @@ -662,9 +691,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'. " - + "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.Collision( + "region", + ParameterNameMessages.WrittenAsArgument("region"), + ParameterNameMessages.WrittenAsArgument("Region"), + "The command", default), ex.Message); } 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/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 a26ecfc1..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] @@ -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 @@ -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/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..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 - = "AddParam after Map applies only to a query made from a DbQuery definition; for a command, call AddParam before Map."; + = 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/MappingCharacterizationTests.cs b/Tests/Open.Database.Extensions.Core.Tests/MappingCharacterizationTests.cs index cd72912d..e19cf0c7 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/MappingCharacterizationTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/MappingCharacterizationTests.cs @@ -217,10 +217,10 @@ 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); + Assert.StartsWith(RowMapMessages.EmptyColumn("Title"), empty.Message); } [Fact] @@ -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 9126f230..188a017c 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); @@ -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/ParameterNameAddParamsTests.cs b/Tests/Open.Database.Extensions.Core.Tests/ParameterNameAddParamsTests.cs index ebfcf7f8..7dcf18f0 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,13 @@ 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 a5396929..2deba880 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/ParameterNameMessageTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/ParameterNameMessageTests.cs @@ -21,17 +21,17 @@ 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] - [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)); @@ -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,10 +59,10 @@ 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("Name one of them explicitly: AddParam(\"name\", value).", ex.Message); + Assert.Contains(ParameterNameMessages.NameOneExplicitly, ex.Message); } [Fact] @@ -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,8 +95,8 @@ 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.Contains("The parameter names are not known, so each argument is used under its last member as written.", 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/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/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/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..741c590d 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 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; @@ -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")); @@ -280,22 +280,22 @@ 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] 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. 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).` | 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