Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 29 additions & 3 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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()
Expand Down
19 changes: 6 additions & 13 deletions Source/Core/AnyCount.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,17 +17,13 @@ public static partial class CoreExtensions
/// <param name="cancellationToken">Cancels the call, together with the cancellation token set on the command.</param>
/// <returns>A task that produces <see langword="true"/> if there is a row; otherwise, <see langword="false"/>.</returns>
/// <exception cref="ArgumentNullException"><paramref name="command"/> is <see langword="null"/>.</exception>
// 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<bool> 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);
}

/// <summary>
/// Asynchronously counts the rows the query returns, with no model to map them to.
Expand All @@ -44,14 +40,11 @@ public static ValueTask<bool> AnyAsync(
/// <returns>A task that produces the number of rows.</returns>
/// <exception cref="ArgumentNullException"><paramref name="command"/> is <see langword="null"/>.</exception>
/// <exception cref="OverflowException">There are more than <see cref="int.MaxValue"/> rows.</exception>
// 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<int> 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);
}
}
80 changes: 61 additions & 19 deletions Source/Core/Capture.cs
Original file line number Diff line number Diff line change
Expand Up @@ -305,15 +305,19 @@ protected override TValue Read(OutputRun call, int start)
/// <typeparam name="TValue">The type of the value.</typeparam>
sealed class ReturnCapture<TValue>()
: CaptureSource<TValue>(
$"CaptureReturn<{Shape.TypeName(typeof(TValue))}>",
Call(),
CaptureKind.Return)
{
public override ImmutableArray<OutputMember> 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<T>().
protected override TValue Read(OutputRun call, int start)
=> RowMap<TValue>.ConvertScalar(call.Value(start));
Expand Down Expand Up @@ -1010,6 +1014,48 @@ public static CaptureSource<TValue> Return<TValue>()
/// </summary>
static class CaptureMessages
{

/// <summary>
/// The async form of a query terminal, named in the message of a sync call.
/// </summary>
public const string ToListInstead
= "ToListAsync instead of ToList";

/// <summary>
/// The async form of a command terminal, named in the message of a sync call.
/// </summary>
public const string ExecuteNonQueryInstead
= "ExecuteNonQueryAsync instead of ExecuteNonQuery";

/// <summary>
/// Why a text command cannot give a return code, in the messages that
/// need a stored procedure.
/// </summary>
public const string NoReturnCodeInText
= "a text command has no return code, "
+ "and the provider would report 0. ";

/// <summary>The fix of a message that needs a stored procedure.</summary>
public const string CallByName
= "Call the procedure by name with StoredProcedure(…), ";

/// <summary>The last resort of a message about a capture.</summary>
public const string OrRemoveTheCapture
= "or remove the capture.";

/// <summary>
/// The last resort of a message about a capture that has no command to fill.
/// </summary>
public const string OrReadWithExecuteOutputAsync
= "or read the outputs with ExecuteOutputAsync.";

/// <summary>
/// The fact a sync call of a command with a capture runs into,
/// in the message of that call.
/// </summary>
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, "
Expand Down Expand Up @@ -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)
{
Expand All @@ -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. "
Expand All @@ -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.";

Expand All @@ -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: "
Expand All @@ -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 "
Expand Down
2 changes: 1 addition & 1 deletion Source/Core/CaptureNames.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion Source/Core/ChunkConfig.cs
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ internal sealed class ChunkConfig<T>(
// 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<T>.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<T>.DefaultDeferFromClearedBytes).")]
public const int DefaultDeferFromClearedBytes = 131_072;

/// <summary>Gets the pool the arrays come from and go back to.</summary>
Expand Down
2 changes: 1 addition & 1 deletion Source/Core/ChunkProducer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ public int Count
/// A task that completes when the producer has ended (and the target has
/// been finished).
/// </returns>
[SuppressMessage("Roslynator", "RCS1229:Use async/await when necessary")]
[SuppressMessage("Roslynator", AnalyzerIds.RCS1229)]
public Task Start()
{
if (caller.IsCancellationRequested)
Expand Down
57 changes: 57 additions & 0 deletions Source/Core/Core/AnalyzerIds.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
namespace Open.Database.Extensions;

/// <summary>
/// The analyzer rules that the code suppresses: one text for each rule,
/// used by every place that suppresses it.
/// </summary>
internal static class AnalyzerIds
{

/// <summary>
/// Roslynator: an exception type does not implement the standard constructors.
/// </summary>
public const string RCS1194
= "RCS1194:Implement exception constructors";

/// <summary>
/// Roslynator: a method with a name that ends in Async is not asynchronous.
/// </summary>
public const string RCS1047
= "RCS1047:Non-asynchronous method name should not end with 'Async'";

/// <summary>
/// Roslynator: a method returns a task without async and await.
/// </summary>
public const string RCS1229
= "RCS1229:Use async/await when necessary";

/// <summary>
/// Roslynator: a static member of a generic type does not use the type
/// parameter.
/// </summary>
public const string RCS1158
= "RCS1158:Static member in generic type should use a type parameter";

/// <summary>
/// Design: a parameter of the type CancellationToken is not the last.
/// </summary>
public const string CA1068
= "CA1068:CancellationToken parameters must come last";

/// <summary>Design: an exception type is not public.</summary>
public const string CA1064
= "CA1064:Exceptions should be public";

/// <summary>
/// Design: an exception type does not implement the standard constructors.
/// </summary>
public const string CA1032
= "CA1032:Implement standard exception constructors";

/// <summary>
/// Usage: an argument exception names a parameter that is not one of the
/// method.
/// </summary>
public const string CA2208
= "CA2208:Instantiate argument exceptions correctly";
}
13 changes: 13 additions & 0 deletions Source/Core/Core/ArgumentMessages.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
namespace Open.Database.Extensions;

/// <summary>
/// The messages of the checks on an argument's range: one text for each fact,
/// used by every place that makes the check.
/// </summary>
internal static class ArgumentMessages
{

/// <summary>A count or an index is below zero.</summary>
public const string NotNegative
= "Cannot be negative. Pass zero or more.";
}
4 changes: 2 additions & 2 deletions Source/Core/Core/CancellationTokens.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ internal static class CancellationTokens
/// <returns>
/// <see langword="default"/> 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.
/// </returns>
[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;
Expand Down Expand Up @@ -52,7 +52,7 @@ public static CancellationToken Combine(CancellationToken commandToken, Cancella
/// its result is the result of <paramref name="start"/>.
/// </returns>
[SuppressMessage(
"Design", "CA1068:CancellationToken parameters must come last")]
"Design", AnalyzerIds.CA1068)]
public static ValueTask<TResult> RunAsync<TState, TResult>(
CancellationToken commandToken,
CancellationToken callToken,
Expand Down
1 change: 1 addition & 0 deletions Source/Core/Core/CommandTextMessages.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ namespace Open.Database.Extensions;
/// </summary>
internal static class CommandTextMessages
{

/// <summary>A command's text is empty or white space.</summary>
public const string Blank
= "The command cannot be empty or white space. "
Expand Down
Loading