forked from motaz/turbobird
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquerywindow.pas
2137 lines (1819 loc) · 55.1 KB
/
querywindow.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 QueryWindow;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, IBConnection, db, sqldb, FileUtil, LResources, Forms,
Controls, Graphics, Dialogs, ExtCtrls, PairSplitter, StdCtrls, Buttons,
DBGrids, Menus, ComCtrls, SynEdit, SynHighlighterSQL, Reg,
SynEditTypes, SynCompletion, Clipbrd, grids, DbCtrls, types, LCLType,
modsqlscript, dbugintf, turbocommon, variants, strutils;
type
TQueryTypes = (
qtUnknown=0,
qtSelectable=1,
qtExecute=2,
qtScript=3);
TQueryActions = (
qaCommit,
qaCommitRet,
qaRollBack,
qaRollbackRet,
qaOpen,
qaDDL,
qaExec );
{ TQueryThread }
TQueryThread = class(TThread)
private
FSQLQuery: TSQLQuery;
FTrans: TSQLTransaction;
FConnection: TIBConnection;
public
Error: Boolean;
ErrorMsg: string;
fTerminated: Boolean;
fType: TQueryActions;
fStatement: string;
property Query: TSQLQuery read FSQLQuery write FSQLQuery;
property Trans: TSQLTransaction read FTrans write FTrans;
property Connection: TIBConnection read FConnection write FConnection;
property Statement: String read fStatement write fStatement;
procedure DoJob;
procedure Execute; override;
constructor Create(aType: TQueryActions);
end;
{ TfmQueryWindow }
TfmQueryWindow = class(TForm)
bbClose: TBitBtn;
cxAutoCommit: TCheckBox;
FindDialog1: TFindDialog;
imTools: TImageList;
imTabs: TImageList;
lmCloseTab: TMenuItem;
lmCopy: TMenuItem;
lmPaste: TMenuItem;
lmSelectAll: TMenuItem;
lmUndo: TMenuItem;
MainMenu1: TMainMenu;
MenuItem1: TMenuItem;
MenuItem10: TMenuItem;
lmCut: TMenuItem;
lmExport: TMenuItem;
lmCommaDelimited: TMenuItem;
lmHTML: TMenuItem;
lmRedo: TMenuItem;
MenuItem2: TMenuItem;
lmFind: TMenuItem;
lmFindAgain: TMenuItem;
MenuItem3: TMenuItem;
lmCopyCell: TMenuItem;
lmExportAsComma: TMenuItem;
lmExportAsHTML: TMenuItem;
lmCopyAll: TMenuItem;
MenuItem5: TMenuItem;
lmRun: TMenuItem;
lmRunSelect: TMenuItem;
lmRunExec: TMenuItem;
lmRunScript: TMenuItem;
OpenDialog1: TOpenDialog;
pgOutputPageCtl: TPageControl;
Panel1: TPanel;
pnlOutputPanel: TPanel;
pmTab: TPopupMenu;
pmMemo: TPopupMenu;
pmGrid: TPopupMenu;
SaveDialog1: TSaveDialog;
Splitter1: TSplitter;
meQuery: TSynEdit;
SynCompletion1: TSynCompletion;
SynSQLSyn1: TSynSQLSyn;
ToolBar1: TToolBar;
tbNew: TToolButton;
tbOpen: TToolButton;
tbSave: TToolButton;
tbRun: TToolButton;
tbCommit: TToolButton;
tbRollback: TToolButton;
tbCommitRetaining: TToolButton;
tbRollbackRetaining: TToolButton;
ToolButton1: TToolButton;
ToolButton2: TToolButton;
ToolButton3: TToolButton;
tbHistory: TToolButton;
ToolButton5: TToolButton;
tbMenu: TToolButton;
procedure bbRunClick(Sender: TObject);
procedure DBGrid1DblClick(Sender: TObject);
procedure DBGridTitleClick(column: TColumn);
procedure FindDialog1Find(Sender: TObject);
procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure FormShow(Sender: TObject);
procedure lmCloseTabClick(Sender: TObject);
procedure lmCommaDelimitedClick(Sender: TObject);
procedure lmCopyAllClick(Sender: TObject);
procedure lmCopyCellClick(Sender: TObject);
procedure lmCopyClick(Sender: TObject);
procedure lmCutClick(Sender: TObject);
procedure lmExportAsCommaClick(Sender: TObject);
procedure lmExportAsHTMLClick(Sender: TObject);
procedure lmHTMLClick(Sender: TObject);
procedure lmPasteClick(Sender: TObject);
procedure lmRedoClick(Sender: TObject);
procedure lmRunClick(Sender: TObject);
procedure lmRunExecClick(Sender: TObject);
procedure lmRunScriptClick(Sender: TObject);
procedure lmRunSelectClick(Sender: TObject);
procedure lmSelectAllClick(Sender: TObject);
procedure lmUndoClick(Sender: TObject);
procedure lmFindClick(Sender: TObject);
procedure lmFindAgainClick(Sender: TObject);
procedure meQueryKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure SQLScript1Exception(Sender: TObject; Statement: TStrings;
TheException: Exception; var Continue: boolean);
procedure SynCompletion1CodeCompletion(var Value: string;
SourceValue: string; var SourceStart, SourceEnd: TPoint;
KeyChar: TUTF8Char; Shift: TShiftState);
procedure tbCloseClick(Sender: TObject);
procedure tbCommitClick(Sender: TObject);
procedure tbCommitRetainingClick(Sender: TObject);
procedure tbHistoryClick(Sender: TObject);
procedure tbMenuClick(Sender: TObject);
procedure tbNewClick(Sender: TObject);
procedure tbOpenClick(Sender: TObject);
procedure tbRollbackClick(Sender: TObject);
procedure tbRollbackRetainingClick(Sender: TObject);
procedure tbRunClick(Sender: TObject);
procedure tbSaveClick(Sender: TObject);
private
{ private declarations }
FDBIndex: Integer; // Index of selected registered database
FRegRec: TRegisteredDatabase;
FOptions: set of TSynSearchOption;
FIBConnection: TIBConnection;
FSQLTrans: TSQLTransaction;
FCanceled: Boolean;
FStartLine: Integer;
FQuery: TStringList; //query text
FOrigQueryType: TQueryTypes;
FFinished: Boolean;
FQT: TQueryThread;
FQueryPart: string;
FTab: TTabSheet;
FResultMemo: TMemo;
FSQLQuery: TSQLQuery;
FSQLScript: TModSQLScript;
// Text for caption
FAText: string;
FModifyCount: Integer;
FCounter: Integer;
// Makes commit button in current tabsheet visible
procedure EnableCommitButton;
procedure ExecuteQuery;
function GetNewTabNum: string;
// Gets TSQLQuery of current result tabsheet - only if it is a select query
function GetCurrentSelectQuery: TSQLQuery;
// Gets both querytype and whether SQL is DML or DDL
// Investigates QueryList[LookAtIndex] to find out
function GetQuerySQLType(QueryList: TStringList; var LookAtIndex: Integer;
var IsDDL: Boolean): TQueryTypes;
procedure NewCommitButton(const Pan: TPanel; var ATab: TTabSheet);
procedure RemoveComments(QueryList: TStringList; StartLine: Integer;
var RealStartLine: Integer);
procedure RemoveAllSingleLineComments(QueryList: TStringList);
procedure RemoveEmptyLines(QueryList: TStringList;
var SecondRealStart: Integer; const RealStartLine: Integer);
procedure ApplyClick(Sender: TObject);
procedure EnableApplyButton;
function GetTableName(SQLText: string): string;
procedure CommitResultClick(Sender: TObject);
protected
// This procedure will receive the events that are logged by the connection:
procedure GetLogEvent(Sender: TSQLConnection; EventType: TDBEventType; Const Msg : String);
public
OnCommit: TNotifyEvent;
procedure Init(dbIndex: Integer);
function GetQueryType(AQuery: string): TQueryTypes;
// Get query text from GUI/memo into
// QueryContents
function GetQuery(QueryContents: tstrings): boolean;
function CreateResultTab(QueryType: TQueryTypes; var aSqlQuery: TSQLQuery; var aSQLScript: TModSQLScript;
var meResult: TMemo; AdditionalTitle: string = ''): TTabSheet;
// Runs SQL script; returns result
function ExecuteScript(Script: string): Boolean;
// Create a new Apply button in the specified panel
procedure NewApplyButton(var Pan: TPanel; var ATab: TTabSheet);
// Returns whether query is DDL or DML
function GetSQLType(Query: string; var Command: string): string;
// Tries to split up text into separate queries
function GetSQLSegment(QueryList: TStringList; StartLine: Integer;
var QueryType: TQueryTypes; var EndLine: Integer;
var SQLSegment: string; var IsDDL: Boolean): Boolean;
procedure QueryAfterPost(DataSet: TDataSet);
procedure QueryAfterScroll(DataSet: TDataSet);
// Run query; use aQueryType to force running as e.g. script or open query
procedure CallExecuteQuery(aQueryType: TQueryTypes);
procedure SortSynCompletion;
procedure ThreadTerminated(Sender: TObject);
procedure EnableButtons;
{ public declarations }
end;
var
fmQueryWindow: TfmQueryWindow;
implementation
uses main, SQLHistory;
{ TfmQueryWindow }
{ NewCommitButton: Create commit button for editable query result }
procedure TfmQueryWindow.NewCommitButton(const Pan: TPanel; var ATab: TTabSheet);
var
Commit: TBitBtn;
begin
Commit:= TBitBtn.Create(self);
Commit.Parent:= Pan;
Commit.Caption:= 'Commit'; //don't change this; code looks for this exact caption
Commit.Left:= 400;
Commit.Visible:= False;
Commit.OnClick:= @CommitResultClick;
Commit.Tag:= ATab.TabIndex;
end;
{ RemoveComments: Remove comments from Query window }
procedure TfmQueryWindow.RemoveComments(QueryList: TStringList; StartLine: Integer; var RealStartLine: Integer);
var
Comment: Boolean;
i: Integer;
MultiComment: Boolean;
begin
MultiComment:= False;
for i:= StartLine to QueryList.Count - 1 do
begin
if Pos('/*', Trim(QueryList[i])) = 1 then
begin
MultiComment:= True;
Comment:= False;
end;
// Avoid checking for comments if there's any chance they're within
// a string literal e.g. select 'this is -- no -- comment' from rdb$database
if (not MultiComment) and (pos('''',QueryList[i])=0) then
Comment:= Pos('--', Trim(QueryList[i])) = 1;
if (Trim(QueryList[i]) <> '') and (not Comment) and (not MultiComment) then
begin
RealStartLine:= i;
Break;
end;
if MultiComment and (Pos('*/', QueryList[i]) > 0) then // End of multi-line comment
begin
QueryList[i]:= Trim(Copy(QueryList[i], Pos('*/', QueryList[i]) + 2, Length
(QueryList[i])));
RealStartLine:= i;
MultiComment:= False;
Comment:= False;
if (i = QueryList.Count - 1) or
((Trim(QueryList[i + 1]) <> '') and (Pos('/*', Trim(QueryList[i + 1])
) <> 1) and
(Pos('--', Trim(QueryList[i + 1])) <> 1)) then
Break;
end;
end;
end;
{ RemoveAllSingleLineComments: remove single line comments from query }
procedure TfmQueryWindow.RemoveAllSingleLineComments(QueryList: TStringList);
var
i: Integer;
begin
for i:= QueryList.Count - 1 downto 0 do
begin
if Pos('--', QueryList[i]) > 0 then
begin
if Pos('--', Trim(QueryList[i])) = 1 then
QueryList.Delete(i);
{
else
// this will also pick up -- within string literals which is wrong
QueryList[i]:= Copy(QueryList[i], 1, Pos('--', QueryList[i]) - 1);
}
end;
end;
end;
{ RemoveEmptyLines: remove empty lines in query }
procedure TfmQueryWindow.RemoveEmptyLines(QueryList: TStringList; var SecondRealStart: Integer;
const RealStartLine: Integer);
var
i: integer;
begin
for i:= RealStartLine to QueryList.Count - 1 do
begin
if Trim(QueryList[i]) <> '' then
begin
SecondRealStart:= i;
Break;
end;
end;
end;
{ ApplyClick: Save Updates for the query }
procedure TfmQueryWindow.ApplyClick(Sender: TObject);
var
i, x: Integer;
TableName: string;
UpdateQuery: TSQLQuery;
PKIndexName: string;
ConstraintName: string;
KeyList, FieldsList: TStringList;
WhereClause: string;
UserData: TSQLQuery;
TabIndex: Integer;
FieldsSQL: string;
begin
try
TabIndex:= pgOutputPageCtl.TabIndex;
UserData:= nil;
UserData:= GetCurrentSelectQuery;
// Better safe than sorry
if not(Assigned(UserData)) then
begin
ShowMessage('Error getting query from tabsheet.');
{$IFDEF DEBUG}
SendDebug('ApplyClick: GetRecordSet call returned nil recordset');
{$ENDIF}
exit;
end;
UserData.ApplyUpdates; // lets query run InsertSQL, UpdateSQL, DeleteSQL
(Sender as TBitBtn).Visible:= False;
// Auto commit
if cxAutoCommit.Checked then
FSQLTrans.CommitRetaining
else
EnableCommitButton;
UserData.EnableControls;
except
on E: Exception do
begin
ShowMessage('Error trying to save data: ' + e.Message);
end;
end;
end;
{ EnableApplyButton: enable save updates button on current tab when records have been modified }
procedure TfmQueryWindow.EnableApplyButton;
var
i: Integer;
Ctl: TControl;
ParentPanel: TPanel;
begin
// The page has a panel that contains the button
ParentPanel:=nil;
for i:= 0 to pgOutputPageCtl.ActivePage.ControlCount-1 do
begin
Ctl:=pgOutputPageCtl.ActivePage.Controls[i];
if Ctl is TPanel then
begin
ParentPanel:= TPanel(Ctl); //found
break;
end;
end;
// Found the hosting panel; this should have the Apply button
// as well as the commit button and the tdbnavigator
if assigned(ParentPanel) then
begin
for i:= 0 to ParentPanel.ControlCount-1 do
begin
Ctl:=ParentPanel.Controls[i];
if (Ctl is TBitBtn) and
((Ctl as TBitBtn).Caption = 'Apply') then
begin
(Ctl as TBitBtn).Visible:= true;
Break;
end;
end;
end;
end;
{ EnableCommitButton: enable commit button after applying updates }
procedure TfmQueryWindow.EnableCommitButton;
var
i: Integer;
Ctl: TControl;
ParentPanel: TPanel;
begin
// The page has a panel that contains the button
ParentPanel:=nil;
for i:= 0 to pgOutputPageCtl.ActivePage.ControlCount-1 do
begin
Ctl:=pgOutputPageCtl.ActivePage.Controls[i];
if Ctl is TPanel then
begin
ParentPanel:= TPanel(Ctl); //found
break;
end;
end;
// Found the hosting panel; this should have the Apply, Commit button
// as well as the navigator
if assigned(ParentPanel) then
begin
for i:= 0 to ParentPanel.ControlCount-1 do
begin
Ctl:=ParentPanel.Controls[i];
if (Ctl is TBitBtn) and
((Ctl as TBitBtn).Caption = 'Commit') then
begin
(Ctl as TBitBtn).Visible:= true;
Break;
end;
end;
end;
end;
{ GetTableName: get table name from query text }
function TfmQueryWindow.GetTableName(SQLText: string): string;
begin
SQLText:= Trim(Copy(SQLText, Pos('from', LowerCase(SQLText)) + 4, Length(SQLText)));
if Pos('"', SQLText) = 1 then
begin
Delete(SQLText, 1, 1);
Result:= Copy(SQLText, 1, Pos('"', SQLText) - 1);
end
else
begin
if Pos(' ', SQLText) > 0 then
Result:= Copy(SQLText, 1, Pos(' ', SQLText) - 1)
else
Result:= SQLText;
end;
if Pos(';', Result) > 0 then
Delete(Result, Pos(';', Result), 1);
end;
{ CommitResultClick: commit current transaction }
procedure TfmQueryWindow.CommitResultClick(Sender: TObject);
begin
FSQLTrans.CommitRetaining;
(Sender as TBitBtn).Visible:= False;
end;
procedure TfmQueryWindow.GetLogEvent(Sender: TSQLConnection;
EventType: TDBEventType; const Msg: String);
// Used to log everything sent through the connection
var
Source: string;
begin
case EventType of
detCustom: Source:='Custom: ';
detPrepare: Source:='Prepare: ';
detExecute: Source:='Execute: ';
detFetch: Source:='Fetch: ';
detCommit: Source:='Commit: ';
detRollBack: Source:='Rollback:';
else Source:='Unknown event. Please fix program code.';
end;
SendDebug(Source + Msg);
end;
{ GetCurrentSelectQuery: return result recordset of a page tab }
function TfmQueryWindow.GetCurrentSelectQuery: TSQLQuery;
var
i: Integer;
Ctl: TControl;
begin
// Tabsheet's tag property should point to any select query
Result:= nil;
if (pgOutputPageCtl.PageCount > 0) then
begin
if (pgOutputPageCtl.ActivePage.Tag<>0) then
begin
Result:= TSQLQuery(pgOutputPageCtl.ActivePage.Tag);
end;
end;
end;
{ GetQuerySQLType: get query type: select, script, execute from current string list }
function TfmQueryWindow.GetQuerySQLType(QueryList: TStringList; var LookAtIndex: Integer; var IsDDL: Boolean): TQueryTypes;
var
MassagedSQL: string;
begin
Result:= qtUnknown;
IsDDL:= False; //default
if LookAtIndex < QueryList.Count then
begin
MassagedSQL:= LowerCase(Trim(QueryList[LookAtIndex]));
// Script overrides rest
if Pos('set term', MassagedSQL) = 1 then
begin
// Using set term does not mean the SQL you're running has to be
// DDL (could be an execute block or something) but it most probably is
IsDDL:= true;
exit(qtScript);
end;
if (Pos('select', MassagedSQL) = 1) then
{ todo: (low priority) misses insert...returning,
update...returning, merge.. returning...}
Result:= qtSelectable
else
begin
Result:= qtExecute;
IsDDL:= (Pos('alter', MassagedSQL) = 1) or
(Pos('create', MassagedSQL) = 1) or
(Pos('drop', MassagedSQL) = 1) or
(Pos('grant', MassagedSQL) = 1) {actually DCL} or
(Pos('revoke', MassagedSQL) = 1) {actually DCL};
end;
end;
end;
{ TQueryThread }
{ DoJob: Execute thread job: open query, execute, commit, rollback, etc }
procedure TQueryThread.DoJob;
begin
try
if fType = qaOpen then
FSQLQuery.Open
else
if fType = qaExec then
FSQLQuery.ExecSQL
else
if fType = qaDDL then
FConnection.ExecuteDirect(fStatement)
else
if fType = qaCommit then
FTrans.Commit
else
if fType = qaCommitRet then
FTrans.CommitRetaining
else
if fType = qaRollBack then
FTrans.Rollback
else
if fType = qaRollbackRet then
FTrans.RollbackRetaining;
Error:= False;
fTerminated:= True;
except
on E: Exception do
begin
Error:= True;
ErrorMsg:= e.Message;
fTerminated:= True;
end;
end;
end;
{ Execute: Query thread main loop }
procedure TQueryThread.Execute;
begin
try
fTerminated:= False;
Error:= False;
DoJob;
fTerminated:= True;
except
on E: Exception do
begin
Error:= True;
ErrorMsg:= e.Message;
fTerminated:= True;
end;
end;
end;
{ Create query thread }
constructor TQueryThread.Create(aType: TQueryActions);
begin
inherited Create(True);
fType:= aType;
FreeOnTerminate:= False;
end;
{ Display SQL script exception message }
procedure TfmQueryWindow.SQLScript1Exception(Sender: TObject;
Statement: TStrings; TheException: Exception; var Continue: boolean);
begin
ShowMessage('Error running script: '+TheException.Message);
end;
procedure TfmQueryWindow.SynCompletion1CodeCompletion(var Value: string;
SourceValue: string; var SourceStart, SourceEnd: TPoint; KeyChar: TUTF8Char;
Shift: TShiftState);
begin
SynCompletion1.Deactivate;
end;
{ Close button pressed: close current Query window and free parent page tab }
procedure TfmQueryWindow.tbCloseClick(Sender: TObject);
begin
Close;
Parent.Free;
end;
{ Commit current transaction }
procedure TfmQueryWindow.tbCommitClick(Sender: TObject);
var
meResult: TMemo;
SqlQuery: TSQLQuery;
SqlScript: TModSQLScript;
ATab: TTabSheet;
QT: TQueryThread;
begin
ATab:= CreateResultTab(qtExecute, SqlQuery, SqlScript, meResult);
QT:= TQueryThread.Create(qaCommit);
try
QT.Trans:= FSQLTrans;
ATab.ImageIndex:= 6;
// Run thread
QT.Resume;
repeat
application.ProcessMessages;
until QT.fTerminated;
if QT.Error then
begin
ATab.ImageIndex:= 3;
meResult.Lines.Text:= QT.ErrorMsg;
meResult.Font.Color:= clRed;
end
else
begin
ATab.ImageIndex:= 4;
meResult.Lines.Add('Commited');
meResult.Font.Color:= clGreen;
// Call OnCommit procedure if assigned, it is used to refresh table management view
if OnCommit <> nil then
OnCommit(self);
OnCommit:= nil;
end;
finally
QT.Free;
end;
end;
{ Commit retaining for current transaction }
procedure TfmQueryWindow.tbCommitRetainingClick(Sender: TObject);
var
QT: TQueryThread;
begin
QT:= TQueryThread.Create(qaCommitRet);
try
QT.Trans:= FSQLTrans;
// Run thread
QT.Resume;
repeat
application.ProcessMessages;
until QT.fTerminated;
if QT.Error then
ShowMessage('Error trying commit retaining: '+QT.ErrorMsg)
else
begin
// Call OnCommit procedure if assigned, it is used to refresh table management view
if OnCommit <> nil then
OnCommit(self);
OnCommit:= nil;
end;
finally
QT.Free;
end;
end;
{HistoryClick: show SQL history form }
procedure TfmQueryWindow.tbHistoryClick(Sender: TObject);
begin
fmSQLHistory.Init(FRegRec.Title, Self);
fmSQLHistory.Show;
end;
{ Display popup menu }
procedure TfmQueryWindow.tbMenuClick(Sender: TObject);
begin
pmTab.PopUp;
end;
{ display New SQL Window tab }
procedure TfmQueryWindow.tbNewClick(Sender: TObject);
var
i: Integer;
begin
// Get a free number to be assigned to the new Query window
for i:= 1 to 1000 do
begin
if fmMain.FindQueryWindow(FRegRec.Title + ': Query Window # ' + IntToStr(i)) = nil then
begin
fmMain.ShowCompleteQueryWindow(FDBIndex, 'Query Window # ' + IntToStr(i), '');
Break;
end;
end;
end;
{ Read SQL query from text file }
procedure TfmQueryWindow.tbOpenClick(Sender: TObject);
begin
OpenDialog1.DefaultExt:= '.sql';
if OpenDialog1.Execute then
meQuery.Lines.LoadFromFile(OpenDialog1.FileName);
end;
{ RollBack current transaction }
procedure TfmQueryWindow.tbRollbackClick(Sender: TObject);
var
meResult: TMemo;
SqlQuery: TSQLQuery;
SqlScript: TModSQLScript;
ATab: TTabSheet;
QT: TQueryThread;
begin
ATab:= CreateResultTab(qtExecute, SqlQuery, SqlScript, meResult);
QT:= TQueryThread.Create(qaRollBack);
try
QT.Trans:= FSQLTrans;
ATab.ImageIndex:= 6;
QT.Resume;
repeat
application.ProcessMessages;
until QT.fTerminated;
if QT.Error then
begin
ATab.ImageIndex:= 3;
meResult.Lines.Text:= QT.ErrorMsg;
meResult.Font.Color:= clRed;
end
else
begin
ATab.ImageIndex:= 4;
meResult.Lines.Add('Rollback');
meResult.Font.Color:= clGreen;
if OnCommit <> nil then
OnCommit(self);
OnCommit:= nil;
meResult.Font.Color:= $AA6666;
end;
finally
QT.Free;
end;
end;
{ Rollback retaning for current transaction }
procedure TfmQueryWindow.tbRollbackRetainingClick(Sender: TObject);
var
QT: TQueryThread;
begin
QT:= TQueryThread.Create(qaRollbackRet);
try
QT.Trans:= FSQLTrans;
QT.Resume;
repeat
application.ProcessMessages;
until QT.fTerminated or (FCanceled);
if QT.Error then
ShowMessage('Error trying rollback retaining: '+QT.ErrorMsg);
finally
QT.Free;
end;
end;
{ Run current SQL, auto-detect type }
procedure TfmQueryWindow.tbRunClick(Sender: TObject);
begin
CallExecuteQuery(qtUnknown);
end;
{ Save current SQL in a text file }
procedure TfmQueryWindow.tbSaveClick(Sender: TObject);
begin
SaveDialog1.DefaultExt:= '.sql';
if SaveDialog1.Execute then
meQuery.Lines.SaveToFile(SaveDialog1.FileName);
end;
{GetNewTabNum: get last tab number and increase result by one }
function TfmQueryWindow.GetNewTabNum: string;
var
i: Integer;
Cnt: Integer;
begin
Cnt:= 0;
for i:= 0 to pgOutputPageCtl.ControlCount - 1 do
if pgOutputPageCtl.Pages[i].TabVisible then
Inc(Cnt);
Result:= IntToStr(Cnt);
end;
{ Initialize query window: fill connection parameters from selected registered database }
procedure TfmQueryWindow.Init(dbIndex: Integer);
begin
FDBIndex:= dbIndex;
FRegRec:= fmMain.RegisteredDatabases[dbIndex].RegRec;
// Set instances of FIBConnection and SQLTransaction for the current Query Window
SetTransactionIsolation(FSQLTrans.Params);
FSQLTrans.DataBase:= FIBConnection;
// Set connection parameters to FIBConnection
with fmMain.RegisteredDatabases[dbIndex] do
begin
Self.FIBConnection.DatabaseName:= RegRec.DatabaseName;
Self.FIBConnection.UserName:= RegRec.UserName;
Self.FIBConnection.Password:= RegRec.Password;
Self.FIBConnection.CharSet:= RegRec.Charset;
Self.FIBConnection.Role:= RegRec.Role;
end;
// Get current database tables to be highlighted in SQL query editor
SynSQLSyn1.TableNames.CommaText:= fmMain.GetTableNames(dbIndex);
SynCompletion1.ItemList.AddStrings(SynSQLSyn1.TableNames);
SortSynCompletion;
end;
(************* Is Selectable (Check statement type Select, Update, Alter, etc) *******************)
function TfmQueryWindow.GetQueryType(AQuery: string): TQueryTypes;
var
List: TStringList;
i: Integer;
Line: string;
StartPos, EndPos: Integer;
begin
List:= TStringList.Create;
try
List.Text:= AQuery;
Result:= qtExecute; // Default Execute
for i:= 0 to List.Count - 1 do
begin
Line:= List[i];
// Remove comments
if Pos('--', Line) > 0 then
Line:= Copy(Line, 1, Pos('--', Line) - 1);
if (Pos('/*', Line) > 0) and (Pos('*/', Line) > 0) then
begin
StartPos:= (Pos('/*', Line));
EndPos:= (Pos('*/', Line));
Delete(Line, StartPos, EndPos - StartPos + 1);
end;
if (Pos('select', LowerCase(Trim(Line))) = 1) then
begin
Result:= qtSelectable; // Selectable
Break;
end
else
if Pos('set term', LowerCase(Trim(Line))) = 1 then
begin
Result:= qtScript;
Break;
end;
if Trim(Line) <> '' then
begin
Result:= qtExecute; // Executable
Break;
end;
end;
finally
List.Free;
end;
end;
{ GetQuery: get query text from editor }
function TfmQueryWindow.GetQuery(QueryContents: tstrings): boolean;
var
Seltext: string;
begin
Result:= false;
if assigned(QueryContents) then
begin
SelText:= trim(meQuery.SelText);
if SelTExt<>'' then
QueryContents.Text:= SelText
else
QueryContents.Text:= trim(meQuery.Lines.Text);
Result:= true;
end;
end;
{ Create new result tab depending on query type }
function TfmQueryWindow.CreateResultTab(QueryType: TQueryTypes;
var aSqlQuery: TSQLQuery; var aSQLScript: TModSQLScript; var meResult: TMemo;
AdditionalTitle: string): TTabSheet;
var
ATab: TTabSheet;
DBGrid: TDBGrid;
DataSource: TDataSource;