-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathQuerySessionControl.axaml.cs
More file actions
2094 lines (1806 loc) · 76.1 KB
/
QuerySessionControl.axaml.cs
File metadata and controls
2094 lines (1806 loc) · 76.1 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.Diagnostics;
using System.Linq;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Input.Platform;
using Avalonia.Interactivity;
using Avalonia.Layout;
using Avalonia.Media;
using AvaloniaEdit;
using AvaloniaEdit.CodeCompletion;
using AvaloniaEdit.TextMate;
using Microsoft.Data.SqlClient;
using PlanViewer.App.Dialogs;
using PlanViewer.App.Services;
using PlanViewer.Core.Interfaces;
using PlanViewer.Core.Models;
using PlanViewer.Core.Output;
using PlanViewer.Core.Services;
using TextMateSharp.Grammars;
namespace PlanViewer.App.Controls;
public partial class QuerySessionControl : UserControl
{
private readonly ICredentialService _credentialService;
private readonly ConnectionStore _connectionStore;
private ServerConnection? _serverConnection;
private string? _connectionString;
private string? _selectedDatabase;
private int _planCounter;
private CancellationTokenSource? _executionCts;
private ServerMetadata? _serverMetadata;
// TextMate installation for syntax highlighting
private TextMate.Installation? _textMateInstallation;
private CancellationTokenSource? _statusClearCts;
private CompletionWindow? _completionWindow;
public QuerySessionControl(ICredentialService credentialService, ConnectionStore connectionStore)
{
_credentialService = credentialService;
_connectionStore = connectionStore;
InitializeComponent();
// Initialize editor with empty text so the document is ready
QueryEditor.Text = "";
ZoomBox.SelectedIndex = 2; // 100%
SetupSyntaxHighlighting();
SetupEditorContextMenu();
// Keybindings: F5/Ctrl+E for Execute, Ctrl+L for Estimated Plan
KeyDown += OnKeyDown;
// Ctrl+mousewheel for font zoom — use Tunnel so it fires before ScrollViewer consumes scroll-down
QueryEditor.AddHandler(Avalonia.Input.InputElement.PointerWheelChangedEvent, OnEditorPointerWheel, Avalonia.Interactivity.RoutingStrategies.Tunnel);
// Code completion
QueryEditor.TextArea.TextEntering += OnTextEntering;
QueryEditor.TextArea.TextEntered += OnTextEntered;
// Focus the editor when the control is attached to the visual tree
// Re-install TextMate if it was disposed on detach (tab switching disposes it)
AttachedToVisualTree += (_, _) =>
{
if (_textMateInstallation == null)
SetupSyntaxHighlighting();
QueryEditor.Focus();
QueryEditor.TextArea.Focus();
};
// Dispose TextMate when detached (e.g. tab switch) to release renderers/transformers.
// Also cancel any in-flight status-clear dispatch so it doesn't fire on a dead control.
DetachedFromVisualTree += (_, _) =>
{
_textMateInstallation?.Dispose();
_textMateInstallation = null;
_statusClearCts?.Cancel();
_statusClearCts?.Dispose();
_statusClearCts = null;
};
// Focus the editor when the Editor tab is selected; toggle plan-dependent buttons
SubTabControl.SelectionChanged += (_, _) =>
{
if (SubTabControl.SelectedIndex == 0)
{
QueryEditor.Focus();
QueryEditor.TextArea.Focus();
}
UpdatePlanTabButtonState();
};
}
private void SetupSyntaxHighlighting()
{
var registryOptions = new RegistryOptions(ThemeName.DarkPlus);
_textMateInstallation = QueryEditor.InstallTextMate(registryOptions);
_textMateInstallation.SetGrammar(registryOptions.GetScopeByLanguageId("sql"));
}
// Schema context menu items — stored as fields so we can toggle visibility on menu open
private MenuItem? _showIndexesItem;
private MenuItem? _showTableDefItem;
private MenuItem? _showObjectDefItem;
private Separator? _schemaSeparator;
private ResolvedSqlObject? _contextMenuObject;
private void SetupEditorContextMenu()
{
var cutItem = new MenuItem { Header = "Cut" };
cutItem.Click += async (_, _) =>
{
var clipboard = TopLevel.GetTopLevel(this)?.Clipboard;
if (clipboard == null) return;
var selection = QueryEditor.TextArea.Selection;
if (selection.IsEmpty) return;
var text = selection.GetText();
await clipboard.SetTextAsync(text);
selection.ReplaceSelectionWithText("");
};
var copyItem = new MenuItem { Header = "Copy" };
copyItem.Click += async (_, _) =>
{
var clipboard = TopLevel.GetTopLevel(this)?.Clipboard;
if (clipboard == null) return;
var selection = QueryEditor.TextArea.Selection;
if (selection.IsEmpty) return;
await clipboard.SetTextAsync(selection.GetText());
};
var pasteItem = new MenuItem { Header = "Paste" };
pasteItem.Click += async (_, _) =>
{
var clipboard = TopLevel.GetTopLevel(this)?.Clipboard;
if (clipboard == null) return;
var text = await clipboard.TryGetTextAsync();
if (string.IsNullOrEmpty(text)) return;
QueryEditor.TextArea.PerformTextInput(text);
};
var selectAllItem = new MenuItem { Header = "Select All" };
selectAllItem.Click += (_, _) =>
{
QueryEditor.SelectAll();
};
var executeFromCursorItem = new MenuItem { Header = "Execute from Cursor" };
executeFromCursorItem.Click += async (_, _) =>
{
var text = GetTextFromCursor();
if (!string.IsNullOrWhiteSpace(text))
await CaptureAndShowPlan(estimated: false, queryTextOverride: text);
};
var executeCurrentBatchItem = new MenuItem { Header = "Execute Current Batch" };
executeCurrentBatchItem.Click += async (_, _) =>
{
var text = GetCurrentBatch();
if (!string.IsNullOrWhiteSpace(text))
await CaptureAndShowPlan(estimated: false, queryTextOverride: text);
};
// Schema lookup items
_schemaSeparator = new Separator();
_showIndexesItem = new MenuItem { Header = "Show Indexes" };
_showIndexesItem.Click += async (_, _) => await ShowSchemaInfoAsync(SchemaInfoKind.Indexes);
_showTableDefItem = new MenuItem { Header = "Show Table Definition" };
_showTableDefItem.Click += async (_, _) => await ShowSchemaInfoAsync(SchemaInfoKind.TableDefinition);
_showObjectDefItem = new MenuItem { Header = "Show Object Definition" };
_showObjectDefItem.Click += async (_, _) => await ShowSchemaInfoAsync(SchemaInfoKind.ObjectDefinition);
var contextMenu = new ContextMenu
{
Items =
{
cutItem, copyItem, pasteItem,
new Separator(), selectAllItem,
new Separator(), executeFromCursorItem, executeCurrentBatchItem,
_schemaSeparator,
_showIndexesItem, _showTableDefItem, _showObjectDefItem
}
};
contextMenu.Opening += OnContextMenuOpening;
QueryEditor.TextArea.ContextMenu = contextMenu;
// Move caret to right-click position so schema lookup resolves the clicked object
QueryEditor.TextArea.PointerPressed += OnEditorPointerPressed;
}
private void OnEditorPointerPressed(object? sender, Avalonia.Input.PointerPressedEventArgs e)
{
if (!e.GetCurrentPoint(QueryEditor.TextArea).Properties.IsRightButtonPressed)
return;
var pos = QueryEditor.GetPositionFromPoint(e.GetPosition(QueryEditor));
if (pos == null) return;
QueryEditor.TextArea.Caret.Position = pos.Value;
}
private void OnContextMenuOpening(object? sender, System.ComponentModel.CancelEventArgs e)
{
// Resolve what object is under the cursor
var sqlText = QueryEditor.Text;
var offset = QueryEditor.CaretOffset;
_contextMenuObject = SqlObjectResolver.Resolve(sqlText, offset);
var hasConnection = _connectionString != null;
var hasObject = _contextMenuObject != null && hasConnection;
_schemaSeparator!.IsVisible = hasObject;
_showIndexesItem!.IsVisible = hasObject && _contextMenuObject!.Kind is SqlObjectKind.Table or SqlObjectKind.Unknown;
_showTableDefItem!.IsVisible = hasObject && _contextMenuObject!.Kind is SqlObjectKind.Table or SqlObjectKind.Unknown;
_showObjectDefItem!.IsVisible = hasObject && _contextMenuObject!.Kind is SqlObjectKind.Function or SqlObjectKind.Procedure;
// Update headers to show the object name
if (hasObject)
{
var name = _contextMenuObject!.FullName;
_showIndexesItem.Header = $"Show Indexes — {name}";
_showTableDefItem.Header = $"Show Table Definition — {name}";
_showObjectDefItem.Header = $"Show Object Definition — {name}";
}
}
private enum SchemaInfoKind { Indexes, TableDefinition, ObjectDefinition }
private async Task ShowSchemaInfoAsync(SchemaInfoKind kind)
{
if (_contextMenuObject == null || _connectionString == null) return;
var objectName = _contextMenuObject.FullName;
SetStatus($"Fetching {kind} for {objectName}...", autoClear: false);
try
{
string content;
string tabLabel;
switch (kind)
{
case SchemaInfoKind.Indexes:
var indexes = await SchemaQueryService.FetchIndexesAsync(_connectionString, objectName);
content = FormatIndexes(objectName, indexes);
tabLabel = $"Indexes — {objectName}";
break;
case SchemaInfoKind.TableDefinition:
var columns = await SchemaQueryService.FetchColumnsAsync(_connectionString, objectName);
var tableIndexes = await SchemaQueryService.FetchIndexesAsync(_connectionString, objectName);
content = FormatColumns(objectName, columns, tableIndexes);
tabLabel = $"Table — {objectName}";
break;
case SchemaInfoKind.ObjectDefinition:
var definition = await SchemaQueryService.FetchObjectDefinitionAsync(_connectionString, objectName);
content = definition ?? $"-- No definition found for {objectName}";
tabLabel = $"Definition — {objectName}";
break;
default:
return;
}
AddSchemaTab(tabLabel, content, isSql: true);
SetStatus($"Loaded {kind} for {objectName}");
}
catch (Exception ex)
{
SetStatus($"Error: {ex.Message}", autoClear: false);
Debug.WriteLine($"Schema lookup error: {ex}");
}
}
private void AddSchemaTab(string label, string content, bool isSql)
{
var editor = new TextEditor
{
Text = content,
IsReadOnly = true,
FontFamily = new FontFamily("Consolas, Menlo, monospace"),
FontSize = 13,
ShowLineNumbers = true,
Background = (IBrush)this.FindResource("BackgroundBrush")!,
Foreground = (IBrush)this.FindResource("ForegroundBrush")!,
HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Auto,
VerticalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Auto,
Padding = new Avalonia.Thickness(4)
};
if (isSql)
{
var registryOptions = new RegistryOptions(ThemeName.DarkPlus);
var tm = editor.InstallTextMate(registryOptions);
tm.SetGrammar(registryOptions.GetScopeByLanguageId("sql"));
}
// Context menu for read-only schema tabs
var schemaCopy = new MenuItem { Header = "Copy" };
schemaCopy.Click += async (_, _) =>
{
var clipboard = TopLevel.GetTopLevel(this)?.Clipboard;
if (clipboard == null) return;
var sel = editor.TextArea.Selection;
if (!sel.IsEmpty)
await clipboard.SetTextAsync(sel.GetText());
};
var schemaCopyAll = new MenuItem { Header = "Copy All" };
schemaCopyAll.Click += async (_, _) =>
{
var clipboard = TopLevel.GetTopLevel(this)?.Clipboard;
if (clipboard == null) return;
await clipboard.SetTextAsync(editor.Text);
};
var schemaSelectAll = new MenuItem { Header = "Select All" };
schemaSelectAll.Click += (_, _) => editor.SelectAll();
editor.TextArea.ContextMenu = new ContextMenu
{
Items = { schemaCopy, schemaCopyAll, new Separator(), schemaSelectAll }
};
var headerText = new TextBlock
{
Text = label,
VerticalAlignment = VerticalAlignment.Center,
FontSize = 12
};
var closeBtn = new Button
{
Content = "\u2715",
MinWidth = 22, MinHeight = 22, Width = 22, Height = 22,
Padding = new Avalonia.Thickness(0),
FontSize = 11,
Margin = new Avalonia.Thickness(6, 0, 0, 0),
Background = Brushes.Transparent,
BorderThickness = new Avalonia.Thickness(0),
Foreground = new SolidColorBrush(Color.FromRgb(0xE4, 0xE6, 0xEB)),
VerticalAlignment = VerticalAlignment.Center,
HorizontalContentAlignment = HorizontalAlignment.Center,
VerticalContentAlignment = VerticalAlignment.Center
};
var header = new StackPanel
{
Orientation = Orientation.Horizontal,
Children = { headerText, closeBtn }
};
var tab = new TabItem { Header = header, Content = editor };
closeBtn.Tag = tab;
closeBtn.Click += (s, _) =>
{
if (s is Button btn && btn.Tag is TabItem t)
SubTabControl.Items.Remove(t);
};
SubTabControl.Items.Add(tab);
SubTabControl.SelectedItem = tab;
}
private static string FormatIndexes(string objectName, IReadOnlyList<IndexInfo> indexes)
{
if (indexes.Count == 0)
return $"-- No indexes found on {objectName}";
var sb = new System.Text.StringBuilder();
sb.AppendLine($"-- Indexes on {objectName}");
sb.AppendLine($"-- {indexes.Count} index(es), {indexes[0].RowCount:N0} rows");
sb.AppendLine();
foreach (var ix in indexes)
{
if (ix.IsDisabled)
sb.AppendLine("-- ** DISABLED **");
// Usage stats as a comment
sb.AppendLine($"-- {ix.SizeMB:N1} MB | Seeks: {ix.UserSeeks:N0} | Scans: {ix.UserScans:N0} | Lookups: {ix.UserLookups:N0} | Updates: {ix.UserUpdates:N0}");
var withOptions = BuildWithOptions(ix);
var onPartition = ix.PartitionScheme != null && ix.PartitionColumn != null
? $"ON {BracketName(ix.PartitionScheme)}({BracketName(ix.PartitionColumn)})"
: null;
if (ix.IsPrimaryKey)
{
var clustered = ix.IndexType.Contains("CLUSTERED", System.StringComparison.OrdinalIgnoreCase)
&& !ix.IndexType.Contains("NONCLUSTERED", System.StringComparison.OrdinalIgnoreCase)
? "CLUSTERED" : "NONCLUSTERED";
sb.AppendLine($"ALTER TABLE {objectName}");
sb.AppendLine($"ADD CONSTRAINT {BracketName(ix.IndexName)}");
sb.Append($" PRIMARY KEY {clustered} ({ix.KeyColumns})");
if (withOptions.Count > 0)
{
sb.AppendLine();
sb.Append($" WITH ({string.Join(", ", withOptions)})");
}
if (onPartition != null)
{
sb.AppendLine();
sb.Append($" {onPartition}");
}
sb.AppendLine(";");
}
else if (IsColumnstore(ix))
{
// Columnstore indexes: no key columns, no INCLUDE, no row/page lock or compression options
var clustered = ix.IndexType.Contains("NONCLUSTERED", System.StringComparison.OrdinalIgnoreCase)
? "NONCLUSTERED " : "CLUSTERED ";
sb.Append($"CREATE {clustered}COLUMNSTORE INDEX {BracketName(ix.IndexName)}");
sb.AppendLine($" ON {objectName}");
// Nonclustered columnstore can have a column list
if (ix.IndexType.Contains("NONCLUSTERED", System.StringComparison.OrdinalIgnoreCase)
&& !string.IsNullOrEmpty(ix.KeyColumns))
{
sb.AppendLine($"({ix.KeyColumns})");
}
// Only emit non-default options that aren't inherent to columnstore
var csOptions = BuildColumnstoreWithOptions(ix);
if (csOptions.Count > 0)
sb.AppendLine($"WITH ({string.Join(", ", csOptions)})");
if (onPartition != null)
sb.AppendLine(onPartition);
// Remove trailing newline before semicolon
if (sb[sb.Length - 1] == '\n') sb.Length--;
if (sb[sb.Length - 1] == '\r') sb.Length--;
sb.AppendLine(";");
}
else
{
var unique = ix.IsUnique ? "UNIQUE " : "";
var clustered = ix.IndexType.Contains("CLUSTERED", System.StringComparison.OrdinalIgnoreCase)
&& !ix.IndexType.Contains("NONCLUSTERED", System.StringComparison.OrdinalIgnoreCase)
? "CLUSTERED " : "NONCLUSTERED ";
sb.Append($"CREATE {unique}{clustered}INDEX {BracketName(ix.IndexName)}");
sb.AppendLine($" ON {objectName}");
sb.Append($"(");
sb.Append(ix.KeyColumns);
sb.AppendLine(")");
if (!string.IsNullOrEmpty(ix.IncludeColumns))
sb.AppendLine($"INCLUDE ({ix.IncludeColumns})");
if (!string.IsNullOrEmpty(ix.FilterDefinition))
sb.AppendLine($"WHERE {ix.FilterDefinition}");
if (withOptions.Count > 0)
sb.AppendLine($"WITH ({string.Join(", ", withOptions)})");
if (onPartition != null)
sb.AppendLine(onPartition);
// Remove trailing newline before semicolon
if (sb[sb.Length - 1] == '\n') sb.Length--;
if (sb[sb.Length - 1] == '\r') sb.Length--;
sb.AppendLine(";");
}
sb.AppendLine();
}
return sb.ToString();
}
private static bool IsColumnstore(IndexInfo ix) =>
ix.IndexType.Contains("COLUMNSTORE", System.StringComparison.OrdinalIgnoreCase);
private static List<string> BuildWithOptions(IndexInfo ix)
{
var options = new List<string>();
if (ix.FillFactor > 0 && ix.FillFactor != 100)
options.Add($"FILLFACTOR = {ix.FillFactor}");
if (ix.IsPadded)
options.Add("PAD_INDEX = ON");
if (!ix.AllowRowLocks)
options.Add("ALLOW_ROW_LOCKS = OFF");
if (!ix.AllowPageLocks)
options.Add("ALLOW_PAGE_LOCKS = OFF");
if (!string.Equals(ix.DataCompression, "NONE", System.StringComparison.OrdinalIgnoreCase))
options.Add($"DATA_COMPRESSION = {ix.DataCompression}");
return options;
}
/// <summary>
/// For columnstore indexes, skip options that are inherent to the storage format
/// (row/page locks are always OFF, compression is always COLUMNSTORE).
/// Only emit fill factor and pad index if non-default.
/// </summary>
private static List<string> BuildColumnstoreWithOptions(IndexInfo ix)
{
var options = new List<string>();
if (ix.FillFactor > 0 && ix.FillFactor != 100)
options.Add($"FILLFACTOR = {ix.FillFactor}");
if (ix.IsPadded)
options.Add("PAD_INDEX = ON");
return options;
}
private static string FormatColumns(string objectName, IReadOnlyList<ColumnInfo> columns, IReadOnlyList<IndexInfo> indexes)
{
if (columns.Count == 0)
return $"-- No columns found for {objectName}";
var sb = new System.Text.StringBuilder();
sb.AppendLine($"CREATE TABLE {objectName}");
sb.AppendLine("(");
for (int i = 0; i < columns.Count; i++)
{
var col = columns[i];
var isLast = i == columns.Count - 1;
sb.Append($" {BracketName(col.ColumnName)} ");
if (col.IsComputed && col.ComputedDefinition != null)
{
sb.Append($"AS {col.ComputedDefinition}");
}
else
{
sb.Append(col.DataType);
if (col.IsIdentity)
sb.Append($" IDENTITY({col.IdentitySeed}, {col.IdentityIncrement})");
sb.Append(col.IsNullable ? " NULL" : " NOT NULL");
if (col.DefaultValue != null)
sb.Append($" DEFAULT {col.DefaultValue}");
}
// Check if we need a PK constraint after all columns
var pk = indexes.FirstOrDefault(ix => ix.IsPrimaryKey);
var needsTrailingComma = !isLast || pk != null;
sb.AppendLine(needsTrailingComma ? "," : "");
}
// Add PK constraint
var pkIndex = indexes.FirstOrDefault(ix => ix.IsPrimaryKey);
if (pkIndex != null)
{
var clustered = pkIndex.IndexType.Contains("CLUSTERED", System.StringComparison.OrdinalIgnoreCase)
&& !pkIndex.IndexType.Contains("NONCLUSTERED", System.StringComparison.OrdinalIgnoreCase)
? "CLUSTERED " : "NONCLUSTERED ";
sb.AppendLine($" CONSTRAINT {BracketName(pkIndex.IndexName)}");
sb.Append($" PRIMARY KEY {clustered}({pkIndex.KeyColumns})");
var pkOptions = BuildWithOptions(pkIndex);
if (pkOptions.Count > 0)
{
sb.AppendLine();
sb.Append($" WITH ({string.Join(", ", pkOptions)})");
}
sb.AppendLine();
}
sb.Append(")");
// Add partition scheme from the clustered index (determines table storage)
var clusteredIx = indexes.FirstOrDefault(ix =>
ix.IndexType.Contains("CLUSTERED", System.StringComparison.OrdinalIgnoreCase)
&& !ix.IndexType.Contains("NONCLUSTERED", System.StringComparison.OrdinalIgnoreCase));
if (clusteredIx?.PartitionScheme != null && clusteredIx.PartitionColumn != null)
{
sb.AppendLine();
sb.Append($"ON {BracketName(clusteredIx.PartitionScheme)}({BracketName(clusteredIx.PartitionColumn)})");
}
sb.AppendLine(";");
return sb.ToString();
}
private static string BracketName(string name)
{
// Already bracketed
if (name.StartsWith('['))
return name;
return $"[{name}]";
}
private void OnOpenInEditorRequested(object? sender, string queryText)
{
QueryEditor.Text = queryText;
SubTabControl.SelectedIndex = 0; // Switch to the editor tab
QueryEditor.Focus();
}
private void OnKeyDown(object? sender, KeyEventArgs e)
{
// F5 or Ctrl+E → Execute (actual plan)
if ((e.Key == Key.F5 || (e.Key == Key.E && e.KeyModifiers == KeyModifiers.Control))
&& ExecuteButton.IsEnabled)
{
Execute_Click(this, new RoutedEventArgs());
e.Handled = true;
}
// Ctrl+L → Estimated plan
else if (e.Key == Key.L && e.KeyModifiers == KeyModifiers.Control
&& ExecuteEstButton.IsEnabled)
{
ExecuteEstimated_Click(this, new RoutedEventArgs());
e.Handled = true;
}
// Escape → Cancel running query
else if (e.Key == Key.Escape && _executionCts != null && !_executionCts.IsCancellationRequested)
{
_executionCts.Cancel();
e.Handled = true;
}
}
private void OnEditorPointerWheel(object? sender, PointerWheelEventArgs e)
{
if (e.KeyModifiers != KeyModifiers.Control) return;
var delta = e.Delta.Y > 0 ? 1 : -1;
var newSize = QueryEditor.FontSize + delta;
QueryEditor.FontSize = Math.Clamp(newSize, 7, 52);
SyncZoomDropdown();
e.Handled = true;
}
private void Zoom_SelectionChanged(object? sender, SelectionChangedEventArgs e)
{
if (ZoomBox.SelectedItem is ComboBoxItem item && item.Tag is string tagStr
&& int.TryParse(tagStr, out var size))
{
QueryEditor.FontSize = size;
}
}
private void SyncZoomDropdown()
{
// Find the closest matching zoom level
var fontSize = (int)Math.Round(QueryEditor.FontSize);
int bestIdx = 2; // default 100%
int bestDist = int.MaxValue;
for (int i = 0; i < ZoomBox.Items.Count; i++)
{
if (ZoomBox.Items[i] is ComboBoxItem item && item.Tag is string tagStr
&& int.TryParse(tagStr, out var size))
{
var dist = Math.Abs(size - fontSize);
if (dist < bestDist) { bestDist = dist; bestIdx = i; }
}
}
ZoomBox.SelectionChanged -= Zoom_SelectionChanged;
ZoomBox.SelectedIndex = bestIdx;
ZoomBox.SelectionChanged += Zoom_SelectionChanged;
}
private void OnTextEntering(object? sender, TextInputEventArgs e)
{
if (_completionWindow == null || string.IsNullOrEmpty(e.Text)) return;
// If the user types a non-identifier character, let the completion window
// decide whether to commit (it handles Tab/Enter/Space automatically)
var ch = e.Text[0];
if (!char.IsLetterOrDigit(ch) && ch != '_')
{
_completionWindow.CompletionList.RequestInsertion(e);
}
}
private void OnTextEntered(object? sender, TextInputEventArgs e)
{
if (_completionWindow != null) return;
if (string.IsNullOrEmpty(e.Text) || !char.IsLetter(e.Text[0])) return;
var (prefix, wordStart) = GetWordBeforeCaret();
if (prefix.Length < 2) return;
var matches = SqlKeywords.All
.Where(k => k.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
.ToArray();
if (matches.Length == 0) return;
_completionWindow = new CompletionWindow(QueryEditor.TextArea);
_completionWindow.StartOffset = wordStart;
_completionWindow.Closed += (_, _) => _completionWindow = null;
foreach (var kw in matches)
_completionWindow.CompletionList.CompletionData.Add(new SqlCompletionData(kw));
_completionWindow.Show();
}
private (string prefix, int startOffset) GetWordBeforeCaret()
{
var doc = QueryEditor.Document;
var offset = QueryEditor.CaretOffset;
var start = offset;
while (start > 0)
{
var ch = doc.GetCharAt(start - 1);
if (char.IsLetterOrDigit(ch) || ch == '_')
start--;
else
break;
}
return (doc.GetText(start, offset - start), start);
}
private string? GetSelectedTextOrNull()
{
var selection = QueryEditor.TextArea.Selection;
if (selection.IsEmpty) return null;
return selection.GetText();
}
private string GetTextFromCursor()
{
var doc = QueryEditor.Document;
var offset = QueryEditor.CaretOffset;
return doc.GetText(offset, doc.TextLength - offset);
}
private string? GetCurrentBatch()
{
var doc = QueryEditor.Document;
var caretOffset = QueryEditor.CaretOffset;
var text = doc.Text;
var goPattern = new Regex(@"^\s*GO\s*$", RegexOptions.IgnoreCase | RegexOptions.Multiline);
var matches = goPattern.Matches(text);
int batchStart = 0;
int batchEnd = text.Length;
foreach (Match m in matches)
{
if (m.Index + m.Length <= caretOffset)
{
batchStart = m.Index + m.Length;
}
else if (m.Index >= caretOffset)
{
batchEnd = m.Index;
break;
}
}
return text[batchStart..batchEnd].Trim();
}
private void SetStatus(string text, bool autoClear = true)
{
var old = _statusClearCts;
_statusClearCts = null;
old?.Cancel();
old?.Dispose();
StatusText.Text = text;
if (autoClear && !string.IsNullOrEmpty(text))
{
var cts = new CancellationTokenSource();
_statusClearCts = cts;
_ = Task.Delay(3000, cts.Token).ContinueWith(_ =>
{
Avalonia.Threading.Dispatcher.UIThread.Post(() => StatusText.Text = "");
}, TaskContinuationOptions.OnlyOnRanToCompletion);
}
}
private async void Connect_Click(object? sender, RoutedEventArgs e)
{
await ShowConnectionDialogAsync();
}
private async Task ShowConnectionDialogAsync()
{
var dialog = new ConnectionDialog(_credentialService, _connectionStore);
var result = await dialog.ShowDialog<bool?>(GetParentWindow());
if (result == true && dialog.ResultConnection != null)
{
_serverConnection = dialog.ResultConnection;
_selectedDatabase = dialog.ResultDatabase;
_connectionString = _serverConnection.GetConnectionString(_credentialService, _selectedDatabase);
ServerLabel.Text = _serverConnection.ServerName;
ServerLabel.Foreground = Brushes.LimeGreen;
ConnectButton.Content = "Reconnect";
await PopulateDatabases();
await FetchServerMetadataAsync();
await FetchServerUtcOffset();
if (_selectedDatabase != null)
{
for (int i = 0; i < DatabaseBox.Items.Count; i++)
{
if (DatabaseBox.Items[i]?.ToString() == _selectedDatabase)
{
DatabaseBox.SelectedIndex = i;
break;
}
}
}
await FetchDatabaseMetadataAsync();
ExecuteButton.IsEnabled = true;
ExecuteEstButton.IsEnabled = true;
}
}
private async Task PopulateDatabases()
{
if (_serverConnection == null) return;
try
{
var connStr = _serverConnection.GetConnectionString(_credentialService, "master");
await using var conn = new SqlConnection(connStr);
await conn.OpenAsync();
var databases = new List<string>();
using var cmd = new SqlCommand(
"SELECT name FROM sys.databases WHERE state_desc = 'ONLINE' ORDER BY name", conn);
using var reader = await cmd.ExecuteReaderAsync();
while (await reader.ReadAsync())
databases.Add(reader.GetString(0));
DatabaseBox.ItemsSource = databases;
DatabaseBox.IsEnabled = true;
}
catch
{
DatabaseBox.IsEnabled = false;
}
}
private async void Database_SelectionChanged(object? sender, SelectionChangedEventArgs e)
{
if (_serverConnection == null || DatabaseBox.SelectedItem == null) return;
_selectedDatabase = DatabaseBox.SelectedItem.ToString();
_connectionString = _serverConnection.GetConnectionString(_credentialService, _selectedDatabase);
// Refresh database metadata for the new context
await FetchDatabaseMetadataAsync();
}
private bool IsAzureConnection =>
_serverConnection != null &&
(_serverConnection.ServerName.Contains(".database.windows.net", StringComparison.OrdinalIgnoreCase) ||
_serverConnection.ServerName.Contains(".database.azure.com", StringComparison.OrdinalIgnoreCase));
private async Task FetchServerMetadataAsync()
{
if (_connectionString == null) return;
try
{
_serverMetadata = await ServerMetadataService.FetchServerMetadataAsync(
_connectionString, IsAzureConnection);
}
catch
{
// Non-fatal — advice will just lack server context
_serverMetadata = null;
}
}
private async Task FetchServerUtcOffset()
{
if (_connectionString == null) return;
try
{
await using var conn = new SqlConnection(_connectionString);
await conn.OpenAsync();
await using var cmd = new SqlCommand(
"SELECT DATEDIFF(MINUTE, GETUTCDATE(), GETDATE())", conn);
var offset = await cmd.ExecuteScalarAsync();
if (offset is int mins)
PlanViewer.Core.Services.TimeDisplayHelper.ServerUtcOffsetMinutes = mins;
}
catch { }
}
private async Task FetchDatabaseMetadataAsync()
{
if (_connectionString == null || _serverMetadata == null) return;
try
{
_serverMetadata.Database = await ServerMetadataService.FetchDatabaseMetadataAsync(
_connectionString, _serverMetadata.SupportsScopedConfigs);
}
catch
{
// Non-fatal — advice will just lack database context
}
}
private async void Execute_Click(object? sender, RoutedEventArgs e)
{
await CaptureAndShowPlan(estimated: false);
}
private async void ExecuteEstimated_Click(object? sender, RoutedEventArgs e)
{
await CaptureAndShowPlan(estimated: true);
}
private async Task CaptureAndShowPlan(bool estimated, string? queryTextOverride = null)
{
if (_serverConnection == null || _selectedDatabase == null)
{
SetStatus("Connect to a server first", autoClear: false);
return;
}
// Always rebuild connection string from current database selection
// to guarantee the picker state is reflected at execution time
_connectionString = _serverConnection.GetConnectionString(_credentialService, _selectedDatabase);
var queryText = queryTextOverride?.Trim()
?? GetSelectedTextOrNull()?.Trim()
?? QueryEditor.Text?.Trim();
if (string.IsNullOrEmpty(queryText))
{
SetStatus("Enter a query", autoClear: false);
return;
}
_executionCts?.Cancel();
_executionCts?.Dispose();
_executionCts = new CancellationTokenSource();
var ct = _executionCts.Token;
var planType = estimated ? "Estimated" : "Actual";
// Create loading tab with cancel button
var loadingPanel = new StackPanel
{
VerticalAlignment = VerticalAlignment.Center,
HorizontalAlignment = HorizontalAlignment.Center,
Width = 300
};
var progressBar = new ProgressBar
{
IsIndeterminate = true,
Height = 4,
Margin = new Avalonia.Thickness(0, 0, 0, 12)
};
var statusLabel = new TextBlock
{
Text = $"Capturing {planType.ToLower()} plan...",
FontSize = 14,
Foreground = new SolidColorBrush(Color.Parse("#E4E6EB")),
HorizontalAlignment = HorizontalAlignment.Center
};
var cancelBtn = new Button
{
Content = "\u25A0 Cancel",
Height = 32,
Width = 120,
Padding = new Avalonia.Thickness(16, 0),
FontSize = 13,
Margin = new Avalonia.Thickness(0, 16, 0, 0),
HorizontalAlignment = HorizontalAlignment.Center,
HorizontalContentAlignment = HorizontalAlignment.Center,
VerticalContentAlignment = VerticalAlignment.Center,
Theme = (Avalonia.Styling.ControlTheme)this.FindResource("AppButton")!
};
cancelBtn.Click += (_, _) => _executionCts?.Cancel();