using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Jellyfin.Database.Implementations;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
namespace Jellyfin.Server.Implementations.Tests.Item;
///
/// Records the reader commands EF Core sends, so a test can ask SQLite how it would run one.
///
internal sealed class QueryPlanRecorder : DbCommandInterceptor
{
///
/// Gets the recorded commands, oldest first.
///
public List Commands { get; } = [];
///
/// Returns the EXPLAIN QUERY PLAN detail lines for a recorded command.
///
/// A context on the database the command ran against.
/// The recorded command.
/// One entry per plan line.
public static string[] Explain(JellyfinDbContext context, RecordedCommand query)
{
using var command = context.Database.GetDbConnection().CreateCommand();
#pragma warning disable CA2100 // query.Sql is generated by EF Core; query values remain bound parameters.
command.CommandText = "EXPLAIN QUERY PLAN " + query.Sql;
#pragma warning restore CA2100
foreach (var value in query.Parameters)
{
var parameter = command.CreateParameter();
parameter.ParameterName = value.Name;
parameter.Value = value.Value;
command.Parameters.Add(parameter);
}
using var reader = command.ExecuteReader();
var plan = new List();
while (reader.Read())
{
plan.Add(reader.GetString(3));
}
return plan.ToArray();
}
///
public override InterceptionResult ReaderExecuting(DbCommand command, CommandEventData eventData, InterceptionResult result)
{
Record(command);
return result;
}
///
public override ValueTask> ReaderExecutingAsync(DbCommand command, CommandEventData eventData, InterceptionResult result, CancellationToken cancellationToken = default)
{
Record(command);
return ValueTask.FromResult(result);
}
private void Record(DbCommand command)
{
Commands.Add(new RecordedCommand(
command.CommandText,
command.Parameters.Cast().Select(p => (p.ParameterName, p.Value)).ToArray()));
}
}