47 lines
1.9 KiB
C#
47 lines
1.9 KiB
C#
using System.Data.Common;
|
|
using Microsoft.EntityFrameworkCore.Diagnostics;
|
|
|
|
namespace ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests;
|
|
|
|
/// <summary>
|
|
/// Records the text of every reader command a context executes, so a query-shape test can
|
|
/// assert what a repository method actually reads (e.g. that a delete never SELECTs a fat
|
|
/// JSON column).
|
|
/// </summary>
|
|
public sealed class SqlReaderCommandRecorder : DbCommandInterceptor
|
|
{
|
|
private readonly List<string> _commands = new();
|
|
|
|
/// <summary>The text of every reader command recorded since the last <see cref="Reset"/>.</summary>
|
|
public IReadOnlyList<string> Commands => _commands;
|
|
|
|
/// <summary>Clears all recorded commands.</summary>
|
|
public void Reset() => _commands.Clear();
|
|
|
|
/// <summary>
|
|
/// True when any recorded reader command is a SELECT that projects <paramref name="column"/>.
|
|
/// </summary>
|
|
/// <param name="column">Column name to look for.</param>
|
|
/// <returns>Whether a recorded SELECT read the column.</returns>
|
|
public bool AnySelectReads(string column) =>
|
|
_commands.Any(c => c.TrimStart().StartsWith("SELECT", StringComparison.OrdinalIgnoreCase)
|
|
&& c.Contains(column, StringComparison.Ordinal));
|
|
|
|
/// <inheritdoc />
|
|
public override InterceptionResult<DbDataReader> ReaderExecuting(
|
|
DbCommand command, CommandEventData eventData, InterceptionResult<DbDataReader> result)
|
|
{
|
|
_commands.Add(command.CommandText);
|
|
return base.ReaderExecuting(command, eventData, result);
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
public override ValueTask<InterceptionResult<DbDataReader>> ReaderExecutingAsync(
|
|
DbCommand command, CommandEventData eventData, InterceptionResult<DbDataReader> result,
|
|
CancellationToken cancellationToken = default)
|
|
{
|
|
_commands.Add(command.CommandText);
|
|
return base.ReaderExecutingAsync(command, eventData, result, cancellationToken);
|
|
}
|
|
}
|