blob: a356932a789e15e1c2699fd9b06b80b733742390 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
|
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;
/// <summary>
/// Records the reader commands EF Core sends, so a test can ask SQLite how it would run one.
/// </summary>
internal sealed class QueryPlanRecorder : DbCommandInterceptor
{
/// <summary>
/// Gets the recorded commands, oldest first.
/// </summary>
public List<RecordedCommand> Commands { get; } = [];
/// <summary>
/// Returns the <c>EXPLAIN QUERY PLAN</c> detail lines for a recorded command.
/// </summary>
/// <param name="context">A context on the database the command ran against.</param>
/// <param name="query">The recorded command.</param>
/// <returns>One entry per plan line.</returns>
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<string>();
while (reader.Read())
{
plan.Add(reader.GetString(3));
}
return plan.ToArray();
}
/// <inheritdoc />
public override InterceptionResult<DbDataReader> ReaderExecuting(DbCommand command, CommandEventData eventData, InterceptionResult<DbDataReader> result)
{
Record(command);
return result;
}
/// <inheritdoc />
public override ValueTask<InterceptionResult<DbDataReader>> ReaderExecutingAsync(DbCommand command, CommandEventData eventData, InterceptionResult<DbDataReader> result, CancellationToken cancellationToken = default)
{
Record(command);
return ValueTask.FromResult(result);
}
private void Record(DbCommand command)
{
Commands.Add(new RecordedCommand(
command.CommandText,
command.Parameters.Cast<DbParameter>().Select(p => (p.ParameterName, p.Value)).ToArray()));
}
}
|