-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathQueryStoreGridControl.axaml.cs
More file actions
1900 lines (1673 loc) · 79.4 KB
/
Copy pathQueryStoreGridControl.axaml.cs
File metadata and controls
1900 lines (1673 loc) · 79.4 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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Interactivity;
using Avalonia.Media;
using PlanViewer.Core.Interfaces;
using PlanViewer.Core.Models;
using PlanViewer.App.Dialogs;
using PlanViewer.App.Services;
using PlanViewer.Core.Services;
namespace PlanViewer.App.Controls;
public partial class QueryStoreGridControl : UserControl
{
private readonly ServerConnection _serverConnection;
private readonly ICredentialService _credentialService;
private string _connectionString;
private string _database;
private CancellationTokenSource? _fetchCts;
private ObservableCollection<QueryStoreRow> _rows = new();
private ObservableCollection<QueryStoreRow> _filteredRows = new();
private readonly Dictionary<string, ColumnFilterState> _activeFilters = new();
private Popup? _filterPopup;
private ColumnFilterPopup? _filterPopupContent;
private string? _sortedColumnTag;
private bool _sortAscending;
private DateTime? _slicerStartUtc;
private DateTime? _slicerEndUtc;
private int _slicerDaysBack = 30;
private string _lastFetchedOrderBy = "cpu";
private bool _initialOrderByLoaded;
private bool _suppressRangeChanged;
private string? _waitHighlightCategory;
private const int AutoSelectTopN = 1; // number of rows auto-selected after each fetch
private bool _waitStatsSupported; // false until version + capture mode confirmed
private bool _waitStatsEnabled = true;
private bool _waitPercentMode;
private QueryStoreGroupBy _groupByMode = QueryStoreGroupBy.QueryHash;
private List<QueryStoreRow> _groupedRootRows = new(); // top-level rows for grouped mode
public event EventHandler<List<QueryStorePlan>>? PlansSelected;
public event EventHandler<string>? DatabaseChanged;
public string Database => _database;
public QueryStoreGridControl(ServerConnection serverConnection, ICredentialService credentialService,
string initialDatabase, List<string> databases, bool supportsWaitStats = false)
{
_serverConnection = serverConnection;
_credentialService = credentialService;
_database = initialDatabase;
_connectionString = serverConnection.GetConnectionString(credentialService, initialDatabase);
_waitStatsSupported = supportsWaitStats;
_slicerDaysBack = AppSettingsService.Load().QueryStoreSlicerDays;
InitializeComponent();
ResultsGrid.ItemsSource = _filteredRows;
Helpers.DataGridBehaviors.Attach(ResultsGrid);
EnsureFilterPopup();
SetupColumnHeaders();
PopulateDatabaseBox(databases, initialDatabase);
TimeRangeSlicer.RangeChanged += OnTimeRangeChanged;
WaitStatsProfile.CategoryClicked += OnWaitCategoryClicked;
WaitStatsProfile.CategoryDoubleClicked += OnWaitCategoryDoubleClicked;
WaitStatsProfile.CollapsedChanged += OnWaitStatsCollapsedChanged;
if (!_waitStatsSupported)
{
// Hide wait stats panel and column when server doesn't support it
WaitStatsProfile.Collapse();
WaitStatsChevronButton.IsVisible = false;
WaitStatsSplitter.IsVisible = false;
SlicerRow.ColumnDefinitions[2].Width = new GridLength(0);
var waitProfileCol = ResultsGrid.Columns
.FirstOrDefault(c => c.SortMemberPath == "WaitGrandTotalSort");
if (waitProfileCol != null)
waitProfileCol.IsVisible = false;
}
// Auto-fetch with default settings on connect
Avalonia.Threading.Dispatcher.UIThread.Post(() =>
{
ReorderColumnsForGroupBy();
Fetch_Click(null, new RoutedEventArgs());
_initialOrderByLoaded = true;
}, Avalonia.Threading.DispatcherPriority.Loaded);
}
private void PopulateDatabaseBox(List<string> databases, string selectedDatabase)
{
QsDatabaseBox.ItemsSource = databases;
QsDatabaseBox.SelectedItem = selectedDatabase;
}
private async void QsDatabase_SelectionChanged(object? sender, SelectionChangedEventArgs e)
{
if (QsDatabaseBox.SelectedItem is not string db || db == _database) return;
_fetchCts?.Cancel();
// Check if Query Store is enabled on the new database
var newConnStr = _serverConnection.GetConnectionString(_credentialService, db);
StatusText.Text = "Checking Query Store...";
try
{
var (enabled, state) = await QueryStoreService.CheckEnabledAsync(newConnStr);
if (!enabled)
{
StatusText.Text = $"Query Store not enabled on {db} ({state ?? "unknown"})";
QsDatabaseBox.SelectedItem = _database; // revert
return;
}
}
catch (Exception ex)
{
StatusText.Text = ex.Message.Length > 60 ? ex.Message[..60] + "..." : ex.Message;
QsDatabaseBox.SelectedItem = _database; // revert
return;
}
_database = db;
_connectionString = newConnStr;
_rows.Clear();
_filteredRows.Clear();
LoadButton.IsEnabled = false;
StatusText.Text = "";
DatabaseChanged?.Invoke(this, db);
}
private async void Fetch_Click(object? sender, RoutedEventArgs e)
{
_fetchCts?.Cancel();
_fetchCts?.Dispose();
_fetchCts = new CancellationTokenSource();
var ct = _fetchCts.Token;
var orderBy = (OrderByBox.SelectedItem as ComboBoxItem)?.Tag?.ToString() ?? "cpu";
_lastFetchedOrderBy = orderBy;
FetchButton.IsEnabled = false;
LoadButton.IsEnabled = false;
StatusText.Text = "Loading time slicer...";
_rows.Clear();
_filteredRows.Clear();
try
{
// Load slicer data, preserving the current selection if one exists.
// Without this, LoadData defaults to last 24h and the user's range is lost.
await LoadTimeSlicerDataAsync(orderBy, ct, _slicerStartUtc, _slicerEndUtc);
}
catch (OperationCanceledException)
{
StatusText.Text = "Cancelled.";
}
catch (Exception ex)
{
StatusText.Text = ex.Message.Length > 80 ? ex.Message[..80] + "..." : ex.Message;
}
finally
{
FetchButton.IsEnabled = true;
}
}
private async System.Threading.Tasks.Task FetchPlansForRangeAsync()
{
_fetchCts?.Cancel();
_fetchCts?.Dispose();
_fetchCts = new CancellationTokenSource();
var ct = _fetchCts.Token;
var topN = (int)(TopNBox.Value ?? 25);
var orderBy = _lastFetchedOrderBy;
var filter = BuildSearchFilter();
FetchButton.IsEnabled = false;
LoadButton.IsEnabled = false;
StatusText.Text = "Fetching plans...";
GridLoadingOverlay.IsVisible = true;
GridLoadingText.Text = "Fetching plans...";
GridEmptyMessage.IsVisible = false;
_rows.Clear();
_filteredRows.Clear();
_groupedRootRows.Clear();
// Start global + ribbon wait stats early (they don't depend on plan results)
if (_waitStatsSupported && _waitStatsEnabled && _slicerStartUtc.HasValue && _slicerEndUtc.HasValue)
_ = FetchGlobalWaitStatsOnlyAsync(_slicerStartUtc.Value, _slicerEndUtc.Value, ct);
try
{
if (_groupByMode == QueryStoreGroupBy.None)
{
await FetchFlatPlansAsync(topN, orderBy, filter, ct);
}
else
{
await FetchGroupedPlansAsync(topN, orderBy, filter, ct);
}
}
catch (OperationCanceledException)
{
StatusText.Text = "Cancelled.";
}
catch (Exception ex)
{
StatusText.Text = ex.Message.Length > 80 ? ex.Message[..80] + "..." : ex.Message;
}
finally
{
GridLoadingOverlay.IsVisible = false;
FetchButton.IsEnabled = true;
}
}
private async System.Threading.Tasks.Task FetchFlatPlansAsync(
int topN, string orderBy, QueryStoreFilter? filter, CancellationToken ct)
{
var plans = await QueryStoreService.FetchTopPlansAsync(
_connectionString, topN, orderBy, filter: filter, ct: ct,
startUtc: _slicerStartUtc, endUtc: _slicerEndUtc);
GridLoadingOverlay.IsVisible = false;
if (plans.Count == 0)
{
StatusText.Text = "No Query Store data found for the selected range.";
return;
}
foreach (var plan in plans)
_rows.Add(new QueryStoreRow(plan));
ApplyFilters();
LoadButton.IsEnabled = true;
SelectToggleButton.Content = "Select All";
// Fetch per-plan wait stats after grid is populated (needs plan IDs)
if (_waitStatsSupported && _waitStatsEnabled && _slicerStartUtc.HasValue && _slicerEndUtc.HasValue)
_ = FetchPerPlanWaitStatsAsync(_slicerStartUtc.Value, _slicerEndUtc.Value, ct);
}
private async System.Threading.Tasks.Task FetchGroupedPlansAsync(
int topN, string orderBy, QueryStoreFilter? filter, CancellationToken ct)
{
QueryStoreGroupedResult grouped;
if (_groupByMode == QueryStoreGroupBy.QueryHash)
{
grouped = await QueryStoreService.FetchGroupedByQueryHashAsync(
_connectionString, topN, orderBy, filter, ct,
_slicerStartUtc, _slicerEndUtc);
}
else // Module
{
grouped = await QueryStoreService.FetchGroupedByModuleAsync(
_connectionString, topN, orderBy, filter, ct,
_slicerStartUtc, _slicerEndUtc);
}
GridLoadingOverlay.IsVisible = false;
GridEmptyMessage.IsVisible = false;
if (grouped.IntermediateRows.Count == 0)
{
if (_groupByMode == QueryStoreGroupBy.Module)
{
GridEmptyMessageText.Text = "No module found in the selected period";
GridEmptyMessage.IsVisible = true;
}
else
{
StatusText.Text = "No Query Store data found for the selected range.";
}
return;
}
var rootRows = BuildGroupedRows(grouped);
// Sort root rows by consolidated metric descending
var metricAccessor = GetMetricAccessor(orderBy);
rootRows = rootRows.OrderByDescending(r => metricAccessor(r)).ToList();
_groupedRootRows = rootRows;
// Flatten to _rows (all levels) and show only top-level in _filteredRows
foreach (var root in rootRows)
{
_rows.Add(root);
foreach (var mid in root.Children)
{
_rows.Add(mid);
foreach (var leaf in mid.Children)
_rows.Add(leaf);
}
}
// Show only root-level rows initially (collapsed)
_filteredRows.Clear();
foreach (var root in rootRows)
_filteredRows.Add(root);
LoadButton.IsEnabled = true;
SelectToggleButton.Content = "Select All";
UpdateStatusText();
UpdateBarRatios();
// Fetch per-plan wait stats for leaf rows, then consolidate upward
if (_waitStatsSupported && _waitStatsEnabled && _slicerStartUtc.HasValue && _slicerEndUtc.HasValue)
_ = FetchGroupedWaitStatsAsync(_slicerStartUtc.Value, _slicerEndUtc.Value, ct);
}
/// <summary>
/// Fetches per-plan wait stats for all real plan IDs found in the grouped hierarchy,
/// assigns them to leaf rows, then consolidates upward to intermediate and root rows.
/// </summary>
private async System.Threading.Tasks.Task FetchGroupedWaitStatsAsync(
DateTime startUtc, DateTime endUtc, CancellationToken ct)
{
try
{
// Collect all real plan IDs from rows that have a real PlanId
var allPlanIds = _rows
.Where(r => r.PlanId > 0)
.Select(r => r.PlanId)
.Distinct()
.ToList();
if (allPlanIds.Count == 0) return;
var planWaits = await QueryStoreService.FetchPlanWaitStatsAsync(
_connectionString, startUtc, endUtc, allPlanIds, ct);
if (ct.IsCancellationRequested) return;
// Build lookup: plan_id → list of WaitCategoryTotal
var byPlan = planWaits
.GroupBy(x => x.PlanId)
.ToDictionary(g => g.Key, g => g.Select(x => x.Wait).ToList());
// 1. Assign raw waits + profiles to rows with a real PlanId
foreach (var row in _rows)
{
if (row.PlanId > 0 && byPlan.TryGetValue(row.PlanId, out var waits))
{
row.RawWaitCategories = waits;
row.WaitProfile = QueryStoreService.BuildWaitProfile(waits);
}
}
// 2. Consolidate upward through the hierarchy
foreach (var root in _groupedRootRows)
ConsolidateWaitProfileUpward(root);
UpdateWaitBarMode();
}
catch (OperationCanceledException) { }
catch (Exception) { }
}
/// <summary>
/// Recursively consolidates wait profiles from children into their parent.
/// For each parent: merges all children's RawWaitCategories by summing WaitRatio
/// per category, then builds a new WaitProfile from the merged totals.
/// </summary>
private static void ConsolidateWaitProfileUpward(QueryStoreRow parent)
{
if (parent.Children.Count == 0) return;
// Recurse first so children are consolidated before we merge them
foreach (var child in parent.Children)
ConsolidateWaitProfileUpward(child);
// Merge all children's raw wait categories by summing WaitRatio per category
var merged = parent.Children
.SelectMany(c => c.RawWaitCategories)
.GroupBy(w => new { w.WaitCategory, w.WaitCategoryDesc })
.Select(g => new WaitCategoryTotal
{
WaitCategory = g.Key.WaitCategory,
WaitCategoryDesc = g.Key.WaitCategoryDesc,
WaitRatio = g.Sum(w => w.WaitRatio),
})
.ToList();
if (merged.Count > 0)
{
parent.RawWaitCategories = merged;
parent.WaitProfile = QueryStoreService.BuildWaitProfile(merged);
}
}
/// <summary>Maps an orderBy metric string to a Func that extracts the sort value from a QueryStoreRow.</summary>
private static Func<QueryStoreRow, double> GetMetricAccessor(string orderBy) => orderBy.ToLowerInvariant() switch
{
"cpu" => r => r.TotalCpuSort,
"avg-cpu" => r => r.AvgCpuSort,
"duration" => r => r.TotalDurSort,
"avg-duration" => r => r.AvgDurSort,
"reads" => r => r.TotalReadsSort,
"avg-reads" => r => r.AvgReadsSort,
"writes" => r => r.TotalWritesSort,
"avg-writes" => r => r.AvgWritesSort,
"physical-reads" => r => r.TotalPhysReadsSort,
"avg-physical-reads" => r => r.AvgPhysReadsSort,
"memory" => r => r.TotalMemSort,
"avg-memory" => r => r.AvgMemSort,
"executions" => r => r.ExecsSort,
_ => r => r.TotalCpuSort,
};
private List<QueryStoreRow> BuildGroupedRows(QueryStoreGroupedResult grouped)
{
var roots = new List<QueryStoreRow>();
var metricAccessor = GetMetricAccessor(_lastFetchedOrderBy);
if (_groupByMode == QueryStoreGroupBy.QueryHash)
{
// Level 0: QueryHash groups
var queryHashGroups = grouped.IntermediateRows
.GroupBy(r => r.QueryHash)
.ToList();
foreach (var qhGroup in queryHashGroups)
{
var qhKey = qhGroup.Key;
var intermediateRows = qhGroup.ToList();
// Build level-1 children (PlanHash)
var midChildren = new List<QueryStoreRow>();
foreach (var mid in intermediateRows)
{
// Build level-2 children (QueryId/PlanId)
var leafChildren = new List<QueryStoreRow>();
var leaves = grouped.LeafRows
.Where(l => l.QueryHash == mid.QueryHash && l.QueryPlanHash == mid.QueryPlanHash)
.ToList();
foreach (var leaf in leaves)
{
var leafPlan = GroupedRowToPlan(leaf);
leafChildren.Add(new QueryStoreRow(leafPlan, 2,
$"Q:{leaf.QueryId} P:{leaf.PlanId}{(leaf.IsTopRepresentative ? " ★" : "")}", new List<QueryStoreRow>()));
}
// Sort leaf children by metric descending
leafChildren = leafChildren.OrderByDescending(r => metricAccessor(r)).ToList();
var midPlan = GroupedRowToPlan(mid);
// Populate QueryText from the top representative leaf for this plan hash
var topLeafForMid = leaves.FirstOrDefault(l => l.IsTopRepresentative) ?? leaves.FirstOrDefault();
if (topLeafForMid != null && !string.IsNullOrEmpty(topLeafForMid.QueryText))
midPlan.QueryText = topLeafForMid.QueryText;
midChildren.Add(new QueryStoreRow(midPlan, 1, mid.QueryPlanHash, leafChildren));
}
// Sort mid children by metric descending
midChildren = midChildren.OrderByDescending(r => metricAccessor(r)).ToList();
// Aggregate metrics at QueryHash level
var aggPlan = AggregateGroupedRows(intermediateRows, qhKey, intermediateRows.FirstOrDefault()?.ModuleName ?? "");
// Populate QueryText from the top representative leaf across all leaves in this query hash group
var topLeafForRoot = grouped.LeafRows
.Where(l => l.QueryHash == qhKey && l.IsTopRepresentative && !string.IsNullOrEmpty(l.QueryText))
.FirstOrDefault()
?? grouped.LeafRows.FirstOrDefault(l => l.QueryHash == qhKey && !string.IsNullOrEmpty(l.QueryText));
if (topLeafForRoot != null)
aggPlan.QueryText = topLeafForRoot.QueryText;
roots.Add(new QueryStoreRow(aggPlan, 0, qhKey, midChildren));
}
}
else // Module
{
// Level 0: Module groups
var moduleGroups = grouped.IntermediateRows
.GroupBy(r => r.ModuleName)
.ToList();
foreach (var modGroup in moduleGroups)
{
var modKey = modGroup.Key;
var intermediateRows = modGroup.ToList();
// Build level-1 children (QueryHash)
var midChildren = new List<QueryStoreRow>();
foreach (var mid in intermediateRows)
{
// Build level-2 children (QueryId/PlanId)
var leafChildren = new List<QueryStoreRow>();
var leaves = grouped.LeafRows
.Where(l => l.ModuleName == mid.ModuleName && l.QueryHash == mid.QueryHash)
.ToList();
foreach (var leaf in leaves)
{
var leafPlan = GroupedRowToPlan(leaf);
leafChildren.Add(new QueryStoreRow(leafPlan, 2,
$"Q:{leaf.QueryId} P:{leaf.PlanId}{(leaf.IsTopRepresentative ? " ★" : "")}", new List<QueryStoreRow>()));
}
// Sort leaf children by metric descending
leafChildren = leafChildren.OrderByDescending(r => metricAccessor(r)).ToList();
var midPlan = GroupedRowToPlan(mid);
// Populate QueryText from the top representative leaf for this query hash
var topLeafForMid = leaves.FirstOrDefault(l => l.IsTopRepresentative) ?? leaves.FirstOrDefault();
if (topLeafForMid != null && !string.IsNullOrEmpty(topLeafForMid.QueryText))
midPlan.QueryText = topLeafForMid.QueryText;
midChildren.Add(new QueryStoreRow(midPlan, 1, mid.QueryHash, leafChildren));
}
// Sort mid children by metric descending
midChildren = midChildren.OrderByDescending(r => metricAccessor(r)).ToList();
// Aggregate metrics at Module level
var aggPlan = AggregateGroupedRows(intermediateRows, "", modKey);
// Populate QueryText from the top representative leaf across all leaves in this module group
var topLeafForRoot = grouped.LeafRows
.Where(l => l.ModuleName == modKey && l.IsTopRepresentative && !string.IsNullOrEmpty(l.QueryText))
.FirstOrDefault()
?? grouped.LeafRows.FirstOrDefault(l => l.ModuleName == modKey && !string.IsNullOrEmpty(l.QueryText));
if (topLeafForRoot != null)
aggPlan.QueryText = topLeafForRoot.QueryText;
roots.Add(new QueryStoreRow(aggPlan, 0, modKey, midChildren));
}
}
return roots;
}
private static QueryStorePlan GroupedRowToPlan(QueryStoreGroupedPlanRow row)
{
var totalExecs = row.CountExecutions > 0 ? row.CountExecutions : 1;
return new QueryStorePlan
{
QueryId = row.QueryId,
PlanId = row.PlanId,
QueryHash = row.QueryHash,
QueryPlanHash = row.QueryPlanHash,
ModuleName = row.ModuleName,
QueryText = row.QueryText,
PlanXml = row.PlanXml,
CountExecutions = row.CountExecutions,
TotalCpuTimeUs = row.TotalCpuTimeUs,
TotalDurationUs = row.TotalDurationUs,
TotalLogicalIoReads = row.TotalLogicalIoReads,
TotalLogicalIoWrites = row.TotalLogicalIoWrites,
TotalPhysicalIoReads = row.TotalPhysicalIoReads,
TotalMemoryGrantPages = row.TotalMemoryGrantPages,
AvgCpuTimeUs = (double)row.TotalCpuTimeUs / totalExecs,
AvgDurationUs = (double)row.TotalDurationUs / totalExecs,
AvgLogicalIoReads = (double)row.TotalLogicalIoReads / totalExecs,
AvgLogicalIoWrites = (double)row.TotalLogicalIoWrites / totalExecs,
AvgPhysicalIoReads = (double)row.TotalPhysicalIoReads / totalExecs,
AvgMemoryGrantPages = (double)row.TotalMemoryGrantPages / totalExecs,
LastExecutedUtc = row.LastExecutedUtc,
};
}
private static QueryStorePlan AggregateGroupedRows(List<QueryStoreGroupedPlanRow> rows, string queryHash, string moduleName)
{
var totalExecs = rows.Sum(r => r.CountExecutions);
var safeExecs = totalExecs > 0 ? totalExecs : 1;
var totalCpu = rows.Sum(r => r.TotalCpuTimeUs);
var totalDur = rows.Sum(r => r.TotalDurationUs);
var totalReads = rows.Sum(r => r.TotalLogicalIoReads);
var totalWrites = rows.Sum(r => r.TotalLogicalIoWrites);
var totalPhysReads = rows.Sum(r => r.TotalPhysicalIoReads);
var totalMem = rows.Sum(r => r.TotalMemoryGrantPages);
var lastExec = rows.Max(r => r.LastExecutedUtc);
return new QueryStorePlan
{
QueryHash = queryHash,
ModuleName = moduleName,
CountExecutions = totalExecs,
TotalCpuTimeUs = totalCpu,
TotalDurationUs = totalDur,
TotalLogicalIoReads = totalReads,
TotalLogicalIoWrites = totalWrites,
TotalPhysicalIoReads = totalPhysReads,
TotalMemoryGrantPages = totalMem,
AvgCpuTimeUs = (double)totalCpu / safeExecs,
AvgDurationUs = (double)totalDur / safeExecs,
AvgLogicalIoReads = (double)totalReads / safeExecs,
AvgLogicalIoWrites = (double)totalWrites / safeExecs,
AvgPhysicalIoReads = (double)totalPhysReads / safeExecs,
AvgMemoryGrantPages = (double)totalMem / safeExecs,
LastExecutedUtc = lastExec,
};
}
private QueryStoreFilter? BuildSearchFilter()
{
var searchType = (SearchTypeBox.SelectedItem as ComboBoxItem)?.Tag?.ToString();
var searchValue = SearchValueBox.Text?.Trim();
if (string.IsNullOrEmpty(searchType) || string.IsNullOrEmpty(searchValue))
return null;
var filter = new QueryStoreFilter();
switch (searchType)
{
case "query-id" when long.TryParse(searchValue, out var qid):
filter.QueryId = qid;
break;
case "query-id":
StatusText.Text = "Invalid Query ID";
return null;
case "plan-id" when long.TryParse(searchValue, out var pid):
filter.PlanId = pid;
break;
case "plan-id":
StatusText.Text = "Invalid Plan ID";
return null;
case "query-hash":
filter.QueryHash = searchValue;
break;
case "plan-hash":
filter.QueryPlanHash = searchValue;
break;
case "module":
// Default to dbo schema if no schema specified, following sp_QuickieStore pattern
filter.ModuleName = searchValue.Contains('.') ? searchValue : $"dbo.{searchValue}";
break;
default:
return null;
}
return filter;
}
private void SearchValue_KeyDown(object? sender, Avalonia.Input.KeyEventArgs e)
{
if (e.Key == Avalonia.Input.Key.Enter)
{
Fetch_Click(sender, e);
e.Handled = true;
}
}
private int[]? _savedColumnDisplayIndices;
private void GroupBy_SelectionChanged(object? sender, SelectionChangedEventArgs e)
{
if (!_initialOrderByLoaded) return;
var tag = (GroupByBox.SelectedItem as ComboBoxItem)?.Tag?.ToString() ?? "none";
var newMode = tag switch
{
"query-hash" => QueryStoreGroupBy.QueryHash,
"module" => QueryStoreGroupBy.Module,
_ => QueryStoreGroupBy.None,
};
if (newMode == _groupByMode) return;
_groupByMode = newMode;
// Show/hide the expand column (first column in the grid)
ResultsGrid.Columns[0].IsVisible = _groupByMode != QueryStoreGroupBy.None;
// Reorder columns: move the group key column right after expand+checkbox
ReorderColumnsForGroupBy();
// Re-fetch with new grouping
Fetch_Click(null, new RoutedEventArgs());
}
private void ReorderColumnsForGroupBy()
{
var cols = ResultsGrid.Columns;
if (_groupByMode == QueryStoreGroupBy.None)
{
// Restore original column order
if (_savedColumnDisplayIndices != null)
{
for (int i = 0; i < cols.Count && i < _savedColumnDisplayIndices.Length; i++)
cols[i].DisplayIndex = _savedColumnDisplayIndices[i];
_savedColumnDisplayIndices = null;
}
// Reset header colors
ApplyGroupByHeaderColors();
return;
}
// Save original order if not yet saved
_savedColumnDisplayIndices ??= cols.Select(c => c.DisplayIndex).ToArray();
// Column definition indices (AXAML order):
// 0=Expand, 1=Checkbox, 2=QueryId, 3=PlanId, 4=QueryHash, 5=PlanHash, 6=Module
if (_groupByMode == QueryStoreGroupBy.QueryHash)
{
// Order: Expand, Checkbox, QueryHash, PlanHash, QueryId, PlanId, ...
cols[4].DisplayIndex = 2; // QueryHash → 2
cols[5].DisplayIndex = 3; // PlanHash → 3
cols[2].DisplayIndex = 4; // QueryId → 4
cols[3].DisplayIndex = 5; // PlanId → 5
}
else // Module
{
// Order: Expand, Checkbox, Module, QueryHash, QueryId, PlanId, ...
cols[6].DisplayIndex = 2; // Module → 2
cols[4].DisplayIndex = 3; // QueryHash → 3
cols[2].DisplayIndex = 4; // QueryId → 4
cols[3].DisplayIndex = 5; // PlanId → 5
}
// Apply golden header colors for expandable columns
ApplyGroupByHeaderColors();
}
/// <summary>
/// Applies golden foreground to column headers that represent expandable/collapsible
/// grouping levels in the current GroupBy mode, and resets others.
/// </summary>
private void ApplyGroupByHeaderColors()
{
// Column definition indices: 4=QueryHash, 5=PlanHash, 6=Module
var goldenCols = _groupByMode switch
{
QueryStoreGroupBy.QueryHash => new HashSet<int> { 4, 5 }, // QueryHash + PlanHash
QueryStoreGroupBy.Module => new HashSet<int> { 6, 4 }, // Module + QueryHash
_ => new HashSet<int>(),
};
var goldenBrush = new SolidColorBrush(Color.FromRgb(0xFF, 0xD7, 0x00)); // Gold
for (int i = 0; i < ResultsGrid.Columns.Count; i++)
{
var col = ResultsGrid.Columns[i];
if (col.Header is not StackPanel sp) continue;
var label = sp.Children.OfType<TextBlock>().LastOrDefault();
if (label == null) continue;
if (goldenCols.Contains(i))
label.Foreground = goldenBrush;
else
label.ClearValue(TextBlock.ForegroundProperty);
}
}
private void ExpandRow_Click(object? sender, RoutedEventArgs e)
{
if (sender is not Button btn) return;
if (btn.DataContext is not QueryStoreRow row) return;
if (!row.HasChildren) return;
row.IsExpanded = !row.IsExpanded;
if (row.IsExpanded)
{
// Insert children after this row in _filteredRows
var idx = _filteredRows.IndexOf(row);
if (idx < 0) return;
var insertAt = idx + 1;
foreach (var child in row.Children)
{
_filteredRows.Insert(insertAt, child);
insertAt++;
}
// Scroll the first child into view so the expansion is visible
if (row.Children.Count > 0)
ResultsGrid.ScrollIntoView(row.Children[0], null);
}
else
{
// Remove children (and their expanded children) recursively
CollapseRowChildren(row);
}
UpdateStatusText();
UpdateBarRatios();
}
private void CollapseRowChildren(QueryStoreRow parent)
{
foreach (var child in parent.Children)
{
if (child.IsExpanded)
{
child.IsExpanded = false;
CollapseRowChildren(child);
}
_filteredRows.Remove(child);
}
}
private async void OrderBy_SelectionChanged(object? sender, SelectionChangedEventArgs e)
{
if (!_initialOrderByLoaded) return;
var newOrderBy = (OrderByBox.SelectedItem as ComboBoxItem)?.Tag?.ToString() ?? "cpu";
if (newOrderBy == _lastFetchedOrderBy) return;
_lastFetchedOrderBy = newOrderBy;
_fetchCts?.Cancel();
_fetchCts?.Dispose();
_fetchCts = new CancellationTokenSource();
var ct = _fetchCts.Token;
// Capture the current slicer selection so it survives the reload
var selStart = TimeRangeSlicer.SelectionStart;
var selEnd = TimeRangeSlicer.SelectionEnd;
FetchButton.IsEnabled = false;
StatusText.Text = "Refreshing metric...";
try
{
var sliceData = await QueryStoreService.FetchTimeSliceDataAsync(
_connectionString, newOrderBy, _slicerDaysBack, ct);
if (ct.IsCancellationRequested) return;
if (sliceData.Count > 0)
{
// Suppress the implicit RangeChanged fetch — we will refresh the grid explicitly below
_suppressRangeChanged = true;
try { TimeRangeSlicer.LoadData(sliceData, newOrderBy, selStart, selEnd); }
finally { _suppressRangeChanged = false; }
// Explicitly refresh the grid with the new metric and current time range
await FetchPlansForRangeAsync();
}
else
{
StatusText.Text = "No time-slicer data available.";
}
}
catch (OperationCanceledException) { }
catch (Exception ex)
{
StatusText.Text = ex.Message.Length > 80 ? ex.Message[..80] + "..." : ex.Message;
}
finally
{
FetchButton.IsEnabled = true;
}
}
private void TimeDisplay_SelectionChanged(object? sender, SelectionChangedEventArgs e)
{
if (!IsInitialized) return;
var tag = (TimeDisplayBox.SelectedItem as ComboBoxItem)?.Tag?.ToString();
if (tag == null) return;
TimeDisplayHelper.Current = tag switch
{
"Utc" => TimeDisplayMode.Utc,
"Server" => TimeDisplayMode.Server,
_ => TimeDisplayMode.Local
};
// Refresh grid display
if (_filteredRows.Count > 0)
{
foreach (var row in _filteredRows)
row.NotifyTimeDisplayChanged();
ResultsGrid.ItemsSource = null;
ResultsGrid.ItemsSource = _filteredRows;
}
// Refresh slicer labels
TimeRangeSlicer.Redraw();
}
private void ClearSearch_Click(object? sender, RoutedEventArgs e)
{
SearchTypeBox.SelectedIndex = 0;
SearchValueBox.Text = "";
}
private async System.Threading.Tasks.Task LoadTimeSlicerDataAsync(
string metric, CancellationToken ct,
DateTime? preserveStart = null, DateTime? preserveEnd = null)
{
try
{
var sliceData = await QueryStoreService.FetchTimeSliceDataAsync(
_connectionString, metric, _slicerDaysBack, ct);
if (ct.IsCancellationRequested) return;
if (sliceData.Count > 0)
TimeRangeSlicer.LoadData(sliceData, metric, preserveStart, preserveEnd);
else
StatusText.Text = "No time-slicer data available.";
}
catch (OperationCanceledException) { throw; }
catch (Exception ex)
{
StatusText.Text = $"Slicer: {(ex.Message.Length > 60 ? ex.Message[..60] + "..." : ex.Message)}";
}
}
private async void OnTimeRangeChanged(object? sender, TimeRangeChangedEventArgs e)
{
_slicerStartUtc = e.StartUtc;
_slicerEndUtc = e.EndUtc;
if (_suppressRangeChanged) return;
await FetchPlansForRangeAsync();
}
// ── Wait stats ─────────────────────────────────────────────────────────
/// <summary>
/// Fetches global bar + ribbon wait stats (independent of grid plan IDs).
/// Shows loading indicator on the wait stats panel.
/// </summary>
private async System.Threading.Tasks.Task FetchGlobalWaitStatsOnlyAsync(
DateTime startUtc, DateTime endUtc, CancellationToken ct)
{
WaitStatsProfile.SetLoading(true);
try
{
// Global (bar)
var globalWaits = await QueryStoreService.FetchGlobalWaitStatsAsync(
_connectionString, startUtc, endUtc, ct);
if (ct.IsCancellationRequested) { return; }
var globalProfile = QueryStoreService.BuildWaitProfile(globalWaits);
WaitStatsProfile.SetBarProfile(globalProfile);
// Global (ribbon) — fetched lazily, data ready for toggle
var ribbonData = await QueryStoreService.FetchGlobalWaitStatsRibbonAsync(
_connectionString, startUtc, endUtc, ct);
if (ct.IsCancellationRequested) { return; }
WaitStatsProfile.SetRibbonData(ribbonData);
}
catch (OperationCanceledException) { }
catch (Exception) { }
finally
{
WaitStatsProfile.SetLoading(false);
}
}
/// <summary>
/// Fetches per-plan wait stats for the plan IDs currently in the grid.
/// </summary>
private async System.Threading.Tasks.Task FetchPerPlanWaitStatsAsync(
DateTime startUtc, DateTime endUtc, CancellationToken ct)
{
try
{
var visiblePlanIds = _rows.Select(r => r.PlanId).ToList();
var planWaits = await QueryStoreService.FetchPlanWaitStatsAsync(
_connectionString, startUtc, endUtc, visiblePlanIds, ct);
if (ct.IsCancellationRequested) { return; }
var byPlan = planWaits
.GroupBy(x => x.PlanId)
.ToDictionary(g => g.Key, g => g.Select(x => x.Wait).ToList());
foreach (var row in _rows)
{
if (byPlan.TryGetValue(row.PlanId, out var waits))
row.WaitProfile = QueryStoreService.BuildWaitProfile(waits);
else
row.WaitProfile = null;
}
UpdateWaitBarMode();
}
catch (OperationCanceledException) { }
catch (Exception) { }
}
/// <summary>
/// Full wait stats fetch (global + ribbon + per-plan). Used when re-expanding the wait stats panel.
/// </summary>
private async System.Threading.Tasks.Task FetchWaitStatsAsync(
DateTime startUtc, DateTime endUtc, CancellationToken ct)
{
await FetchGlobalWaitStatsOnlyAsync(startUtc, endUtc, ct);
if (_groupByMode != QueryStoreGroupBy.None)
await FetchGroupedWaitStatsAsync(startUtc, endUtc, ct);
else
await FetchPerPlanWaitStatsAsync(startUtc, endUtc, ct);
}
private void OnWaitCategoryClicked(object? sender, string category)
{
// Toggle highlight: click same category again → clear
if (_waitHighlightCategory == category)
_waitHighlightCategory = null;
else
_waitHighlightCategory = category;
ApplyWaitHighlight();
}
private void OnWaitCategoryDoubleClicked(object? sender, string category)
{
_waitHighlightCategory = category;
ApplyWaitHighlight();
// Sort grid by this category's wait ratio (descending)
var sorted = _filteredRows
.OrderByDescending(r =>
r.WaitProfile?.Segments
.Where(s => s.Category == category)