-
-
Notifications
You must be signed in to change notification settings - Fork 245
/
SPCustomQuery.m
3727 lines (3103 loc) · 164 KB
/
SPCustomQuery.m
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
//
// SPCustomQuery.m
// sequel-pro
//
// Created by Lorenz Textor (lorenz@textor.ch) on May 1, 2002.
// Copyright (c) 2002-2003 Lorenz Textor. All rights reserved.
// Copyright (c) 2012 Sequel Pro Team. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
//
// More info at <https://github.com/sequelpro/sequelpro>
#import "SPCustomQuery.h"
#import "SPSQLParser.h"
#import "SPDataCellFormatter.h"
#import "SPDatabaseDocument.h"
#import "SPTablesList.h"
#import "RegexKitLite.h"
#import "SPFieldEditorController.h"
#import "SPTextAndLinkCell.h"
#import "SPTooltip.h"
#import "SPCopyTable.h"
#import "SPQueryFavoriteManager.h"
#import "SPQueryController.h"
#import "SPEncodingPopupAccessory.h"
#import "SPDataStorage.h"
#import "SPCopyTable.h"
#import "SPGeometryDataView.h"
#import "SPSplitView.h"
#import "SPTextView.h"
#import "RegexKitLite.h"
#import "SPThreadAdditions.h"
#import "SPConstants.h"
#import "SPAppController.h"
#import "SPBundleHTMLOutputController.h"
#import "SPFunctions.h"
#import "SPHelpViewerClient.h"
#import "SPHelpViewerController.h"
#import "SPBundleManager.h"
#import <pthread.h>
#import <SPMySQL/SPMySQL.h>
#import "SPBracketHighlighter.h"
#include <libkern/OSAtomic.h>
#import "sequel-ace-Swift.h"
typedef struct {
NSUInteger query;
NSUInteger total;
} QueryProgress;
typedef void (^QueryProgressHandler)(QueryProgress *);
/**
* This class is used to decouple the background thread running the SQL queries
* from the main thread displaying the progress.
*
* It ensures that
* - the background thread will not get blocked because it has to wait for the UI update to complete,
* - the main thread does not have to process more progress updates than it can handle and
* - the UI is updated at most once for each query (important with slow queries)
*
* This has quite a significant performance impact:
* - Both threads synchronized on progress update =>
* running 2500 queries takes about 157 seconds wall time (SP reported time: 10.5s) and the UI is updated 2500 times
* - With this class decoupling them =>
* running 2500 queries takes about 1 second wall time (SP reported time: 605ms) and the UI is updated 80 times
*/
@interface SPQueryProgressUpdateDecoupling : NSObject
{
QueryProgressHandler updateHandler;
volatile BOOL dirtyMarker;
os_unfair_lock qpLock;
volatile QueryProgress _queryProgress;
}
@property(atomic,assign) QueryProgress queryProgress;
- (instancetype)initWithBlock:(QueryProgressHandler)anUpdateHandler;
- (void)_updateProgress;
@end
@interface SPCustomQuery ()
- (id)_resultDataItemAtRow:(NSInteger)row columnIndex:(NSUInteger)column preserveNULLs:(BOOL)preserveNULLs asPreview:(BOOL)asPreview;
- (void)documentWillClose:(NSNotification *)notification;
- (void)queryFavoritesHaveBeenUpdated:(NSNotification *)notification;
- (void)historyItemsHaveBeenUpdated:(NSNotification *)notification;
- (void)helpWindowClosedByUser:(NSNotification *)notification;
@property (readwrite, strong) NSMutableDictionary<NSNumber*,NSNumber*> *sortCount;
@end
@implementation SPCustomQuery
@synthesize runAllButton;
@synthesize textViewWasChanged;
@synthesize bracketHighlighter;
@synthesize sortCount;
#pragma mark IBAction methods
/**
* Run the primary query task, as per the user preference
*/
- (IBAction)runPrimaryQueryAction:(id)sender
{
if ([prefs boolForKey:SPQueryPrimaryControlRunsAll]) {
[self runAllQueries:sender];
} else {
[self runSelectedQueries:sender];
}
}
/**
* Run the secondary query task, as per the user preference
*/
- (IBAction)runSecondaryQueryAction:(id)sender
{
if ([prefs boolForKey:SPQueryPrimaryControlRunsAll]) {
[self runSelectedQueries:sender];
} else {
[self runAllQueries:sender];
}
}
/**
* Swap the primary and secondary query run actions
*/
- (IBAction)switchDefaultQueryAction:(id)sender
{
BOOL newValue = ![prefs boolForKey:SPQueryPrimaryControlRunsAll];
[prefs setBool:newValue forKey:SPQueryPrimaryControlRunsAll];
[self updateQueryInteractionInterface];
}
/*
* Split all the queries in the text view, split them into individual queries,
* and run sequentially.
*/
- (IBAction)runAllQueries:(id)sender
{
SPSQLParser *queryParser;
NSArray *queries;
// Prevent multiple runs by holding the keys down
if ([tableDocumentInstance isWorking]) return;
// Fixes bug in key equivalents.
if ([[NSApp currentEvent] type] == NSEventTypeKeyUp) {
return;
}
// Re-init sort order
isDesc = NO;
sortColumn = nil;
[sortCount removeAllObjects];
// Retrieve the custom query string and split it into separate SQL queries
queryParser = [[SPSQLParser alloc] initWithString:[textView string]];
[queryParser setDelimiterSupport:YES];
queries = [queryParser splitStringByCharacter:';'];
// If carriage returns were found, normalise the queries
if ([queryParser containsCarriageReturns]) {
NSMutableArray *normalisedQueries = [NSMutableArray arrayWithCapacity:[queries count]];
for (NSString *query in queries) {
[normalisedQueries addObject:[SPSQLParser normaliseQueryForExecution:query]];
}
queries = normalisedQueries;
}
// Reset queryStartPosition
queryStartPosition = 0;
reloadingExistingResult = NO;
[self clearResultViewDetailsToRestore];
[self performQueries:queries withCallback:NULL];
}
/*
* Depending on selection, run either the query containing the selection caret (if the caret is
* at a single point within the text view), or run the selected text (if a text range is selected).
*/
- (IBAction)runSelectedQueries:(id)sender
{
NSArray *queries;
NSRange selectedRange = [textView selectedRange];
// Prevent multiple runs by holding the keys down
if ([tableDocumentInstance isWorking]) return;
// Re-init sort order
isDesc = NO;
sortColumn = nil;
[sortCount removeAllObjects];
// If the current selection is a single caret position, run the current query.
if (selectedRange.length == 0) {
if(!currentQueryRange.length || [textView string].length < currentQueryRange.length) {
NSBeep();
NSLog(@"Could not find a query range suitable to run query");
return;
}
queries = @[[SPSQLParser normaliseQueryForExecution:[[textView string] safeSubstringWithRange:currentQueryRange]]];
// Otherwise, run the selected text.
} else {
SPSQLParser *queryParser = [[SPSQLParser alloc] initWithString:[[textView string] safeSubstringWithRange:selectedRange]];
[queryParser setDelimiterSupport:YES];
queries = [queryParser splitStringByCharacter:';'];
// If carriage returns were found, normalise the queries
if ([queryParser containsCarriageReturns]) {
NSMutableArray *normalisedQueries = [NSMutableArray arrayWithCapacity:[queries count]];
NSString *query = nil;
for (query in queries) {
[normalisedQueries addObject:[SPSQLParser normaliseQueryForExecution:query]];
}
queries = normalisedQueries;
}
}
reloadingExistingResult = NO;
[self clearResultViewDetailsToRestore];
[self performQueries:queries withCallback:NULL];
}
/**
* Insert the choosen favorite query in the query textView or save query to favorites or opens window to edit favorites
*/
- (IBAction)chooseQueryFavorite:(id)sender
{
if ([queryFavoritesButton indexOfSelectedItem] == 1) {
// This should never evaluate to true as we are now performing menu validation, meaning the 'Save Query to Favorites' menu item will
// only be enabled if the query text view has at least one character present.
if ([[textView string] isEqualToString:@""]) {
[NSAlert createWarningAlertWithTitle:NSLocalizedString(@"Empty query", @"empty query message") message:NSLocalizedString(@"Cannot save an empty query.", @"empty query informative message") callback:nil];
return;
}
if ([tableDocumentInstance isUntitled]) {
[saveQueryFavoriteGlobal setState:NSOnState];
}
[[tableDocumentInstance parentWindowControllerWindow] beginSheet:queryFavoritesSheet completionHandler:^(NSModalResponse returnCode) {
if (returnCode == NSModalResponseOK) {
// Add the new query favorite directly the user's preferences here instead of asking the manager to do it
// as it may not have been fully initialized yet.
NSMutableArray *favorites = [NSMutableArray arrayWithArray:[self->prefs objectForKey:SPQueryFavorites]];
// What should be saved
NSString *queryToBeAddded;
if ([self->textView selectedRange].length) { // First check for a selection
queryToBeAddded = [[self->textView string] substringWithRange:[self->textView selectedRange]];
} else if (self->currentQueryRange.length) { // then for a current query
queryToBeAddded = [[self->textView string] substringWithRange:self->currentQueryRange];
} else { // otherwise take the entire string
queryToBeAddded = [self->textView string];
}
if ([self->saveQueryFavoriteGlobal state] == NSOnState) {
[favorites addObject:[NSMutableDictionary dictionaryWithObjects: [NSArray arrayWithObjects:[self->queryFavoriteNameTextField stringValue], queryToBeAddded, nil] forKeys:@[@"name", @"query"]]];
[self->prefs setObject:favorites forKey:SPQueryFavorites];
} else {
[[SPQueryController sharedQueryController] addFavorite:[NSMutableDictionary dictionaryWithObjects: [NSArray arrayWithObjects:[self->queryFavoriteNameTextField stringValue], [queryToBeAddded mutableCopy], nil] forKeys:@[@"name", @"query"]] forFileURL:[self->tableDocumentInstance fileURL]];
}
[self->saveQueryFavoriteGlobal setState:NSOffState];
[self queryFavoritesHaveBeenUpdated:nil];
[self->queryFavoriteNameTextField setStringValue:@""];
}
}];
}
if ([queryFavoritesButton indexOfSelectedItem] == 2) {
// This should never evaluate to true as we are now performing menu validation, meaning the 'Save Query to Favorites' menu item will only be enabled if the query text view has at least one character present.
if ([[textView string] isEqualToString:@""]) {
[NSAlert createWarningAlertWithTitle:NSLocalizedString(@"Empty query", @"empty query message") message:NSLocalizedString(@"Cannot save an empty query.", @"empty query informative message") callback:nil];
return;
}
if ([tableDocumentInstance isUntitled]) {
[saveQueryFavoriteGlobal setState:NSOnState];
}
[[tableDocumentInstance parentWindowControllerWindow] beginSheet:queryFavoritesSheet completionHandler:^(NSModalResponse returnCode) {
if (returnCode == NSModalResponseOK) {
// Add the new query favorite directly the user's preferences here instead of asking the manager to do it
// as it may not have been fully initialized yet.
NSMutableArray *favorites = [NSMutableArray arrayWithArray:[self->prefs objectForKey:SPQueryFavorites]];
// What should be saved
NSString *queryToBeAddded = [self->textView string];
if ([self->saveQueryFavoriteGlobal state] == NSOnState) {
[favorites addObject:[NSMutableDictionary dictionaryWithObjects: [NSArray arrayWithObjects:[self->queryFavoriteNameTextField stringValue], queryToBeAddded, nil] forKeys:@[@"name", @"query"]]];
[self->prefs setObject:favorites forKey:SPQueryFavorites];
} else {
[[SPQueryController sharedQueryController] addFavorite:[NSMutableDictionary dictionaryWithObjects: [NSArray arrayWithObjects:[self->queryFavoriteNameTextField stringValue], [queryToBeAddded mutableCopy], nil] forKeys:@[@"name", @"query"]] forFileURL:[self->tableDocumentInstance fileURL]];
}
[self->saveQueryFavoriteGlobal setState:NSOffState];
[self queryFavoritesHaveBeenUpdated:nil];
[self->queryFavoriteNameTextField setStringValue:@""];
}
}];
} else if ([queryFavoritesButton indexOfSelectedItem] == 3) {
favoritesManager = [[SPQueryFavoriteManager alloc] initWithDelegate:self];
// Open query favorite manager
[[tableDocumentInstance parentWindowControllerWindow] beginSheet:[favoritesManager window] completionHandler:nil];
} else if ([queryFavoritesButton indexOfSelectedItem] > 5) {
// Choose favorite
BOOL replaceContent = [prefs boolForKey:SPQueryFavoriteReplacesContent];
[textView breakUndoCoalescing];
// The actual query strings have been already stored as tooltip
NSMutableString *selectedFaveQueryStr = [[[queryFavoritesButton selectedItem] toolTip] mutableCopy];
if([[NSApp currentEvent] modifierFlags] & (NSEventModifierFlagShift|NSEventModifierFlagControl|NSEventModifierFlagOption|NSEventModifierFlagCommand)){
replaceContent = !replaceContent;
}
if(replaceContent) {
SPLog(@"replaceContent == YES");
[textView.textStorage setAttributedString:[[NSAttributedString alloc] initWithString:@""]];
[textView insertAsSnippet:selectedFaveQueryStr atRange:NSMakeRange(0, selectedFaveQueryStr.length)];
[textView setSelectedRange:NSMakeRange(0,[[textView string] length])];
}
else{
SPLog(@"replaceContent == NO");
NSUInteger startStringLen = [[textView string] length];
[selectedFaveQueryStr insertString:@"\n" atIndex:0];
[textView insertAsSnippet:selectedFaveQueryStr atRange:NSMakeRange(startStringLen, selectedFaveQueryStr.length)];
[textView setSelectedRange:NSMakeRange(startStringLen+1, selectedFaveQueryStr.length)];
}
}
}
/*
* Insert the choosen history query in the query textView
*/
- (IBAction)chooseQueryHistory:(id)sender
{
// Choose history item
if ([queryHistoryButton indexOfSelectedItem] > 6) {
NSMutableString *selectedHistoryQueryStr = [[[[SPQueryController sharedQueryController] historyForFileURL:[tableDocumentInstance fileURL]] safeObjectAtIndex:[queryHistoryButton indexOfSelectedItem]-7] mutableCopy];
BOOL replaceContent = [prefs boolForKey:SPQueryHistoryReplacesContent];
[textView breakUndoCoalescing];
if([[NSApp currentEvent] modifierFlags] & (NSEventModifierFlagShift|NSEventModifierFlagControl|NSEventModifierFlagOption|NSEventModifierFlagCommand)){
replaceContent = !replaceContent;
}
if(replaceContent){
SPLog(@"replaceContent == YES");
[textView.textStorage setAttributedString:[[NSAttributedString alloc] initWithString:@""]];
[textView insertAsSnippet:selectedHistoryQueryStr atRange:NSMakeRange(0, selectedHistoryQueryStr.length)];
[textView setSelectedRange:NSMakeRange(0,[[textView string] length])];
}
else{
SPLog(@"replaceContent == NO");
NSUInteger startStringLen = [[textView string] length];
[selectedHistoryQueryStr insertString:@"\n" atIndex:0];
[textView insertAsSnippet:selectedHistoryQueryStr atRange:NSMakeRange(startStringLen, selectedHistoryQueryStr.length)];
[textView setSelectedRange:NSMakeRange(startStringLen+1, selectedHistoryQueryStr.length)];
}
}
}
/**
* Closes the sheet
*/
- (IBAction)closeSheet:(id)sender
{
[NSApp endSheet:[sender window] returnCode:[sender tag]];
[[sender window] orderOut:self];
}
/**
* Perform simple actions (which don't require their own method), triggered by selecting the appropriate menu item
* in the "gear" action menu displayed beneath the cusotm query view.
*/
- (IBAction)gearMenuItemSelected:(id)sender
{
if ( sender == previousHistoryMenuItem ) {
NSInteger numberOfHistoryItems = [[SPQueryController sharedQueryController] numberOfHistoryItemsForFileURL:[tableDocumentInstance fileURL]];
currentHistoryOffsetIndex++;
if ( numberOfHistoryItems > 0 && currentHistoryOffsetIndex < numberOfHistoryItems && currentHistoryOffsetIndex >= 0) {
historyItemWasJustInserted = YES;
[textView breakUndoCoalescing];
NSString *historyString = [[[SPQueryController sharedQueryController] historyForFileURL:[tableDocumentInstance fileURL]] objectAtIndex:currentHistoryOffsetIndex];
NSRange rangeOfInsertedString = NSMakeRange([textView selectedRange].location, [historyString length]);
[textView.textStorage appendAttributedString:[[NSAttributedString alloc] initWithString:historyString]];
[textView setSelectedRange:rangeOfInsertedString];
} else {
currentHistoryOffsetIndex--;
NSBeep();
}
historyItemWasJustInserted = NO;
}
if ( sender == nextHistoryMenuItem ) {
NSInteger numberOfHistoryItems = [[SPQueryController sharedQueryController] numberOfHistoryItemsForFileURL:[tableDocumentInstance fileURL]];
currentHistoryOffsetIndex--;
if ( numberOfHistoryItems > 0 && currentHistoryOffsetIndex < numberOfHistoryItems && currentHistoryOffsetIndex >= 0) {
historyItemWasJustInserted = YES;
[textView breakUndoCoalescing];
NSString *historyString = [[[SPQueryController sharedQueryController] historyForFileURL:[tableDocumentInstance fileURL]] objectAtIndex:currentHistoryOffsetIndex];
NSRange rangeOfInsertedString = NSMakeRange([textView selectedRange].location, [historyString length]);
[textView.textStorage appendAttributedString:[[NSAttributedString alloc] initWithString:historyString]];
[textView setSelectedRange:rangeOfInsertedString];
} else {
currentHistoryOffsetIndex++;
NSBeep();
}
historyItemWasJustInserted = NO;
}
// "Shift Right" menu item - indent the selection with an additional tab.
if (sender == shiftRightMenuItem) {
[textView shiftSelectionRight];
}
// "Shift Left" menu item - un-indent the selection by one tab if possible.
if (sender == shiftLeftMenuItem) {
[textView shiftSelectionLeft];
}
// "Comment Line/Selection" menu item - Add or remove "-- " for each line
// in a line or selection resp. or wrap the selection into /* */
// if the selection does not end at the end of a line (in-line comment)
if (sender == commentLineOrSelectionMenuItem) {
[self commentOut];
}
// "Comment Current Query" menu item - Add or remove "-- " for each line
// in the current query
if (sender == commentCurrentQueryMenuItem) {
[self commentOutCurrentQueryTakingSelection:NO];
}
// "Completion List" menu item - used to autocomplete. Uses a different shortcut to avoid the menu button flickering
// on normal autocomplete usage.
if (sender == completionListMenuItem) {
if([[NSApp currentEvent] modifierFlags] & (NSEventModifierFlagControl))
[textView doCompletionByUsingSpellChecker:NO fuzzyMode:YES autoCompleteMode:NO];
else
[textView doCompletionByUsingSpellChecker:NO fuzzyMode:NO autoCompleteMode:NO];
}
// "Editor font..." menu item to bring up the font panel
if (sender == editorFontMenuItem) {
[[NSFontPanel sharedFontPanel] setPanelFont:[textView font] isMultiple:NO];
[[NSFontPanel sharedFontPanel] setDelegate:self];
[[NSFontPanel sharedFontPanel] makeKeyAndOrderFront:self];
}
// "Indent new lines" toggle
if (sender == autoindentMenuItem) {
BOOL enableAutoindent = !([autoindentMenuItem state] == NSOffState);
[prefs setBool:enableAutoindent forKey:SPCustomQueryAutoIndent];
[autoindentMenuItem setState:enableAutoindent?NSOnState:NSOffState];
[textView setAutoindent:enableAutoindent];
}
// "Auto-pair characters" toggle
if (sender == autopairMenuItem) {
BOOL enableAutopair = !([autopairMenuItem state] == NSOffState);
[prefs setBool:enableAutopair forKey:SPCustomQueryAutoPairCharacters];
[autopairMenuItem setState:enableAutopair?NSOnState:NSOffState];
[textView setAutopair:enableAutopair];
}
// "Auto-help" toggle
if (sender == autohelpMenuItem) {
BOOL enableAutohelp = !([autohelpMenuItem state] == NSOffState);
[prefs setBool:enableAutohelp forKey:SPCustomQueryUpdateAutoHelp];
[autohelpMenuItem setState:enableAutohelp?NSOnState:NSOffState];
[textView setAutohelp:enableAutohelp];
}
// "Auto-uppercase keywords" toggle
if (sender == autouppercaseKeywordsMenuItem) {
BOOL enableAutouppercaseKeywords = !([autouppercaseKeywordsMenuItem state] == NSOffState);
[prefs setBool:enableAutouppercaseKeywords forKey:SPCustomQueryAutoUppercaseKeywords];
[autouppercaseKeywordsMenuItem setState:enableAutouppercaseKeywords?NSOnState:NSOffState];
[textView setAutouppercaseKeywords:enableAutouppercaseKeywords];
}
}
- (IBAction)saveQueryHistory:(id)sender
{
NSSavePanel *panel = [NSSavePanel savePanel];
[panel setAllowedFileTypes:@[SPFileExtensionSQL]];
[panel setExtensionHidden:NO];
[panel setAllowsOtherFileTypes:YES];
[panel setCanSelectHiddenExtension:YES];
[panel setCanCreateDirectories:YES];
[panel setAccessoryView:[SPEncodingPopupAccessory encodingAccessory:[prefs integerForKey:SPLastSQLFileEncoding] includeDefaultEntry:NO encodingPopUp:&encodingPopUp]];
[encodingPopUp setEnabled:YES];
[panel setNameFieldStringValue:@"history"];
[panel beginSheetModalForWindow:[tableDocumentInstance parentWindowControllerWindow] completionHandler:^(NSInteger returnCode) {
if (returnCode == NSModalResponseOK) {
NSError *error = nil;
[self->prefs setInteger:[[self->encodingPopUp selectedItem] tag] forKey:SPLastSQLFileEncoding];
[[self buildHistoryString] writeToURL:[panel URL]
atomically:YES
encoding:[[self->encodingPopUp selectedItem] tag]
error:&error];
if (error) [[NSAlert alertWithError:error] runModal];
}
}];
}
- (IBAction)copyQueryHistory:(id)sender
{
NSPasteboard *pb = [NSPasteboard generalPasteboard];
[pb declareTypes:@[NSStringPboardType] owner:nil];
[pb setString:[self buildHistoryString] forType:NSStringPboardType];
}
/**
* 'Clear History' menu item - clear query history
*/
- (IBAction)clearQueryHistory:(id)sender {
NSString *infoString;
if ([tableDocumentInstance isUntitled]) {
infoString = NSLocalizedString(@"Are you sure you want to clear the global history list? This action cannot be undone.", @"clear global history list informative message");
} else {
infoString = [NSString stringWithFormat:NSLocalizedString(@"Are you sure you want to clear the history list for “%@”? This action cannot be undone.", @"clear history list for “%@” informative message"), [tableDocumentInstance displayName]];
}
[NSAlert createDefaultAlertWithTitle:NSLocalizedString(@"Clear History?", @"clear history message") message:infoString primaryButtonTitle:NSLocalizedString(@"Clear", @"clear button") primaryButtonHandler:^{
// Remove items in the query controller
[[SPQueryController sharedQueryController] replaceHistoryByArray:[NSMutableArray array] forFileURL:[self->tableDocumentInstance fileURL]];
} cancelButtonHandler:nil];
}
/* *
* Set font panel's valid modes
*/
- (NSFontPanelModeMask)validModesForFontPanel:(NSFontPanel *)fontPanel
{
return NSFontPanelSizeModeMask | NSFontPanelCollectionModeMask;
}
#pragma mark -
#pragma mark Query actions
- (void)performQueriesWithNoWarning:(NSArray *)queries withCallback:(SEL)customQueryCallbackMethod{
NSString *taskString;
//ensure there is no pending edit, which could be messed up (#2113)
[[tableDocumentInstance parentWindowControllerWindow] endEditingFor:nil];
if ([queries count] > 1) {
taskString = [NSString stringWithFormat:NSLocalizedString(@"Running query %i of %lu...", @"Running multiple queries string"), 1, (unsigned long)[queries count]];
}
else {
taskString = NSLocalizedString(@"Running query...", @"Running single query string");
}
[tableDocumentInstance startTaskWithDescription:taskString];
[errorTextTitle setStringValue:NSLocalizedString(@"Query Status", @"Query Status")];
// reset colour
[errorText setTextColor:[NSColor controlTextColor]];
[errorText setString:taskString];
[affectedRowsText setStringValue:@""];
NSValue *encodedCallbackMethod = nil;
if (customQueryCallbackMethod)
encodedCallbackMethod = [NSValue valueWithBytes:&customQueryCallbackMethod objCType:@encode(SEL)];
NSDictionary *taskArguments = [NSDictionary dictionaryWithObjectsAndKeys:queries, @"queries", encodedCallbackMethod, @"callback", nil];
// If a helper thread is already running, execute inline - otherwise detach a new thread for the queries
if ([NSThread isMainThread]) {
[NSThread detachNewThreadWithName:SPCtxt(@"SPCustomQuery query perform task", tableDocumentInstance) target:self selector:@selector(performQueriesTask:) object:taskArguments];
}
else {
[self performQueriesTask:taskArguments];
}
}
/**
* Method that checks if an array of SQL queries contain any destructive SQL
* Basically, defaults to YES, unless all of the queries start with SHOW or SELECT
*
* @param queries NSArray - Array of SQL queries
*
* @return BOOL YES if any of the queries contain destructive SQL
*/
-(BOOL)queriesContainDestructiveSQL:(NSArray *)queries{
NSArray *safeCommands = @[@"SHOW", @"SELECT"];
BOOL __block retCode = YES;
[queries enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop){
retCode = YES;
if([obj isKindOfClass:[NSString class]] && [(NSString *)obj length]){
NSMutableString *query = [obj mutableCopy];
// remove comments
[query replaceOccurrencesOfRegex:@"--.*?\n" withString:@""];
[query replaceOccurrencesOfRegex:@"--.*?$" withString:@""];
[query replaceOccurrencesOfRegex:@"/\\*(.|\n)*?\\*/" withString:@""];
// trim leading and trailing spaces and new lines
[query setString:[query trimWhitespacesAndNewlines]];
SPLog(@"query: [%@]", query);
for (NSString *safeCommand in safeCommands){
if([query hasPrefixWithPrefix:safeCommand caseSensitive:NO] == YES){
SPLog(@"Safe command: [%@], breaking", safeCommand);
retCode = NO;
break;
}
}
} // End isKindOfClass
// if we get to here and retCode is still YES,
// then it means the query contains Destructive SQL
// so we can just stop and return YES
if(retCode == YES){
*stop = YES;
}
}];
return retCode;
}
/**
* Performs the mysql-query given by the user
* sets the tableView columns corresponding to the mysql-result
*/
- (void)performQueries:(NSArray *)queries withCallback:(SEL)customQueryCallbackMethod;
{
// check for new flag, if set to no, just exec queries
if ([prefs boolForKey:SPQueryWarningEnabled] == NO) {
[self performQueriesWithNoWarning:queries withCallback:customQueryCallbackMethod];
return;
}
// search for destructive SQL
// if no destructive SQL, just execute
if([self queriesContainDestructiveSQL:queries] == NO){
[self performQueriesWithNoWarning:queries withCallback:customQueryCallbackMethod];
return;
}
NSMutableString *theQueries = [[NSMutableString alloc] init];
for(NSString *tmpStr in queries){
SPLog(@"len: %lu", (unsigned long)tmpStr.length);
[theQueries appendString:tmpStr];
[theQueries appendString:@"\n\n"];
}
SPLog(@"theQueriesLen: %lu", theQueries.length);
NSString *infoText = [NSString stringWithFormat:NSLocalizedString(@"Do you really want to proceed with this query?\n\n %@", @"message of panel asking for confirmation for exec query"),theQueries];
if(queries.count > 1){
infoText = [NSString stringWithFormat:NSLocalizedString(@"Do you really want to proceed with these queries?\n\n %@", @"message of panel asking for confirmation for exec query"),theQueries];
}
if(theQueries.length > SPMaxQueryLengthForWarning){
theQueries = (NSMutableString*)[theQueries summarizeToLength:SPMaxQueryLengthForWarning withEllipsis:YES];
infoText = [NSString stringWithFormat:NSLocalizedString(@"Do you really want to proceed with these queries?\n\n %@", @"message of panel asking for confirmation for exec query"), theQueries];
}
[NSAlert createDefaultAlertWithTitle:[NSString stringWithFormat:NSLocalizedString(@"Execute SQL?", @"Execute SQL?")]
message:infoText
primaryButtonTitle:NSLocalizedString(@"Proceed", @"Proceed")
primaryButtonHandler:^{
SPLog(@"User clicked Yes, exec queries");
[self performQueriesWithNoWarning:queries withCallback:customQueryCallbackMethod];
}
cancelButtonHandler:^{
SPLog(@"Cancel pressed");
}];
}
- (void)performQueriesTask:(NSDictionary *)taskArguments
{
@autoreleasepool {
NSArray *queries = [taskArguments objectForKey:@"queries"];
SPMySQLStreamingResultStore *resultStore = nil;
NSMutableString *errors = [NSMutableString string];
SEL callbackMethod = NULL;
NSString *taskButtonString;
NSUInteger __block i, totalQueriesRun = 0, totalAffectedRows = 0;
double executionTime = 0;
NSInteger firstErrorOccurredInQuery = -1;
BOOL __block suppressErrorSheet = NO;
BOOL tableListNeedsReload = NO;
BOOL databaseWasChanged = NO;
// BOOL queriesSeparatedByDelimiter = NO;
NSCharacterSet *whitespaceAndNewlineSet = [NSCharacterSet whitespaceAndNewlineCharacterSet];
[tableDocumentInstance setQueryMode:SPCustomQueryQueryMode];
NSNotificationCenter *defaultNC = [NSNotificationCenter defaultCenter];
// Notify listeners that a query has started
[defaultNC postNotificationOnMainThreadWithName:@"SMySQLQueryWillBePerformed" object:tableDocumentInstance];
// Reset the current table view as necessary to avoid redraw and reload issues.
// Restore the view position to the top left to be within the results for all datasets.
if(editedRow == -1 && !reloadingExistingResult) {
[[customQueryView onMainThread] scrollRowToVisible:0];
[[customQueryView onMainThread] scrollColumnToVisible:0];
}
// Remove all the columns if not reloading the table
if(!reloadingExistingResult) {
[[self onMainThread] updateTableView];
}
// Disable automatic query retries on failure for the custom queries
[mySQLConnection setRetryQueriesOnConnectionFailure:NO];
NSUInteger queryCount = [queries count];
NSMutableArray *tempQueries = [NSMutableArray arrayWithCapacity:queryCount];
// Enable task cancellation
taskButtonString = (queryCount > 1)? NSLocalizedString(@"Stop queries", @"Stop queries string") : NSLocalizedString(@"Stop query", @"Stop query string");
[tableDocumentInstance enableTaskCancellationWithTitle:taskButtonString callbackObject:nil callbackFunction:NULL];
SPQueryProgressUpdateDecoupling *progressUpdater = [[SPQueryProgressUpdateDecoupling alloc] initWithBlock:^(QueryProgress *qp) {
NSString *taskString = [NSString stringWithFormat:NSLocalizedString(@"Running query %ld of %lu...", @"Running multiple queries string"), (long)(qp->query+1), (unsigned long)(qp->total)];
[self->tableDocumentInstance setTaskDescription:taskString];
// reset text colour
[self->errorText setTextColor:[NSColor controlTextColor]];
[self->errorText setString:taskString];
}];
// Perform the supplied queries in series
for ( i = 0 ; i < queryCount ; i++ ) {
if (i > 0) {
QueryProgress qp = { .query = i, .total = queryCount};
[progressUpdater setQueryProgress:qp];
}
NSString *query = [[queries safeObjectAtIndex:i] stringByTrimmingCharactersInSet:whitespaceAndNewlineSet];
// Don't run blank queries, or queries which only contain whitespace.
if (![query length]) continue;
// store trimmed queries for usedQueries and history
[tempQueries addObject:query];
// Run the query, timing execution (note this also includes network and overhead)
resultStore = [mySQLConnection resultStoreFromQueryString:query];
executionTime += [resultStore queryExecutionTime];
totalQueriesRun++;
// If this is the last query, retrieve and store the result; otherwise,
// discard the result without fully loading.
if (totalQueriesRun == queryCount || [mySQLConnection lastQueryWasCancelled]) {
// Retrieve and cache the column definitions for the result array
cqColumnDefinition = [resultStore fieldDefinitions];
if(!reloadingExistingResult) {
[[self onMainThread] updateTableView];
}
// Find result table name for copying as SQL INSERT.
// If more than one table name is found set resultTableName to nil.
// resultTableName will be set to the original table name (not defined via AS) provided by mysql return
// and the resultTableName can differ due to case-sensitive/insensitive settings!.
NSString *resultTableName = [[cqColumnDefinition objectAtIndex:0] objectForKey:@"org_table"];
for(id field in cqColumnDefinition) {
if(![[field objectForKey:@"org_table"] isEqualToString:resultTableName]) {
resultTableName = nil;
break;
}
}
// Init copyTable with necessary information for copying selected rows as SQL INSERT
[customQueryView setTableInstance:self
withTableData:resultData
withColumns:cqColumnDefinition
withTableName:resultTableName
withConnection:mySQLConnection];
[self updateResultStore:resultStore];
} else {
[resultStore cancelResultLoad];
}
// Record any affected rows
if ( [mySQLConnection rowsAffectedByLastQuery] != (unsigned long long)~0 ) {
totalAffectedRows += (NSUInteger) [mySQLConnection rowsAffectedByLastQuery];
}
else if ( [resultStore numberOfRows] ) {
totalAffectedRows += (NSUInteger) [resultStore numberOfRows];
}
// Store any error messages
if ([mySQLConnection queryErrored] || [mySQLConnection lastQueryWasCancelled]) {
NSString *errorString;
if ([mySQLConnection lastQueryWasCancelled]) {
errorString = NSLocalizedString(@"Query cancelled.", @"Query cancelled error");
} else {
errorString = [mySQLConnection lastErrorMessage];
// If dealing with a "MySQL server has gone away" error, explain the situation.
// Error 2006 is CR_SERVER_GONE_ERROR, which means the query write couldn't complete.
if ([mySQLConnection lastErrorID] == 2006) {
errorString = [NSString stringWithFormat:@"%@.\n\n%@", errorString, NSLocalizedString(@"(This usually indicates that the connection has been closed by the server after inactivity, but can also occur due to other conditions. The connection has been restored; please try again if the query is safe to re-run.)", @"Explanation for MySQL server has gone away error")];
}
}
// If the query errored, append error to the error log for display at the end
if ( queryCount > 1 ) {
if(firstErrorOccurredInQuery == -1) firstErrorOccurredInQuery = i+1;
if(!suppressErrorSheet) {
// Update error text for the user
[errors appendFormat:NSLocalizedString(@"[ERROR in query %ld] %@\n", @"error text when multiple custom query failed"), (long)(i+1), errorString];
[[errorTextTitle onMainThread] setStringValue:NSLocalizedString(@"Last Error Message", @"Last Error Message")];
if(errors.length>0){
SPMainQSync(^{
[self->errorText setString:errors];
// set text colour to red
[self->errorText setTextColor:[NSColor redColor]];
});
}
SPMainQSync(^{
// ask the user to continue after detecting an error
if (![self->mySQLConnection lastQueryWasCancelled]) {
[self->tableDocumentInstance setTaskIndicatorShouldAnimate:NO];
NSAlert *alert = [[NSAlert alloc] init];
[alert setMessageText:NSLocalizedString(@"MySQL Error", @"mysql error message")];
[alert setInformativeText:[self->mySQLConnection lastErrorMessage]];
// Order of buttons matters! first button has "firstButtonReturn" return value from runModal()
[alert addButtonWithTitle:NSLocalizedString(@"Run All", @"run all button")];
[alert addButtonWithTitle:NSLocalizedString(@"Continue", @"continue button")];
[alert addButtonWithTitle:NSLocalizedString(@"Stop", @"stop button")];
NSInteger alertReturnCode = [alert runModal];
[self->tableDocumentInstance setTaskIndicatorShouldAnimate:YES];
switch (alertReturnCode) {
case NSAlertFirstButtonReturn:
suppressErrorSheet = YES;
case NSAlertSecondButtonReturn:
break;
default:
if (i < queryCount-1) {
// output that message only if it was not the last one
[errors appendString:NSLocalizedString(@"Execution stopped!\n", @"execution stopped message")];
}
i = queryCount; // break for loop; for safety reasons stop the execution of the following queries
}
}
});
} else {
[errors appendFormat:NSLocalizedString(@"[ERROR in query %ld] %@\n", @"error text when multiple custom query failed"),
(long)(i+1),
errorString];
}
} else {
[errors setStringOrNil:errorString];
}
} // end of query errored
else {
// Check if table/db list needs an update
// The regex is a compromise between speed and usefullness. TODO: further improvements are needed
if (!tableListNeedsReload && [query isMatchedByRegex:@"(?i)^\\s*\\b(create|alter|drop|rename)\\b\\s+."]) {
tableListNeedsReload = YES;
}
if (!databaseWasChanged && [query isMatchedByRegex:@"(?i)^\\s*\\b(use|drop\\s+database|drop\\s+schema)\\b\\s+."]) {
databaseWasChanged = YES;
}
}
// write errors to console
[tableDocumentInstance queryGaveError:errors connection:nil];
// If the query was cancelled, end all queries.
if ([mySQLConnection lastQueryWasCancelled]) break;
}
// Reload table list if at least one query began with drop, alter, rename, or create
if(tableListNeedsReload || databaseWasChanged) {
// Build database pulldown menu
[[tableDocumentInstance onMainThread] setDatabases:self];
if (databaseWasChanged) {
// Reset the current database
[tableDocumentInstance refreshCurrentDatabase];
}
// Reload table list
[tablesListInstance updateTables:self];
}
// if(!queriesSeparatedByDelimiter) // TODO: How to combine queries delimited by DELIMITER?
usedQuery = [NSString stringWithString:[tempQueries componentsJoinedByString:@";\n"]]; // MARK: JCS - this is where the queries are split, by ";\n"
lastExecutedQuery = [tempQueries lastObject];
// Perform empty query if no query is given
if ( !queryCount ) {
resultStore = [mySQLConnection resultStoreFromQueryString:@""];
[resultStore cancelResultLoad];
[errors setStringOrNil:[mySQLConnection lastErrorMessage]];
}
// add query to history
if(!reloadingExistingResult && [usedQuery length]) {
[self performSelectorOnMainThread:@selector(addHistoryEntry:) withObject:usedQuery waitUntilDone:NO];
}
// Update status/errors text
NSDictionary *statusDetails = [NSDictionary dictionaryWithObjectsAndKeys:
errors, @"errorString",
[NSNumber numberWithInteger:firstErrorOccurredInQuery], @"firstErrorQueryNumber",
nil
];
[self performSelectorOnMainThread:@selector(updateStatusInterfaceWithDetails:) withObject:statusDetails waitUntilDone:YES];
// Set up the status string
NSString *statusString = nil;
NSString *statusErrorString = [errors length]?NSLocalizedString(@"Errors", @"Errors title"):NSLocalizedString(@"No errors", @"No errors title");
if ( [mySQLConnection lastQueryWasCancelled] ) {
if (totalQueriesRun > 1) {
statusString = [NSString stringWithFormat:NSLocalizedString(@"%@; Cancelled in query %ld, after %@", @"text showing multiple queries were cancelled"),
statusErrorString,
(long)totalQueriesRun,
[NSString stringForTimeInterval:executionTime]];
} else {
statusString = [NSString stringWithFormat:NSLocalizedString(@"%@; Cancelled after %@", @"text showing a query was cancelled"),
statusErrorString,
[NSString stringForTimeInterval:executionTime]];
}
} else if ( totalQueriesRun > 1 ) {
if (totalAffectedRows==1) {
statusString = [NSString stringWithFormat:NSLocalizedString(@"%@; 1 row affected in total, by %ld queries taking %@", @"text showing one row has been affected by multiple queries"),
statusErrorString,
(long)totalQueriesRun,