-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathQueryStoreHistoryControl.axaml.cs
More file actions
324 lines (284 loc) · 9.98 KB
/
Copy pathQueryStoreHistoryControl.axaml.cs
File metadata and controls
324 lines (284 loc) · 9.98 KB
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.VisualTree;
using PlanViewer.Core.Models;
using PlanViewer.Core.Services;
using ScottPlot;
namespace PlanViewer.App.Controls;
public partial class QueryStoreHistoryControl : UserControl
{
private readonly string _connectionString;
private readonly string _queryHash;
private readonly string _database;
private readonly string _queryText;
private readonly DateTime? _slicerStartUtc;
private readonly DateTime? _slicerEndUtc;
private readonly int _maxHoursBack;
private bool _useFullHistory;
private CancellationTokenSource? _fetchCts;
private List<QueryStoreHistoryRow> _historyData = new();
private readonly List<(ScottPlot.Plottables.Scatter Scatter, string Label, string PlanHash)> _scatters = new();
// Hover tooltip
private Popup? _tooltip;
private TextBlock? _tooltipText;
// Box selection state
private bool _isDragging;
private Point _dragStartPoint;
private ScottPlot.Plottables.Rectangle? _selectionRect;
private readonly HashSet<int> _selectedRowIndices = new();
// Highlight markers for selected dots
private readonly List<ScottPlot.Plottables.Scatter> _highlightMarkers = new();
// Color mapping: plan hash -> color
private readonly Dictionary<string, ScottPlot.Color> _planHashColorMap = new();
// Legend state
private bool _legendExpanded;
private bool _isLoadingPlan;
private string _dataSummaryText = "";
// Legend highlight: which plan hash is currently highlighted (null = none)
private string? _highlightedPlanHash;
private ScottPlot.Plottables.HorizontalLine? _avgLine;
// Active button highlight brush
private static readonly SolidColorBrush ActiveButtonBg = new(Avalonia.Media.Color.FromRgb(0x4F, 0xC3, 0xF7));
private static readonly SolidColorBrush ActiveButtonFg = new(Avalonia.Media.Color.FromRgb(0x11, 0x12, 0x17));
private static readonly SolidColorBrush InactiveButtonFg = new(Avalonia.Media.Color.FromRgb(0x9D, 0xA5, 0xB4));
// Validated colorblind-safe categorical ramp (dark surface), in fixed CVD
// order — shared with the Multi QS Overview database palette so the two
// Query Store views read as one system.
private static readonly ScottPlot.Color[] PlanColors =
{
ScottPlot.Color.FromHex("#3987E5"),
ScottPlot.Color.FromHex("#199E70"),
ScottPlot.Color.FromHex("#C98500"),
ScottPlot.Color.FromHex("#008300"),
ScottPlot.Color.FromHex("#9085E9"),
ScottPlot.Color.FromHex("#E66767"),
ScottPlot.Color.FromHex("#D55181"),
ScottPlot.Color.FromHex("#D95926"),
};
// Map grid orderBy tags to history metric tags
private static readonly Dictionary<string, string> OrderByToMetricTag = new()
{
["cpu"] = "TotalCpuMs",
["avg-cpu"] = "AvgCpuMs",
["duration"] = "TotalDurationMs",
["avg-duration"] = "AvgDurationMs",
["reads"] = "TotalLogicalReads",
["avg-reads"] = "AvgLogicalReads",
["writes"] = "TotalLogicalWrites",
["avg-writes"] = "AvgLogicalWrites",
["physical-reads"] = "TotalPhysicalReads",
["avg-physical-reads"] = "AvgPhysicalReads",
["memory"] = "TotalMemoryMb",
["avg-memory"] = "AvgMemoryMb",
["executions"] = "CountExecutions",
};
/// <summary>
/// Gets the query hash displayed by this control (used for tab labels).
/// </summary>
public string QueryHash => _queryHash;
/// <summary>
/// Gets the database name displayed by this control.
/// </summary>
public string Database => _database;
/// <summary>
/// Raised when the user requests to load a plan from the context menu.
/// </summary>
public event EventHandler<HistoryPlanLoadEventArgs>? PlanLoadRequested;
/// <summary>
/// Parameterless constructor required by Avalonia designer.
/// </summary>
public QueryStoreHistoryControl()
{
_connectionString = "";
_queryHash = "";
_database = "";
_queryText = "";
InitializeComponent();
}
public QueryStoreHistoryControl(string connectionString, string queryHash,
string queryText, string database,
string initialMetricTag = "AvgCpuMs",
DateTime? slicerStartUtc = null, DateTime? slicerEndUtc = null,
int slicerDaysBack = 30)
{
_connectionString = connectionString;
_queryHash = queryHash;
_database = database;
_queryText = queryText;
_slicerStartUtc = slicerStartUtc;
_slicerEndUtc = slicerEndUtc;
_maxHoursBack = slicerDaysBack * 24;
InitializeComponent();
Helpers.DataGridBehaviors.Attach(HistoryDataGrid);
QueryIdentifierText.Text = $"Query Store History: {queryHash} in [{database}]";
QueryTextBox.Text = queryText;
// Select initial metric in the combo box
var metricTag = initialMetricTag;
foreach (var entry in MetricSelector.Items)
{
if (entry is ComboBoxItem item && item.Tag?.ToString() == metricTag)
{
MetricSelector.SelectedItem = item;
break;
}
}
// Default to range period mode when slicer range is available
_useFullHistory = !(_slicerStartUtc.HasValue && _slicerEndUtc.HasValue);
UpdateRangeButtons();
// Build hover tooltip
_tooltipText = new TextBlock
{
Foreground = new SolidColorBrush(Avalonia.Media.Color.FromRgb(0xE0, 0xE0, 0xE0)),
FontSize = 13
};
_tooltip = new Popup
{
PlacementTarget = HistoryChart,
Placement = PlacementMode.Pointer,
IsHitTestVisible = false,
IsLightDismissEnabled = false,
Child = new Border
{
Background = new SolidColorBrush(Avalonia.Media.Color.FromRgb(0x33, 0x33, 0x33)),
BorderBrush = new SolidColorBrush(Avalonia.Media.Color.FromRgb(0x55, 0x55, 0x55)),
BorderThickness = new Thickness(1),
CornerRadius = new CornerRadius(3),
Padding = new Thickness(8, 4, 8, 4),
Child = _tooltipText
}
};
((Grid)Content!).Children.Add(_tooltip);
HistoryChart.PointerMoved += OnChartPointerMoved;
HistoryChart.PointerExited += (_, _) => { if (_tooltip != null) _tooltip.IsOpen = false; };
HistoryChart.PointerPressed += OnChartPointerPressed;
HistoryChart.PointerReleased += OnChartPointerReleased;
// Disable ScottPlot's built-in left-click-drag pan so our box selection works
HistoryChart.UserInputProcessor.LeftClickDragPan(enable: false);
BuildContextMenu();
AttachedToVisualTree += async (_, _) =>
{
if (_historyData.Count == 0)
await LoadHistoryAsync();
};
DetachedFromVisualTree += (_, _) => CancelFetch();
}
/// <summary>
/// Shows the Close button in the footer (used when hosted in a detached window).
/// </summary>
public void ShowCloseButton(bool visible = true)
{
FooterPanel.IsVisible = visible;
}
/// <summary>
/// Cancels any pending data fetch.
/// </summary>
public void CancelFetch()
{
_fetchCts?.Cancel();
_fetchCts?.Dispose();
_fetchCts = null;
}
private void Cancel_Click(object? sender, RoutedEventArgs e)
{
CancelFetch();
}
/// <summary>
/// Maps a grid orderBy tag (e.g. "cpu", "avg-duration") to the history metric tag.
/// </summary>
public static string MapOrderByToMetricTag(string orderBy)
{
return OrderByToMetricTag.TryGetValue(orderBy.ToLowerInvariant(), out var tag)
? tag
: "AvgCpuMs";
}
private static double GetMetricValue(QueryStoreHistoryRow row, string tag) => tag switch
{
"AvgCpuMs" => row.AvgCpuMs,
"AvgDurationMs" => row.AvgDurationMs,
"AvgLogicalReads" => row.AvgLogicalReads,
"AvgLogicalWrites" => row.AvgLogicalWrites,
"AvgPhysicalReads" => row.AvgPhysicalReads,
"AvgMemoryMb" => row.AvgMemoryMb,
"AvgRowcount" => row.AvgRowcount,
"TotalCpuMs" => row.TotalCpuMs,
"TotalDurationMs" => row.TotalDurationMs,
"TotalLogicalReads" => row.TotalLogicalReads,
"TotalLogicalWrites" => row.TotalLogicalWrites,
"TotalPhysicalReads" => row.TotalPhysicalReads,
"TotalMemoryMb" => row.TotalMemoryMb,
"CountExecutions" => row.CountExecutions,
_ => row.AvgCpuMs,
};
private void ApplyDarkTheme()
{
var fig = ScottPlot.Color.FromHex("#22252b");
var data = ScottPlot.Color.FromHex("#111217");
var text = ScottPlot.Color.FromHex("#E4E6EB");
var grid = ScottPlot.Colors.White.WithAlpha(40);
HistoryChart.Plot.FigureBackground.Color = fig;
HistoryChart.Plot.DataBackground.Color = data;
HistoryChart.Plot.Axes.Color(text);
HistoryChart.Plot.Grid.MajorLineColor = grid;
HistoryChart.Plot.Axes.Bottom.TickLabelStyle.ForeColor = text;
HistoryChart.Plot.Axes.Left.TickLabelStyle.ForeColor = text;
}
private void UpdateRangeButtons()
{
if (_useFullHistory)
{
FullHistoryButton.Background = ActiveButtonBg;
FullHistoryButton.Foreground = ActiveButtonFg;
RangePeriodButton.Background = Brushes.Transparent;
RangePeriodButton.Foreground = InactiveButtonFg;
}
else
{
RangePeriodButton.Background = ActiveButtonBg;
RangePeriodButton.Foreground = ActiveButtonFg;
FullHistoryButton.Background = Brushes.Transparent;
FullHistoryButton.Foreground = InactiveButtonFg;
}
}
private async void RangePeriod_Click(object? sender, RoutedEventArgs e)
{
if (!_useFullHistory) return;
_useFullHistory = false;
UpdateRangeButtons();
await LoadHistoryAsync();
}
private async void FullHistory_Click(object? sender, RoutedEventArgs e)
{
if (_useFullHistory) return;
_useFullHistory = true;
UpdateRangeButtons();
await LoadHistoryAsync();
}
private void MetricSelector_SelectionChanged(object? sender, SelectionChangedEventArgs e)
{
if (IsVisible && _historyData.Count > 0)
UpdateChart();
}
private async void CopyQuery_Click(object? sender, RoutedEventArgs e)
{
if (string.IsNullOrEmpty(_queryText)) return;
var clipboard = TopLevel.GetTopLevel(this)?.Clipboard;
if (clipboard != null)
await clipboard.SetTextAsync(_queryText);
}
private void Close_Click(object? sender, RoutedEventArgs e)
{
// When in a detached window, close it (this destroys the history view)
CancelFetch();
var window = TopLevel.GetTopLevel(this) as Window;
if (window != null && window is not PlanViewer.App.MainWindow)
window.Close();
}
}