/
tabletools.pas
1840 lines (1674 loc) · 74.7 KB
/
tabletools.pas
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
unit tabletools;
// -------------------------------------
// Table-diagnostics
// -------------------------------------
interface
uses
Windows, SysUtils, Classes, Controls, Forms, StdCtrls, ComCtrls, Buttons, Dialogs, StdActns,
VirtualTrees, ExtCtrls, Graphics, SynRegExpr, Math, Generics.Collections, extra_controls,
dbconnection, helpers, Menus, gnugettext, DateUtils, System.Zip, System.UITypes, StrUtils;
type
TToolMode = (tmMaintenance, tmFind, tmSQLExport, tmBulkTableEdit);
TfrmTableTools = class(TFormWithSizeGrip)
btnCloseOrCancel: TButton;
pnlTop: TPanel;
TreeObjects: TVirtualStringTree;
spltHorizontally: TSplitter;
pnlRight: TPanel;
ResultGrid: TVirtualStringTree;
tabsTools: TPageControl;
tabMaintenance: TTabSheet;
comboOperation: TComboBox;
lblOperation: TLabel;
chkQuick: TCheckBox;
chkFast: TCheckBox;
chkMedium: TCheckBox;
chkExtended: TCheckBox;
chkChanged: TCheckBox;
chkUseFrm: TCheckBox;
lblOptions: TLabel;
btnHelpMaintenance: TButton;
tabFind: TTabSheet;
lblFindText: TLabel;
memoFindText: TMemo;
comboDataTypes: TComboBox;
lblDataTypes: TLabel;
tabSQLexport: TTabSheet;
chkExportDatabasesCreate: TCheckBox;
chkExportDatabasesDrop: TCheckBox;
chkExportTablesDrop: TCheckBox;
chkExportTablesCreate: TCheckBox;
lblExportData: TLabel;
comboExportData: TComboBox;
lblExportOutputType: TLabel;
comboExportOutputType: TComboBox;
comboExportOutputTarget: TComboBox;
lblExportDatabases: TLabel;
lblExportTables: TLabel;
lblExportOutputTarget: TLabel;
btnExecute: TButton;
btnExportOutputTargetSelect: TButton;
tabBulkTableEdit: TTabSheet;
chkBulkTableEditDatabase: TCheckBox;
comboBulkTableEditDatabase: TComboBox;
chkBulkTableEditResetAutoinc: TCheckBox;
chkBulkTableEditCollation: TCheckBox;
comboBulkTableEditCollation: TComboBox;
chkBulkTableEditEngine: TCheckBox;
comboBulkTableEditEngine: TComboBox;
chkBulkTableEditCharset: TCheckBox;
comboBulkTableEditCharset: TComboBox;
btnSeeResults: TButton;
chkCaseSensitive: TCheckBox;
lblCheckedSize: TLabel;
popupTree: TPopupMenu;
menuCheckAll: TMenuItem;
menuCheckByType: TMenuItem;
menuCheckNone: TMenuItem;
chkForUpgrade: TCheckBox;
lblInsertSize: TLabel;
editInsertSize: TEdit;
updownInsertSize: TUpDown;
lblInsertSizeUnit: TLabel;
btnHelpSQLExport: TButton;
btnExportOptions: TButton;
popupExportOptions: TPopupMenu;
menuExportAddComments: TMenuItem;
menuExportRemoveAutoIncrement: TMenuItem;
comboMatchType: TComboBox;
lblMatchType: TLabel;
procedure FormDestroy(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure btnHelpMaintenanceClick(Sender: TObject);
procedure TreeObjectsGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex;
TextType: TVSTTextType; var CellText: String);
procedure TreeObjectsInitNode(Sender: TBaseVirtualTree; ParentNode, Node: PVirtualNode;
var InitialStates: TVirtualNodeInitStates);
procedure TreeObjectsGetImageIndex(Sender: TBaseVirtualTree; Node: PVirtualNode; Kind: TVTImageKind;
Column: TColumnIndex; var Ghosted: Boolean; var ImageIndex: Integer);
procedure TreeObjectsInitChildren(Sender: TBaseVirtualTree; Node: PVirtualNode; var ChildCount: Cardinal);
procedure Execute(Sender: TObject);
procedure ResultGridInitNode(Sender: TBaseVirtualTree; ParentNode, Node: PVirtualNode;
var InitialStates: TVirtualNodeInitStates);
procedure ResultGridGetNodeDataSize(Sender: TBaseVirtualTree; var NodeDataSize: Integer);
procedure ResultGridGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex;
TextType: TVSTTextType; var CellText: String);
procedure TreeObjectsChecked(Sender: TBaseVirtualTree; Node: PVirtualNode);
procedure ResultGridHeaderClick(Sender: TVTHeader; HitInfo: TVTHeaderHitInfo);
procedure ResultGridCompareNodes(Sender: TBaseVirtualTree; Node1, Node2: PVirtualNode;
Column: TColumnIndex; var Result: Integer);
procedure ResultGridPaintText(Sender: TBaseVirtualTree; const TargetCanvas: TCanvas; Node: PVirtualNode;
Column: TColumnIndex; TextType: TVSTTextType);
procedure ValidateControls(Sender: TObject);
procedure SaveSettings(Sender: TObject);
procedure chkExportOptionClick(Sender: TObject);
procedure btnExportOutputTargetSelectClick(Sender: TObject);
procedure comboExportOutputTargetChange(Sender: TObject);
procedure comboExportOutputTypeChange(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure TreeObjectsPaintText(Sender: TBaseVirtualTree; const TargetCanvas: TCanvas; Node: PVirtualNode;
Column: TColumnIndex; TextType: TVSTTextType);
procedure chkBulkTableEditCheckComboClick(Sender: TObject);
procedure TreeObjectsChange(Sender: TBaseVirtualTree; Node: PVirtualNode);
procedure TreeObjectsChecking(Sender: TBaseVirtualTree; Node: PVirtualNode; var NewState: TCheckState;
var Allowed: Boolean);
procedure btnSeeResultsClick(Sender: TObject);
procedure TreeObjectsGetNodeDataSize(Sender: TBaseVirtualTree; var NodeDataSize: Integer);
procedure btnCloseOrCancelClick(Sender: TObject);
procedure TreeObjectsBeforeCellPaint(Sender: TBaseVirtualTree; TargetCanvas: TCanvas;
Node: PVirtualNode; Column: TColumnIndex; CellPaintMode: TVTCellPaintMode; CellRect: TRect;
var ContentRect: TRect);
procedure CheckAllClick(Sender: TObject);
procedure TreeObjectsExpanded(Sender: TBaseVirtualTree; Node: PVirtualNode);
procedure btnHelpSQLExportClick(Sender: TObject);
procedure btnExportOptionsClick(Sender: TObject);
private
{ Private declarations }
FResults: TObjectList<TStringList>;
FToolMode: TToolMode;
FSecondExportPass: Boolean; // Set to True after everything is exported and final VIEWs need to be exported again
FCancelled: Boolean;
ExportStream: TStream;
FExportFileName: String;
ExportStreamStartOfQueryPos: Int64;
ExportLastDatabase: String;
FTargetConnection: TDBConnection;
FLastOutputSelectedIndex: Integer;
FModifiedDbs: TStringList;
FHeaderCreated: Boolean;
FFindSeeResultSQL: TStringList;
ToFile, ToDir, ToClipboard, ToDb, ToServer: Boolean;
FObjectSizes, FObjectSizesDone, FObjectSizesDoneExact: Int64;
procedure SetToolMode(Value: TToolMode);
procedure Output(SQL: String; IsEndOfQuery, ForFile, ForDir, ForDb, ForServer: Boolean);
procedure AddResults(SQL: String; Connection: TDBConnection);
procedure AddNotes(Col1, Col2, Col3, Col4: String); overload;
procedure AddNotes(DBObject: TDBObject; Msg1, Msg2: String); overload;
procedure SetupResultGrid(Results: TDBQuery=nil);
procedure UpdateResultGrid;
procedure DoMaintenance(DBObj: TDBObject);
procedure DoFind(DBObj: TDBObject);
procedure DoExport(DBObj: TDBObject);
procedure DoBulkTableEdit(DBObj: TDBObject);
public
{ Public declarations }
PreSelectObjects: TDBObjectList;
property ToolMode: TToolMode read FToolMode write SetToolMode;
end;
implementation
uses main, mysql_structures;
const
STRSKIPPED: String = 'Skipped - ';
EXPORT_FILE_FOOTER = '/*!40101 SET SQL_MODE=IFNULL(@OLD_SQL_MODE, '''') */;'+CRLF+
'/*!40014 SET FOREIGN_KEY_CHECKS=IF(@OLD_FOREIGN_KEY_CHECKS IS NULL, 1, @OLD_FOREIGN_KEY_CHECKS) */;'+CRLF+
'/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;'+CRLF;
var
OUTPUT_FILE,
OUTPUT_FILE_COMPRESSED,
OUTPUT_CLIPBOARD,
OUTPUT_DIR,
OUTPUT_DB,
OUTPUT_SERVER,
DATA_NO,
DATA_REPLACE,
DATA_INSERT,
DATA_INSERTNEW,
DATA_UPDATE : String;
{$R *.DFM}
procedure TfrmTableTools.FormCreate(Sender: TObject);
var
i: Integer;
dtc: TDBDatatypeCategoryIndex;
SessionPaths: TStringList;
MenuItem: TMenuItem;
dt: TListNodeType;
Obj: TDBObject;
begin
TranslateComponent(Self);
OUTPUT_FILE := _('Single .sql file');
OUTPUT_FILE_COMPRESSED := _('ZIP compressed .sql file');
OUTPUT_CLIPBOARD := _('Clipboard');
OUTPUT_DIR := _('Directory - one file per object in database subdirectories');
OUTPUT_DB := _('Database');
OUTPUT_SERVER := _('Server')+': ';
DATA_NO := _('No data');
DATA_REPLACE := _('Delete + insert (truncate existing data)');
DATA_INSERT := _('Insert');
DATA_INSERTNEW := _('Insert ignore (do not update existing)');
DATA_UPDATE := _('Replace existing data');
// Restore GUI setup
InheritFont(Font);
Width := AppSettings.ReadInt(asTableToolsWindowWidth);
Height := AppSettings.ReadInt(asTableToolsWindowHeight);
TreeObjects.Width := AppSettings.ReadInt(asTableToolsTreeWidth);
// Find text tab
memoFindText.Text := AppSettings.ReadString(asTableToolsFindText);
comboDatatypes.Items.Add(_('All data types'));
for dtc:=Low(DatatypeCategories) to High(DatatypeCategories) do
comboDatatypes.Items.Add(DatatypeCategories[dtc].Name);
comboDatatypes.ItemIndex := AppSettings.ReadInt(asTableToolsDatatype);
chkCaseSensitive.Checked := AppSettings.ReadBool(asTableToolsFindCaseSensitive);
comboMatchType.ItemIndex := AppSettings.ReadInt(asTableToolsFindMatchType);
// SQL export tab
chkExportDatabasesCreate.Checked := AppSettings.ReadBool(asExportSQLCreateDatabases);
chkExportTablesCreate.Checked := AppSettings.ReadBool(asExportSQLCreateTables);
comboExportData.Items.Text := DATA_NO+CRLF +DATA_REPLACE+CRLF +DATA_INSERT+CRLF +DATA_INSERTNEW+CRLF +DATA_UPDATE;
comboExportData.ItemIndex := AppSettings.ReadInt(asExportSQLDataHow);
updownInsertSize.Position := AppSettings.ReadInt(asExportSQLDataInsertSize);
menuExportAddComments.Checked := AppSettings.ReadBool(asExportSQLAddComments);
menuExportRemoveAutoIncrement.Checked := AppSettings.ReadBool(asExportSQLRemoveAutoIncrement);
// Add hardcoded output options and session names from registry
comboExportOutputType.Items.Text :=
OUTPUT_FILE + CRLF +
OUTPUT_FILE_COMPRESSED + CRLF +
OUTPUT_DIR + CRLF +
OUTPUT_CLIPBOARD + CRLF +
OUTPUT_DB;
SessionPaths := TStringList.Create;
AppSettings.GetSessionPaths('', SessionPaths);
for i:=0 to SessionPaths.Count-1 do begin
if SessionPaths[i] <> Mainform.ActiveConnection.Parameters.SessionPath then
comboExportOutputType.Items.Add(OUTPUT_SERVER+SessionPaths[i]);
end;
SessionPaths.Free;
comboExportOutputTarget.Text := '';
// Various
FixVT(TreeObjects);
FixVT(ResultGrid);
FResults := TObjectList<TStringList>.Create;
PreSelectObjects := TDBObjectList.Create(False);
FModifiedDbs := TStringList.Create;
FFindSeeResultSQL := TStringList.Create;
// Popup menu
Obj := TDBObject.Create(nil);
for dt:=lntTable to lntEvent do begin
Obj.NodeType := dt;
MenuItem := TMenuItem.Create(menuCheckByType);
MenuItem.Caption := _(Obj.ObjType+'s');
MenuItem.ImageIndex := Obj.ImageIndex;
MenuItem.OnClick := CheckAllClick;
MenuItem.Tag := Integer(dt);
menuCheckByType.Add(MenuItem);
end;
Obj.Free;
end;
procedure TfrmTableTools.FormDestroy(Sender: TObject);
begin
// Save GUI setup
AppSettings.WriteInt(asTableToolsWindowWidth, Width );
AppSettings.WriteInt(asTableToolsWindowHeight, Height );
AppSettings.WriteInt(asTableToolsTreeWidth, TreeObjects.Width);
end;
procedure TfrmTableTools.FormShow(Sender: TObject);
var
Node, FirstChecked: PVirtualNode;
idx: Integer;
DBObj: TDBObject;
begin
// When this form is displayed the second time, databases may be deleted or filtered.
// Also, checked nodes must be unchecked and unchecked nodes may need to be checked.
TreeObjects.Clear;
TreeObjects.RootNodeCount := Mainform.DBtree.RootNodeCount;
FObjectSizes := 0;
// Init all objects in active database, so the tree does not just check the db node
// if we want the first child only. See issue #2267.
Node := MainForm.FindDBNode(TreeObjects, MainForm.ActiveConnection, MainForm.ActiveDatabase);
Node := TreeObjects.GetFirstChild(Node);
while Assigned(Node) do
Node := TreeObjects.GetNextSibling(Node);
for DBObj in PreSelectObjects do begin
Node := MainForm.FindDBObjectNode(TreeObjects, DBObj);
if Assigned(Node) then
TreeObjects.CheckState[Node] := csCheckedNormal;
end;
FirstChecked := TreeObjects.GetFirstChecked;
if Assigned(FirstChecked) then
SelectNode(TreeObjects, FirstChecked);
// CHECKSUM available since MySQL 4.1.1
idx := comboOperation.ItemIndex;
if idx = -1 then idx := 0;
comboOperation.Items.CommaText := 'Check,Analyze,Checksum,Optimize,Repair';
if Mainform.ActiveConnection.ServerVersionInt < 40101 then
comboOperation.Items.Text := StringReplace(comboOperation.Items.Text, 'Checksum', 'Checksum ('+_(SUnsupported)+')', [rfReplaceAll]);
comboOperation.ItemIndex := idx;
comboOperation.OnChange(Sender);
// Restore output option. Avoid server preselection to avoid unwanted connects.
// See issue #3411
idx := AppSettings.ReadInt(asExportSQLOutput);
if (idx = -1)
or (idx >= comboExportOutputType.Items.Count)
or StartsStr(OUTPUT_SERVER, comboExportOutputType.Items[idx])
then idx := 0;
comboExportOutputType.ItemIndex := idx;
comboExportOutputType.OnChange(Sender);
comboBulkTableEditDatabase.Items.Text := Mainform.ActiveConnection.AllDatabases.Text;
if comboBulkTableEditDatabase.Items.Count > 0 then
comboBulkTableEditDatabase.ItemIndex := 0;
comboBulkTableEditEngine.Items := MainForm.ActiveConnection.TableEngines;
if comboBulkTableEditEngine.Items.Count > 0 then
comboBulkTableEditEngine.ItemIndex := comboBulkTableEditEngine.Items.IndexOf(MainForm.ActiveConnection.TableEngineDefault);
comboBulkTableEditCollation.Items := MainForm.ActiveConnection.CollationList;
if comboBulkTableEditCollation.Items.Count > 0 then
comboBulkTableEditCollation.ItemIndex := 0;
comboBulkTableEditCharset.Items := MainForm.ActiveConnection.CharsetList;
if comboBulkTableEditCharset.Items.Count > 0 then
comboBulkTableEditCharset.ItemIndex := 0;
ValidateControls(Sender);
end;
procedure TfrmTableTools.FormClose(Sender: TObject; var Action: TCloseAction);
begin
// Auto close temorary connection
if Assigned(FTargetConnection) then
FreeAndNil(FTargetConnection);
Action := caFree;
end;
procedure TfrmTableTools.SaveSettings(Sender: TObject);
var
i: Integer;
Items: TStringList;
begin
case ToolMode of
tmFind: begin
AppSettings.WriteString(asTableToolsFindText, memoFindText.Text);
AppSettings.WriteInt(asTableToolsDatatype, comboDatatypes.ItemIndex);
AppSettings.WriteBool(asTableToolsFindCaseSensitive, chkCaseSensitive.Checked);
AppSettings.WriteInt(asTableToolsFindMatchType, comboMatchType.ItemIndex);
end;
tmSQLExport: begin
AppSettings.WriteBool(asExportSQLCreateDatabases, chkExportDatabasesCreate.Checked);
AppSettings.WriteBool(asExportSQLCreateTables, chkExportTablesCreate.Checked);
AppSettings.WriteInt(asExportSQLDataHow, comboExportData.ItemIndex);
if comboExportData.ItemIndex > 0 then
AppSettings.WriteInt(asExportSQLDataInsertSize, updownInsertSize.Position);
AppSettings.WriteBool(asExportSQLAddComments, menuExportAddComments.Checked);
AppSettings.WriteBool(asExportSQLRemoveAutoIncrement, menuExportRemoveAutoIncrement.Checked);
if not StartsStr(OUTPUT_SERVER, comboExportOutputType.Text) then
AppSettings.WriteInt(asExportSQLOutput, comboExportOutputType.ItemIndex);
// Remove duplicates from recent file pulldown
if (comboExportOutputType.Text = OUTPUT_FILE)
or (comboExportOutputType.Text = OUTPUT_FILE_COMPRESSED)
or (comboExportOutputType.Text = OUTPUT_DIR)
then begin
Items := TStringList.Create;
Items.Assign(comboExportOutputTarget.Items);
Items.Insert(0, comboExportOutputTarget.Text);
for i:=Items.Count-1 downto 1 do begin
if Items[i] = comboExportOutputTarget.Text then
Items.Delete(i);
end;
comboExportOutputTarget.Items.Assign(Items);
Items.Free;
end;
if comboExportOutputType.Text = OUTPUT_FILE then begin
AppSettings.WriteString(asExportSQLFilenames, comboExportOutputTarget.Items.Text);
end else if comboExportOutputType.Text = OUTPUT_FILE_COMPRESSED then begin
AppSettings.WriteString(asExportZIPFilenames, comboExportOutputTarget.Items.Text);
end else if comboExportOutputType.Text = OUTPUT_DIR then begin
AppSettings.WriteString(asExportSQLDirectories, comboExportOutputTarget.Items.Text);
end else if comboExportOutputType.Text = OUTPUT_DB then begin
AppSettings.WriteString(asExportSQLDatabase, comboExportOutputTarget.Text);
end else if copy(comboExportOutputType.Text, 1, Length(OUTPUT_SERVER)) = OUTPUT_SERVER then begin
AppSettings.WriteString(asExportSQLServerDatabase, comboExportOutputTarget.Text);
end;
end;
end;
end;
procedure TfrmTableTools.ValidateControls(Sender: TObject);
var
SomeChecked, OptionChecked: Boolean;
op: String;
i: Integer;
begin
SomeChecked := TreeObjects.CheckedCount > 0;
btnSeeResults.Visible := tabsTools.ActivePage = tabFind;
lblCheckedSize.Caption := f_('Selected objects size: %s', [FormatByteNumber(FObjectSizes)]);
if tabsTools.ActivePage = tabMaintenance then begin
btnExecute.Caption := _('Execute');
btnExecute.Enabled := (Pos(_(SUnsupported), comboOperation.Text) = 0) and SomeChecked;
// Only enable available options
op := LowerCase(comboOperation.Text);
chkQuick.Enabled := (op = 'check') or (op = 'checksum') or (op = 'repair');
chkFast.Enabled := op = 'check';
chkMedium.Enabled := op = 'check';
chkExtended.Enabled := (op = 'check') or (op = 'checksum') or (op = 'repair');
chkChanged.Enabled := op = 'check';
chkUseFrm.Enabled := op = 'repair';
chkForUpgrade.Enabled := op = 'check';
// CHECKSUM's options are mutually exclusive
if comboOperation.Text = 'Checksum' then begin
if (Sender = chkExtended) and chkExtended.Checked then chkQuick.Checked := False
else if chkQuick.Checked then chkExtended.Checked := False;
end;
end else if tabsTools.ActivePage = tabFind then begin
btnExecute.Caption := _('Find');
btnExecute.Enabled := SomeChecked and (memoFindText.Text <> '');
// Enable "See results" button if there were results
btnSeeResults.Enabled := False;
if Assigned(FResults) then for i:=0 to FResults.Count-1 do begin
if MakeInt(FResults[i][2]) > 0 then begin
btnSeeResults.Enabled := True;
break;
end;
end;
end else if tabsTools.ActivePage = tabSQLExport then begin
btnExecute.Caption := _('Export');
btnExecute.Enabled := SomeChecked and ((comboExportOutputTarget.Text <> '') or (not comboExportOutputTarget.Enabled));
lblInsertSize.Enabled := comboExportData.ItemIndex > 0;
editInsertSize.Enabled := lblInsertSize.Enabled;
updownInsertSize.Enabled := lblInsertSize.Enabled;
lblInsertSizeUnit.Enabled := lblInsertSize.Enabled;
end else if tabsTools.ActivePage = tabBulkTableEdit then begin
btnExecute.Caption := _('Update');
chkBulkTableEditCollation.Enabled := MainForm.ActiveConnection.IsUnicode;
chkBulkTableEditCharset.Enabled := MainForm.ActiveConnection.IsUnicode;
OptionChecked := chkBulkTableEditDatabase.Checked or chkBulkTableEditEngine.Checked or chkBulkTableEditCollation.Checked
or chkBulkTableEditCharset.Checked or chkBulkTableEditResetAutoinc.Checked;
btnExecute.Enabled := SomeChecked and OptionChecked;
end;
end;
procedure TfrmTableTools.TreeObjectsBeforeCellPaint(Sender: TBaseVirtualTree; TargetCanvas: TCanvas;
Node: PVirtualNode; Column: TColumnIndex; CellPaintMode: TVTCellPaintMode; CellRect: TRect;
var ContentRect: TRect);
begin
MainForm.DBtreeBeforeCellPaint(Sender, TargetCanvas, Node, Column, CellPaintMode, CellRect, ContentRect);
end;
procedure TfrmTableTools.TreeObjectsChange(Sender: TBaseVirtualTree; Node: PVirtualNode);
begin
Mainform.DBtreeChange(Sender, Node);
end;
procedure TfrmTableTools.TreeObjectsChecked(Sender: TBaseVirtualTree; Node: PVirtualNode);
var
Obj: PDBObject;
ObjSize: Int64;
begin
// Track sum of checked objects size
Obj := Sender.GetNodeData(Node);
ObjSize := Max(Obj.Size, 0);
if Node.CheckState in CheckedStates then
Inc(FObjectSizes, ObjSize)
else
Dec(FObjectSizes, ObjSize);
ValidateControls(Sender);
end;
procedure TfrmTableTools.TreeObjectsChecking(Sender: TBaseVirtualTree; Node: PVirtualNode;
var NewState: TCheckState; var Allowed: Boolean);
var
n: PVirtualNode;
begin
// Ensure to also toggle check state of not yet initialized nodes
Allowed := True;
// Weird fix: Just iterate through all sub nodes for implicit initialization. Without this
// loop a checkbox click on a parent node would only auto-check its visible children.
n := Sender.GetFirstChild(Node);
while Assigned(n) do
n := Sender.GetNextSibling(n);
end;
procedure TfrmTableTools.TreeObjectsExpanded(Sender: TBaseVirtualTree;
Node: PVirtualNode);
begin
// Auto-resizes the 2nd/"size" column
TreeObjectsChange(Sender, Node);
end;
procedure TfrmTableTools.TreeObjectsGetImageIndex(Sender: TBaseVirtualTree; Node: PVirtualNode;
Kind: TVTImageKind; Column: TColumnIndex; var Ghosted: Boolean; var ImageIndex: Integer);
begin
Mainform.DBtreeGetImageIndex(Sender, Node, Kind, Column, Ghosted, ImageIndex);
end;
procedure TfrmTableTools.TreeObjectsGetNodeDataSize(Sender: TBaseVirtualTree; var NodeDataSize: Integer);
begin
MainForm.DBtreeGetNodeDataSize(Sender, NodeDataSize);
end;
procedure TfrmTableTools.TreeObjectsGetText(Sender: TBaseVirtualTree; Node: PVirtualNode;
Column: TColumnIndex; TextType: TVSTTextType; var CellText: String);
begin
Mainform.DBtreeGetText(Sender, Node, Column, TextType, CellText);
end;
procedure TfrmTableTools.TreeObjectsInitChildren(Sender: TBaseVirtualTree; Node: PVirtualNode;
var ChildCount: Cardinal);
begin
Mainform.DBtreeInitChildren(Sender, Node, ChildCount);
end;
procedure TfrmTableTools.TreeObjectsInitNode(Sender: TBaseVirtualTree; ParentNode, Node: PVirtualNode;
var InitialStates: TVirtualNodeInitStates);
begin
// Attach a checkbox to all nodes
Mainform.DBtreeInitNode(Sender, ParentNode, Node, InitialStates);
Node.CheckType := ctTriStateCheckBox;
Node.CheckState := csUncheckedNormal;
end;
procedure TfrmTableTools.TreeObjectsPaintText(Sender: TBaseVirtualTree; const TargetCanvas: TCanvas;
Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType);
begin
Mainform.DBtreePaintText(Sender, TargetCanvas, Node, Column, TextType);
end;
procedure TfrmTableTools.btnHelpMaintenanceClick(Sender: TObject);
begin
Mainform.CallSQLHelpWithKeyword(UpperCase(comboOperation.Text) + ' TABLE');
end;
procedure TfrmTableTools.btnHelpSQLExportClick(Sender: TObject);
begin
Help(Sender, 'sqlexport');
end;
procedure TfrmTableTools.Execute(Sender: TObject);
var
SessionNode, DBNode: PVirtualNode;
CheckedObjects, Triggers, Views: TDBObjectList;
DBObj: TDBObject;
i: Integer;
Conn: TDBConnection;
FileName, FileNameZip, FileNameInZip: TFileName;
Zip: TZipFile;
StartTime: Cardinal;
LogRow: TStringlist;
procedure ProcessNode(DBObj: TDBObject);
begin
try
case FToolMode of
tmMaintenance: DoMaintenance(DBObj);
tmFind: DoFind(DBObj);
tmSQLExport: DoExport(DBObj);
tmBulkTableEdit: DoBulkTableEdit(DBObj);
end;
except
on E:EDatabaseError do begin
// The above SQL can easily throw an exception, e.g. if a table is corrupted.
// In such cases we create a dummy row, including the error message
AddNotes(DBObj, 'error', E.Message)
end;
on E:EFCreateError do begin
// Occurs when export output file can not be created
ErrorDialog(E.Message);
FCancelled := True;
end;
end;
end;
procedure SetCheckedObjects(DBNode: PVirtualNode);
var
Child, GrandChild: PVirtualNode;
ChildObj, GrandChildObj: PDBObject;
begin
CheckedObjects.Clear;
Child := TreeObjects.GetFirstChild(DBNode);
while Assigned(Child) do begin
if Child.CheckState in CheckedStates then begin
ChildObj := TreeObjects.GetNodeData(Child);
case ChildObj.NodeType of
lntGroup: begin
GrandChild := TreeObjects.GetFirstChild(Child);
while Assigned(GrandChild) do begin
if GrandChild.CheckState in CheckedStates then begin
GrandChildObj := TreeObjects.GetNodeData(GrandChild);
CheckedObjects.Add(GrandChildObj^);
end;
GrandChild := TreeObjects.GetNextSibling(GrandChild);
end;
end
else begin
CheckedObjects.Add(ChildObj^);
end;
end;
end;
Child := TreeObjects.GetNextSibling(Child);
end;
end;
begin
Screen.Cursor := crHourGlass;
// Disable critical controls so ProcessMessages is unable to do things while export is in progress
btnExecute.Enabled := False;
btnCloseOrCancel.Caption := _('Cancel');
btnCloseOrCancel.ModalResult := mrNone;
tabsTools.Enabled := False;
treeObjects.Enabled := False;
if tabsTools.ActivePage = tabMaintenance then
FToolMode := tmMaintenance
else if tabsTools.ActivePage = tabFind then
FToolMode := tmFind
else if tabsTools.ActivePage = tabSQLExport then
FToolMode := tmSQLExport
else if tabsTools.ActivePage = tabBulkTableEdit then
FToolMode := tmBulkTableEdit;
ResultGrid.Clear;
FResults.Clear;
FFindSeeResultSQL.Clear;
CheckedObjects := TDBObjectList.Create(False);
Triggers := TDBObjectList.Create(False); // False, so we can .Free that object afterwards without loosing the contained objects
Views := TDBObjectList.Create(False);
FHeaderCreated := False;
FCancelled := False;
FObjectSizesDone := 0;
FObjectSizesDoneExact := 0;
MainForm.EnableProgress(100);
SessionNode := TreeObjects.GetFirstChild(nil);
while Assigned(SessionNode) do begin
DBNode := TreeObjects.GetFirstChild(SessionNode);
while Assigned(DBNode) do begin
if not (DBNode.CheckState in [csUncheckedNormal, csUncheckedPressed]) then begin
Triggers.Clear;
Views.Clear;
FSecondExportPass := False;
SetCheckedObjects(DBNode);
for DBObj in CheckedObjects do begin
// Triggers have to be exported at the very end
if (FToolMode = tmSQLExport) and (DBObj.NodeType = lntTrigger) then
Triggers.Add(DBObj)
else begin
ProcessNode(DBObj);
FObjectSizesDone := FObjectSizesDone + Max(DBObj.Size, 0);
FObjectSizesDoneExact := FObjectSizesDone;
if (FToolMode = tmSQLExport) and (DBObj.NodeType = lntView) then
Views.Add(DBObj);
end;
// File creation exception occurred or user clicked cancel button
if FCancelled then Break;
end; // End of db object node loop in db
// Special block for late created triggers in export mode
for i:=0 to Triggers.Count-1 do begin
ProcessNode(Triggers[i]);
if FCancelled then Break;
end;
// Special block for exporting final view structure
FSecondExportPass := True;
for i:=0 to Views.Count-1 do begin
ProcessNode(Views[i]);
if FCancelled then Break;
end;
end;
if FCancelled then Break;
DBNode := TreeObjects.GetNextSibling(DBNode);
end; // End of db item loop
if FCancelled then Break;
SessionNode := TreeObjects.GetNextSibling(SessionNode);
end;
Conn := Mainform.ActiveConnection;
if Assigned(ExportStream) then begin
Output(EXPORT_FILE_FOOTER, False, True, False, False, False);
Output('/*!40101 SET SQL_MODE=IFNULL(@OLD_SQL_MODE, '''') */', True, False, False, True, True);
Output('/*!40014 SET FOREIGN_KEY_CHECKS=IF(@OLD_FOREIGN_KEY_CHECKS IS NULL, 1, @OLD_FOREIGN_KEY_CHECKS) */', True, False, False, True, True);
if comboExportOutputType.Text = OUTPUT_CLIPBOARD then
StreamToClipboard(ExportStream, nil, false);
if comboExportOutputType.Text = OUTPUT_FILE_COMPRESSED then
FileName := TFileStream(ExportStream).FileName;
FreeAndNil(ExportStream);
if comboExportOutputType.Text = OUTPUT_FILE_COMPRESSED then begin
AddNotes('', '', _('Compressing')+'...', '');
StartTime := GetTickCount;
FileNameZip := FExportFileName;
if FileExists(FileNameZip) then
DeleteFile(FileNameZip);
Zip := TZipFile.Create;
Zip.Open(FileNameZip, zmWrite);
FileNameInZip := ExtractFileName(ChangeFileExt(FileNameZip, '.sql'));
Zip.Add(FileName, FileNameInZip);
Zip.Close;
DeleteFile(FileName);
LogRow := FResults.Last;
LogRow[2] := _('Compressing done.');
LogRow[3] := FormatTimeNumber((GetTickCount-StartTime) DIV 1000, True);
ResultGrid.Repaint;
end;
// Activate ansi mode or whatever again, locally
Conn.Query('/*!40101 SET SQL_MODE=IFNULL(@OLD_LOCAL_SQL_MODE, '''') */');
end;
ExportLastDatabase := '';
for i:=0 to FModifiedDbs.Count-1 do begin
Conn.ClearDbObjects(FModifiedDbs[i]);
DBNode := MainForm.FindDBNode(TreeObjects, Conn, FModifiedDbs[i]);
TreeObjects.ReinitNode(DBNode, False);
TreeObjects.ReinitChildren(DBNode, False)
end;
FModifiedDbs.Clear;
btnCloseOrCancel.Caption := _('Close');
btnCloseOrCancel.ModalResult := mrCancel;
MainForm.DisableProgress;
tabsTools.Enabled := True;
treeObjects.Enabled := True;
ValidateControls(Sender);
SaveSettings(Sender);
Screen.Cursor := crDefault;
end;
procedure TfrmTableTools.DoMaintenance(DBObj: TDBObject);
var
SQL: String;
begin
if not (DBObj.NodeType in [lntTable, lntView]) then begin
AddNotes(DBObj, STRSKIPPED+'a '+LowerCase(DBObj.ObjType)+' cannot be maintained.', '');
Exit;
end;
SQL := UpperCase(comboOperation.Text) + ' TABLE ' + DBObj.QuotedDatabase + '.' + DBObj.QuotedName;
if chkQuick.Enabled and chkQuick.Checked then SQL := SQL + ' QUICK';
if chkFast.Enabled and chkFast.Checked then SQL := SQL + ' FAST';
if chkMedium.Enabled and chkMedium.Checked then SQL := SQL + ' MEDIUM';
if chkExtended.Enabled and chkExtended.Checked then SQL := SQL + ' EXTENDED';
if chkChanged.Enabled and chkChanged.Checked then SQL := SQL + ' CHANGED';
if chkUseFrm.Enabled and chkUseFrm.Checked then SQL := SQL + ' USE_FRM';
if chkForUpgrade.Enabled and chkForUpgrade.Checked then SQL := SQL + ' FOR UPGRADE';
AddResults(SQL, DBObj.Connection);
end;
procedure TfrmTableTools.DoFind(DBObj: TDBObject);
var
Columns: TTableColumnList;
Col: TTableColumn;
SQL, Dummy, Column, RoutineDefinitionColumn, RoutineSchemaColumn, FindText, FindTextJokers: String;
begin
FFindSeeResultSQL.Add('');
FindText := memoFindText.Text;
case comboMatchType.ItemIndex of
0: FindTextJokers := '%'+FindText+'%';
1: FindTextJokers := FindText;
2: FindTextJokers := '%'+FindText;
3: FindTextJokers := FindText+'%';
end;
RoutineDefinitionColumn := DBObj.Connection.QuoteIdent('routine_definition');
if not chkCaseSensitive.Checked then begin
FindText := LowerCase(FindText);
FindTextJokers := LowerCase(FindTextJokers);
RoutineDefinitionColumn := 'LOWER('+RoutineDefinitionColumn+')';
end;
RoutineSchemaColumn := 'routine_schema';
if DBObj.Connection.Parameters.IsMSSQL then
RoutineSchemaColumn := 'routine_catalog';
Columns := TTableColumnList.Create(True);
case DBObj.NodeType of
lntTable: DBObj.Connection.ParseTableStructure(DBObj.CreateCode, Columns, nil, nil);
lntView: DBObj.Connection.ParseViewStructure(DBObj.CreateCode, DBObj, Columns, Dummy, Dummy, Dummy, Dummy, Dummy);
lntProcedure, lntFunction: ;
// TODO: Triggers + Events
else AddNotes(DBObj, STRSKIPPED+'a '+LowerCase(DBObj.ObjType)+' does not contain rows.', '');
end;
case DBObj.NodeType of
lntTable, lntView: begin
if Columns.Count > 0 then begin
SQL := '';
for Col in Columns do begin
Column := DBObj.Connection.QuoteIdent(Col.Name);
if (comboDatatypes.ItemIndex = 0) or (Integer(Col.DataType.Category) = comboDatatypes.ItemIndex-1) then begin
if (Col.DataType.Category in [dtcInteger, dtcReal]) and (comboMatchType.ItemIndex=1) then begin
SQL := SQL + Column + '=' + UnformatNumber(FindText) + ' OR ';
end else if chkCaseSensitive.Checked then begin
case DBObj.Connection.Parameters.NetTypeGroup of
ngMySQL:
SQL := SQL + Column + ' LIKE BINARY ' + esc(FindTextJokers) + ' OR ';
ngMSSQL:
SQL := SQL + Column+' LIKE ' + esc(FindTextJokers) + ' COLLATE SQL_Latin1_General_CP1_CS_AS OR ';
ngPgSQL:
SQL := SQL + 'CAST(' + Column + ' AS TEXT) LIKE ' + esc(FindTextJokers) + ' OR ';
end;
end else begin
Column := 'LOWER('+Column+')';
case DBObj.Connection.Parameters.NetTypeGroup of
ngMySQL:
SQL := SQL + 'CONVERT('+Column+' USING '+DBObj.Connection.CharacterSet+') LIKE ' + esc(FindTextJokers) + ' OR ';
ngMSSQL:
SQL := SQL + Column+' LIKE ' + esc(FindTextJokers) + ' OR ';
ngPgSQL:
SQL := SQL + 'CAST('+Column+' AS TEXT) LIKE ' + esc(FindTextJokers) + ' OR ';
end;
end;
end;
end;
if SQL <> '' then begin
Delete(SQL, Length(SQL)-3, 3);
FFindSeeResultSQL[FFindSeeResultSQL.Count-1] := 'SELECT * FROM '+DBObj.QuotedDatabase+'.'+DBObj.QuotedName+' WHERE ' + SQL;
case DBObj.Connection.Parameters.NetTypeGroup of
ngMySQL, ngPgSQL:
SQL := 'SELECT '''+DBObj.Database+''' AS '+DBObj.Connection.QuoteIdent('Database')+', '''+DBObj.Name+''' AS '+DBObj.Connection.QuoteIdent('Table')+', COUNT(*) AS '+DBObj.Connection.QuoteIdent('Found rows')+', '
+ 'CONCAT(ROUND(100 / '+IntToStr(Max(DBObj.Rows,1))+' * COUNT(*), 1), ''%'') AS '+DBObj.Connection.QuoteIdent('Relevance')+' FROM '+DBObj.QuotedDatabase+'.'+DBObj.QuotedName+' WHERE '
+ SQL;
ngMSSQL:
SQL := 'SELECT '''+DBObj.Database+''' AS '+DBObj.Connection.QuoteIdent('Database')+', '''+DBObj.Name+''' AS '+DBObj.Connection.QuoteIdent('Table')+', COUNT(*) AS '+DBObj.Connection.QuoteIdent('Found rows')+', '
+ 'CONVERT(VARCHAR(10), ROUND(100 / '+IntToStr(Max(DBObj.Rows,1))+' * COUNT(*), 1)) + ''%'' AS '+DBObj.Connection.QuoteIdent('Relevance')+' FROM '+DBObj.QuotedDatabase+'.'+DBObj.QuotedName+' WHERE '
+ SQL;
end;
AddResults(SQL, DBObj.Connection);
end else
AddNotes(DBObj, f_('%s%s doesn''t have columns of selected type (%s).', [STRSKIPPED, DBObj.ObjType, comboDatatypes.Text]), '');
end;
end;
lntProcedure, lntFunction: begin
SQL := 'SELECT '+
esc(DBObj.Database)+' AS '+DBObj.Connection.QuoteIdent('Database')+', '+
esc(DBObj.Name)+' AS '+DBObj.Connection.QuoteIdent('Table')+', '+
DBObj.Connection.GetSQLSpecifity(spFuncCeil)+'(('+DBObj.Connection.GetSQLSpecifity(spFuncLength)+'('+RoutineDefinitionColumn+') - '+DBObj.Connection.GetSQLSpecifity(spFuncLength)+'(REPLACE('+RoutineDefinitionColumn+', '+esc(FindText)+', '+esc('')+'))) / '+DBObj.Connection.GetSQLSpecifity(spFuncLength)+'('+esc(FindText)+')) AS '+DBObj.Connection.QuoteIdent('Found rows')+', '+
'0 AS '+DBObj.Connection.QuoteIdent('Relevance')+
'FROM '+DBObj.Connection.QuoteIdent('information_schema')+'.'+DBObj.Connection.QuoteIdent('routines')+' '+
'WHERE '+DBObj.Connection.QuoteIdent(RoutineSchemaColumn)+'='+esc(DBObj.Database)+' AND '+DBObj.Connection.QuoteIdent('routine_name')+'='+esc(DBObj.Name);
AddResults(SQL, DBObj.Connection);
end;
end;
Columns.Free;
end;
procedure TfrmTableTools.btnSeeResultsClick(Sender: TObject);
var
SQL: String;
i: Integer;
Tab: TQueryTab;
begin
// "See results" clicked - auto create new query tab, and execute a batch of SELECT queries
SQL := '';
for i:=0 to FResults.Count-1 do begin
if MakeInt(FResults[i][2]) > 0 then begin
SQL := SQL + FFindSeeResultSQL[i] + ';' + CRLF;
end;
end;
MainForm.actNewQueryTab.Execute;
Tab := MainForm.QueryTabs[MainForm.QueryTabs.Count-1];
Tab.Memo.Text := SQL;
Tab.TabSheet.Show;
MainForm.actExecuteQueryExecute(Sender);
end;
procedure TfrmTableTools.AddResults(SQL: String; Connection: TDBConnection);
var
i: Integer;
Row: TStringList;
Results: TDBQuery;
Value: String;
begin
// Execute query and append results into grid
Results := Connection.GetResults(SQL);
if Results = nil then
Exit;
SetupResultGrid(Results);
Results.First;
while not Results.Eof do begin
Row := TStringList.Create;
for i:=0 to Results.ColumnCount-1 do begin
Value := Results.Col(i);
if Results.DataType(i).Category = dtcInteger then begin
if MakeFloat(Value) >= 0 then
Row.Add(FormatNumber(Value))
else
Row.Add('');
end else
Row.Add(Value);
end;
FResults.Add(Row);
Results.Next;
end;
Results.Free;
UpdateResultGrid;
end;
procedure TfrmTableTools.AddNotes(Col1, Col2, Col3, Col4: String);
var
Row: TStringList;
begin
// Adds a row with non SQL results
SetupResultGrid;
Row := TStringList.Create;
Row.Add(Col1);
Row.Add(Col2);
Row.Add(Col3);
Row.Add(Col4);
FResults.Add(Row);
UpdateResultGrid;
end;
procedure TfrmTableTools.AddNotes(DBObject: TDBObject; Msg1, Msg2: String);
begin
AddNotes(DBObject.Database, DBObject.Name, Msg1, Msg2);
end;
procedure TfrmTableTools.SetupResultGrid(Results: TDBQuery=nil);
var
ColCount, i: Integer;
Col: TVirtualTreeColumn;
begin
if Assigned(Results) then begin
ColCount := Results.ColumnCount;
ResultGrid.Header.Options := ResultGrid.Header.Options + [hoVisible];
end else begin
ColCount := 4;
// Remove column headers if this is the first row
if FResults.Count = 0 then
ResultGrid.Header.Options := ResultGrid.Header.Options - [hoVisible];
end;
// Add missing columns
for i:=ResultGrid.Header.Columns.Count to ColCount-1 do begin
Col := ResultGrid.Header.Columns.Add;
Col.Width := 130;
end;
// Remove superfluous columns
for i:=ResultGrid.Header.Columns.Count-1 downto ColCount do
ResultGrid.Header.Columns[i].Free;