-
Notifications
You must be signed in to change notification settings - Fork 842
/
SPTablesList.m
2745 lines (2317 loc) · 106 KB
/
SPTablesList.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
//
// SPTablesList.m
// sequel-pro
//
// Created by Lorenz Textor (lorenz@textor.ch) on Wed 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 "SPTablesList.h"
#import "SPDatabaseDocument.h"
#import "SPTableStructure.h"
#import "SPDatabaseStructure.h"
#import "SPDatabaseViewController.h"
#ifndef SP_CODA /* headers */
#import "SPTableContent.h"
#endif
#import "SPTableData.h"
#ifndef SP_CODA /* headers */
#import "SPTableInfo.h"
#import "SPDataImport.h"
#import "SPTableView.h"
#import "ImageAndTextCell.h"
#import "RegexKitLite.h"
#endif
#import "SPDatabaseData.h"
#import "SPAlertSheets.h"
#ifndef SP_CODA /* headers */
#import "SPNavigatorController.h"
#import "SPHistoryController.h"
#endif
#import "SPServerSupport.h"
#ifndef SP_CODA /* headers */
#import "SPWindowController.h"
#import "SPAppController.h"
#import "SPSplitView.h"
#endif
#import "SPThreadAdditions.h"
#ifdef SP_CODA
#import "SQLSidebarViewController.h"
#endif
#import "SPCharsetCollationHelper.h"
#import "SPWindowManagement.h"
#import <SPMySQL/SPMySQL.h>
// Constants
static NSString *SPAddRow = @"SPAddRow";
static NSString *SPAddNewTable = @"SPAddNewTable";
static NSString *SPRemoveTable = @"SPRemoveTable";
#ifndef SP_CODA
static NSString *SPTruncateTable = @"SPTruncateTable";
static NSString *SPDuplicateTable = @"SPDuplicateTable";
#endif
@interface SPTablesList ()
#ifndef SP_CODA
- (void)_removeTable:(NSNumber *)force;
- (void)_truncateTable;
#endif
- (void)_addTable;
#ifndef SP_CODA
- (void)_copyTable;
#endif
- (void)_renameTableOfType:(SPTableType)tableType from:(NSString *)oldTableName to:(NSString *)newTableName;
- (void)_duplicateConnectionToFrontTab;
- (NSMutableArray *)_allSchemaObjectsOfType:(SPTableType)type;
@end
@implementation SPTablesList
#ifdef SP_CODA
@synthesize sidebarViewController;
@synthesize databaseDataInstance;
@synthesize toolbarAddButton;
@synthesize toolbarDeleteButton;
@synthesize toolbarReloadButton;
@synthesize tableSourceInstance;
@synthesize tableContentInstance;
@synthesize tableSheet;
@synthesize tableNameField;
@synthesize tableEncodingButton;
@synthesize tableTypeButton;
@synthesize addTableButton;
@synthesize tablesListView;
#endif
#pragma mark -
#pragma mark Initialisation
- (id)init
{
if ((self = [super init])) {
tables = [[NSMutableArray alloc] init];
filteredTables = tables;
tableTypes = [[NSMutableArray alloc] init];
filteredTableTypes = tableTypes;
isTableListFiltered = NO;
tableListIsSelectable = YES;
tableListContainsViews = NO;
selectedTableType = SPTableTypeNone;
selectedTableName = nil;
#ifndef SP_CODA
[tables addObject:NSLocalizedString(@"TABLES", @"header for table list")];
smallSystemFont = [NSFont systemFontOfSize:[NSFont smallSystemFontSize]];
#endif
addTableCharsetHelper = nil; //initialized in awakeFromNib
}
return self;
}
- (void)awakeFromNib
{
#ifndef SP_CODA
// Configure the table information pane
[tableListSplitView setCollapsibleSubviewIndex:1];
// Collapse the pane if the last state was collapsed
if ([[[NSUserDefaults standardUserDefaults] objectForKey:SPTableInformationPanelCollapsed] boolValue]) {
[tableListSplitView setCollapsibleSubviewCollapsed:YES animate:NO];
}
// Configure the table list filter, starting it collapsed
[tableListFilterSplitView setCollapsibleSubviewIndex:0];
[tableListFilterSplitView setCollapsibleSubviewCollapsed:YES animate:NO];
// Disable tab edit behaviour in the tables list
[tablesListView setTabEditingDisabled:YES];
#endif
// Add observers for document task activity
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(startDocumentTaskForTab:)
name:SPDocumentTaskStartNotification
object:tableDocumentInstance];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(endDocumentTaskForTab:)
name:SPDocumentTaskEndNotification
object:tableDocumentInstance];
#ifndef SP_CODA
[tablesListView registerForDraggedTypes:@[SPNavigatorTableDataPasteboardDragType]];
#endif
//create the charset helper
addTableCharsetHelper = [[SPCharsetCollationHelper alloc] initWithCharsetButton:tableEncodingButton CollationButton:tableCollationButton];
}
#pragma mark -
#pragma mark IBAction methods
/**
* Loads all table names in array tables and reload the tableView
*/
- (IBAction)updateTables:(id)sender
{
SPMySQLResult *theResult;
NSString *previousSelectedTable = nil;
NSString *previousFilterString = nil;
BOOL previousTableListIsSelectable = tableListIsSelectable;
BOOL changeEncoding = ![[mySQLConnection encoding] isEqualToString:@"utf8"];
if (selectedTableName) previousSelectedTable = [[NSString alloc] initWithString:selectedTableName];
#ifndef SP_CODA /* table list filtering */
if (isTableListFiltered) {
previousFilterString = [[NSString alloc] initWithString:[listFilterField stringValue]];
if (filteredTables) [filteredTables release];
filteredTables = tables;
if (filteredTableTypes) [filteredTableTypes release];
filteredTableTypes = tableTypes;
isTableListFiltered = NO;
[[self onMainThread] clearFilter];
}
tableListContainsViews = NO;
#endif
tableListIsSelectable = YES;
#ifndef SP_CODA
[[tablesListView onMainThread] deselectAll:self];
tableListIsSelectable = previousTableListIsSelectable;
#endif
[tables removeAllObjects];
[tableTypes removeAllObjects];
if ([tableDocumentInstance database]) {
// Notify listeners that a query has started
[[NSNotificationCenter defaultCenter] postNotificationOnMainThreadWithName:@"SMySQLQueryWillBePerformed" object:tableDocumentInstance];
// Use UTF8 for identifier-based queries
if (changeEncoding) {
[mySQLConnection storeEncodingForRestoration];
[mySQLConnection setEncoding:@"utf8"];
}
// Select the table list for the current database. On MySQL versions after 5 this will include
// views; on MySQL versions >= 5.0.02 select the "full" list to also select the table type column.
theResult = [mySQLConnection queryString:@"SHOW /*!50002 FULL*/ TABLES"];
[theResult setDefaultRowReturnType:SPMySQLResultRowAsArray];
if ([theResult numberOfFields] == 1) {
for (NSArray *eachRow in theResult) {
[tables addObject:[eachRow objectAtIndex:0]];
[tableTypes addObject:[NSNumber numberWithInteger:SPTableTypeTable]];
}
} else {
for (NSArray *eachRow in theResult) {
// Due to encoding problems it can be the case that [resultRow objectAtIndex:0]
// return NSNull, thus catch that case for safety reasons
id tableName = [eachRow objectAtIndex:0];
if ([tableName isNSNull]) {
tableName = @"...";
}
[tables addObject:tableName];
if ([[eachRow objectAtIndex:1] isEqualToString:@"VIEW"]) {
[tableTypes addObject:[NSNumber numberWithInteger:SPTableTypeView]];
tableListContainsViews = YES;
} else {
[tableTypes addObject:[NSNumber numberWithInteger:SPTableTypeTable]];
}
}
}
// Reorder the tables in alphabetical order
[tables sortArrayUsingSelector:@selector(localizedCompare:) withPairedMutableArrays:tableTypes, nil];
#ifndef SP_CODA /* table procedures and functions */
/* Grab the procedures and functions
*
* Using information_schema gives us more info (for information window perhaps?) but breaks
* backward compatibility with pre 4 I believe. I left the other methods below, in case.
*/
if ([[tableDocumentInstance serverSupport] supportsInformationSchema]) {
NSString *pQuery = [NSString stringWithFormat:@"SELECT * FROM information_schema.routines WHERE routine_schema = %@ ORDER BY routine_name", [[tableDocumentInstance database] tickQuotedString]];
theResult = [mySQLConnection queryString:pQuery];
[theResult setDefaultRowReturnType:SPMySQLResultRowAsArray];
// Check for mysql errors - if information_schema is not accessible for some reasons
// omit adding procedures and functions
if(![mySQLConnection queryErrored] && theResult != nil && [theResult numberOfRows] && [theResult numberOfFields] > 3) {
// Add the header row
[tables addObject:NSLocalizedString(@"PROCS & FUNCS",@"header for procs & funcs list")];
[tableTypes addObject:[NSNumber numberWithInteger:SPTableTypeNone]];
for (NSArray *eachRow in theResult) {
[tables addObject:NSArrayObjectAtIndex(eachRow, 3)];
if ([NSArrayObjectAtIndex(eachRow, 4) isEqualToString:@"PROCEDURE"]) {
[tableTypes addObject:[NSNumber numberWithInteger:SPTableTypeProc]];
} else {
[tableTypes addObject:[NSNumber numberWithInteger:SPTableTypeFunc]];
}
}
}
}
#endif
// Restore encoding if appropriate
if (changeEncoding) [mySQLConnection restoreStoredEncoding];
// Notify listeners that the query has finished
[[NSNotificationCenter defaultCenter] postNotificationOnMainThreadWithName:@"SMySQLQueryHasBeenPerformed" object:tableDocumentInstance];
}
#ifndef SP_CODA
// Add the table headers even if no tables were found
if (tableListContainsViews) {
[tables insertObject:NSLocalizedString(@"TABLES & VIEWS",@"header for table & views list") atIndex:0];
}
else {
[tables insertObject:NSLocalizedString(@"TABLES",@"header for table list") atIndex:0];
}
[tableTypes insertObject:[NSNumber numberWithInteger:SPTableTypeNone] atIndex:0];
#endif
#ifndef SP_CODA /* ui manipulation */
[[tablesListView onMainThread] reloadData];
#else
[sidebarViewController setTableNames:[self allTableNames] selectedTableName:selectedTableName];
[sidebarViewController tableViewSelectionDidChange:nil];
#endif
// if the previous selected table still exists, select it
// but not if the update was called from SPTableData since it calls that method
// if a selected table doesn't exist - this happens if a table was deleted/renamed by an other user
// or if the table name contains characters which are not supported by the current set encoding
if ( ![sender isKindOfClass:[SPTableData class]] && previousSelectedTable != nil && [tables indexOfObject:previousSelectedTable] < [tables count]) {
NSInteger itemToReselect = [tables indexOfObject:previousSelectedTable];
tableListIsSelectable = YES;
#ifndef SP_CODA /* ui manipulation */
[[tablesListView onMainThread] selectRowIndexes:[NSIndexSet indexSetWithIndex:itemToReselect] byExtendingSelection:NO];
#endif
tableListIsSelectable = previousTableListIsSelectable;
if (selectedTableName) [selectedTableName release];
selectedTableName = [[NSString alloc] initWithString:[tables objectAtIndex:itemToReselect]];
selectedTableType = (SPTableType)[[tableTypes objectAtIndex:itemToReselect] integerValue];
}
else {
if (selectedTableName) SPClear(selectedTableName);
selectedTableType = SPTableTypeNone;
}
#ifndef SP_CODA /* table list filtering */
// Determine whether or not to preserve the existing filter, and whether to
// show or hide the list filter based on the number of tables
if ([tables count] > 20) {
[self showFilter];
if (previousFilterString) {
[[listFilterField onMainThread] setStringValue:previousFilterString];
[[self onMainThread] updateFilter:self];
}
} else {
[self hideFilter];
}
// Set the filter placeholder text
if ([tableDocumentInstance database]) {
[[[listFilterField cell] onMainThread] setPlaceholderString:NSLocalizedString(@"Filter", @"filter label")];
}
#endif
if (previousSelectedTable) [previousSelectedTable release];
if (previousFilterString) [previousFilterString release];
// Query the structure of all databases in the background
if (sender == self)
// Invoked by SP
[NSThread detachNewThreadWithName:@"SPNavigatorController database structure querier" target:[tableDocumentInstance databaseStructureRetrieval] selector:@selector(queryDbStructureWithUserInfo:) object:nil];
else
// User press refresh button ergo force update
[NSThread detachNewThreadWithName:@"SPNavigatorController database structure querier" target:[tableDocumentInstance databaseStructureRetrieval] selector:@selector(queryDbStructureWithUserInfo:) object:@{@"forceUpdate" : @YES, @"cancelQuerying" : @YES}];
}
/**
* Adds a new table to the tables-array (no changes in mysql-db)
*/
- (IBAction)addTable:(id)sender
{
if ((![tableSourceInstance saveRowOnDeselect]) || (![tableContentInstance saveRowOnDeselect]) || (![tableDocumentInstance database])) return;
[[tableDocumentInstance parentWindow] endEditingFor:nil];
// Populate the table type (engine) popup button
[tableTypeButton removeAllItems];
NSArray *engines = [databaseDataInstance getDatabaseStorageEngines];
// Add default menu item
[tableTypeButton addItemWithTitle:[NSString stringWithFormat:NSLocalizedString(@"Default (%@)", @"New Table Sheet : Table Engine Dropdown : Default"), [databaseDataInstance getDatabaseDefaultStorageEngine]]];
[[tableTypeButton menu] addItem:[NSMenuItem separatorItem]];
for (NSDictionary *engine in engines)
{
[tableTypeButton addItemWithTitle:[engine objectForKey:@"Engine"]];
}
// Setup the charset and collation dropdowns
[addTableCharsetHelper setDatabaseData:databaseDataInstance];
[addTableCharsetHelper setServerSupport:[tableDocumentInstance serverSupport]];
[addTableCharsetHelper setPromoteUTF8:YES];
[addTableCharsetHelper setDefaultCharsetFormatString:NSLocalizedString(@"Inherit from database (%@)", @"New Table Sheet : Table Encoding Dropdown : Default inherited from database")];
[addTableCharsetHelper setDefaultCharset:[databaseDataInstance getDatabaseDefaultCharacterSet]];
[addTableCharsetHelper setDefaultCollation:[databaseDataInstance getDatabaseDefaultCollation]];
[addTableCharsetHelper setSelectedCharset:nil]; //reset to not carry over state from last time sheet was shown
[addTableCharsetHelper setSelectedCollation:nil];
[addTableCharsetHelper setEnabled:YES];
// Set the focus to the name field
[tableSheet makeFirstResponder:tableNameField];
[NSApp beginSheet:tableSheet
modalForWindow:[tableDocumentInstance parentWindow]
modalDelegate:self
didEndSelector:@selector(sheetDidEnd:returnCode:contextInfo:)
contextInfo:SPAddNewTable];
}
- (IBAction)tableEncodingButtonChanged:(id)sender
{
NSString *fmtStrDefaultId = NSLocalizedString(@"Default (%@)",@"Add Table : Collation : Default ($1 = collation name)");
NSString *fmtStrDefaultUnknown = NSLocalizedString(@"Default",@"Add Table Sheet : Collation : Default (unknown)"); // MySQL < 4.1.0
//throw out all items
[tableCollationButton removeAllItems];
//we'll enable that later if the user can actually change the selection.
[tableCollationButton setEnabled:NO];
/* logic below is as follows:
* if the database default charset is selected also use the database default collation
* regardless of default charset or not get the list of all collations that apply
* if a non-default charset is selected look out for it's default collation and promote that to the top as default
*
* Selecting a default charset (or collation) means that we don't want to specify one in the CREATE TABLE statement.
*/
//is the default charset currently selected?
BOOL isDefaultCharset = ([tableEncodingButton indexOfSelectedItem] == 0);
if(isDefaultCharset) {
NSString *defaultCollation = [databaseDataInstance getDatabaseDefaultCollation];
NSString *defaultItemTitle = (defaultCollation)? [NSString stringWithFormat:fmtStrDefaultId,defaultCollation] : fmtStrDefaultUnknown;
[tableCollationButton addItemWithTitle:defaultItemTitle];
//add the separator for the real items
[[tableCollationButton menu] addItem:[NSMenuItem separatorItem]];
}
//if the server actually has support for charsets & collations we will now get a list of all collations
//for the current charset. Even if the default charset is kept by the user he can change the default collation
//so we search in that case, too.
if(![[tableDocumentInstance serverSupport] supportsPost41CharacterSetHandling])
return;
//get the charset id the lazy way
NSString *charsetName = [[tableEncodingButton title] stringByMatching:@"\\((.*)\\)\\Z" capture:1L];
//this should not fail as even default is "Default (charset)" - if it does there's nothing we can do
if(!charsetName) {
NSLog(@"%s: Can't find charset id in encoding name <%@>. Format should be <Description (id)>.",__func__,[tableEncodingButton title]);
return;
}
//now let's get the list of collations for the selected charset id
NSArray *applicableCollations = [databaseDataInstance getDatabaseCollationsForEncoding:charsetName];
//got something?
if (![applicableCollations count])
return;
//add the real items
for (NSDictionary *collation in applicableCollations)
{
NSString *collationName = [collation objectForKey:@"COLLATION_NAME"];
[tableCollationButton addItemWithTitle:collationName];
//if this is not the server default charset let's find it's default collation too
if(!isDefaultCharset && [[collation objectForKey:@"IS_DEFAULT"] isEqualToString:@"Yes"]) {
NSString *defaultCollateTitle = [NSString stringWithFormat:fmtStrDefaultId,collationName];
//add it to the top of the list
[tableCollationButton insertItemWithTitle:defaultCollateTitle atIndex:0];
//add a separator underneath
[[tableCollationButton menu] insertItem:[NSMenuItem separatorItem] atIndex:1];
}
}
//reset selection to first item (it may moved when adding the default item)
[tableCollationButton selectItemAtIndex:0];
//yay, now there is actually something not the Default item, so we can enable the button
[tableCollationButton setEnabled:YES];
}
/**
* Closes the current sheet and stops the modal session
*/
- (IBAction)closeSheet:(id)sender
{
[NSApp endSheet:[sender window] returnCode:[sender tag]];
[[sender window] orderOut:self];
}
/**
* Invoked when user hits the remove button alert sheet to ask user if he really wants to delete the table.
*/
- (IBAction)removeTable:(id)sender
{
if (![tablesListView numberOfSelectedRows]) return;
[[tableDocumentInstance parentWindow] endEditingFor:nil];
NSAlert *alert = [NSAlert alertWithMessageText:@"" defaultButton:NSLocalizedString(@"Delete", @"delete button") alternateButton:NSLocalizedString(@"Cancel", @"cancel button") otherButton:nil informativeTextWithFormat:@""];
[alert setAlertStyle:NSCriticalAlertStyle];
NSArray *buttons = [alert buttons];
#ifndef SP_CODA
// Change the alert's cancel button to have the key equivalent of return
[[buttons objectAtIndex:0] setKeyEquivalent:@"d"];
[[buttons objectAtIndex:0] setKeyEquivalentModifierMask:NSCommandKeyMask];
[[buttons objectAtIndex:1] setKeyEquivalent:@"\r"];
#else
[[buttons objectAtIndex:0] setKeyEquivalent:@"\r"]; // Return = OK
[[buttons objectAtIndex:1] setKeyEquivalent:@"\e"]; // Esc = Cancel
#endif
NSIndexSet *indexes = [tablesListView selectedRowIndexes];
NSString *tblTypes = @"";
NSUInteger currentIndex = [indexes lastIndex];
if ([tablesListView numberOfSelectedRows] == 1) {
if ([[filteredTableTypes objectAtIndex:currentIndex] integerValue] == SPTableTypeView) {
tblTypes = NSLocalizedString(@"view", @"view");
}
else if ([[filteredTableTypes objectAtIndex:currentIndex] integerValue] == SPTableTypeTable) {
tblTypes = NSLocalizedString(@"table", @"table");
}
else if ([[filteredTableTypes objectAtIndex:currentIndex] integerValue] == SPTableTypeProc) {
tblTypes = NSLocalizedString(@"procedure", @"procedure");
}
else if ([[filteredTableTypes objectAtIndex:currentIndex] integerValue] == SPTableTypeFunc) {
tblTypes = NSLocalizedString(@"function", @"function");
}
[alert setMessageText:[NSString stringWithFormat:NSLocalizedString(@"Delete %@ '%@'?", @"delete table/view message"), tblTypes, [filteredTables objectAtIndex:[tablesListView selectedRow]]]];
[alert setInformativeText:[NSString stringWithFormat:NSLocalizedString(@"Are you sure you want to delete the %@ '%@'? This operation cannot be undone.", @"delete table/view informative message"), tblTypes, [filteredTables objectAtIndex:[tablesListView selectedRow]]]];
}
else {
BOOL areTableTypeEqual = YES;
NSInteger lastType = [[filteredTableTypes objectAtIndex:currentIndex] integerValue];
while (currentIndex != NSNotFound)
{
if ([[filteredTableTypes objectAtIndex:currentIndex] integerValue] != lastType) {
areTableTypeEqual = NO;
break;
}
currentIndex = [indexes indexLessThanIndex:currentIndex];
}
if (areTableTypeEqual)
{
switch (lastType) {
case SPTableTypeTable:
tblTypes = NSLocalizedString(@"tables", @"tables");
break;
case SPTableTypeView:
tblTypes = NSLocalizedString(@"views", @"views");
break;
case SPTableTypeProc:
tblTypes = NSLocalizedString(@"procedures", @"procedures");
break;
case SPTableTypeFunc:
tblTypes = NSLocalizedString(@"functions", @"functions");
break;
}
}
else {
tblTypes = NSLocalizedString(@"items", @"items");
}
[alert setMessageText:[NSString stringWithFormat:NSLocalizedString(@"Delete selected %@?", @"delete tables/views message"), tblTypes]];
[alert setInformativeText:[NSString stringWithFormat:NSLocalizedString(@"Are you sure you want to delete the selected %@? This operation cannot be undone.", @"delete tables/views informative message"), tblTypes]];
}
NSButton *button = [alert suppressionButton];
[button setTitle:NSLocalizedString(@"Force delete (disables integrity checks)", @"force table deletion button text")];
[button setToolTip:NSLocalizedString(@"Disables foreign key checks (FOREIGN_KEY_CHECKS) before deletion and re-enables them afterwards.", @"force table deltion button text tooltip")];
[button setFont:[NSFont systemFontOfSize:[NSFont smallSystemFontSize]]];
[[button cell] setControlSize:NSSmallControlSize];
[alert setShowsSuppressionButton:YES];
[alert beginSheetModalForWindow:[tableDocumentInstance parentWindow]
modalDelegate:self
didEndSelector:@selector(sheetDidEnd:returnCode:contextInfo:)
contextInfo:SPRemoveTable];
}
#ifndef SP_CODA /* whole table operations */
/**
* Copies a table/view/proc/func, if desired with content
*/
- (IBAction)copyTable:(id)sender
{
NSString *tableType = @"";
if ([tablesListView numberOfSelectedRows] != 1) return;
if (![tableSourceInstance saveRowOnDeselect] || ![tableContentInstance saveRowOnDeselect]) return;
[[tableDocumentInstance parentWindow] endEditingFor:nil];
// Detect table type: table or view
NSInteger tblType = [[filteredTableTypes objectAtIndex:[tablesListView selectedRow]] integerValue];
switch (tblType){
case SPTableTypeTable:
tableType = NSLocalizedString(@"table",@"table");
[copyTableContentSwitch setEnabled:YES];
break;
case SPTableTypeView:
tableType = NSLocalizedString(@"view",@"view");
[copyTableContentSwitch setEnabled:NO];
break;
case SPTableTypeProc:
tableType = NSLocalizedString(@"procedure",@"procedure");
[copyTableContentSwitch setEnabled:NO];
break;
case SPTableTypeFunc:
tableType = NSLocalizedString(@"function",@"function");
[copyTableContentSwitch setEnabled:NO];
break;
}
[copyTableMessageField setStringValue:[NSString stringWithFormat:NSLocalizedString(@"Duplicate %@ '%@' to:", @"duplicate object message"), tableType, [self tableName]]];
[copyTableNameField setStringValue:[NSString stringWithFormat:@"%@_copy", [filteredTables objectAtIndex:[tablesListView selectedRow]]]];
[copyTableContentSwitch setState:NSOffState];
[NSApp beginSheet:copyTableSheet
modalForWindow:[tableDocumentInstance parentWindow]
modalDelegate:self
didEndSelector:@selector(sheetDidEnd:returnCode:contextInfo:)
contextInfo:SPDuplicateTable];
}
/**
* This action starts editing the table name in the table list
*/
- (IBAction)renameTable:(id)sender
{
if ((![tableSourceInstance saveRowOnDeselect]) || (![tableContentInstance saveRowOnDeselect]) || (![tableDocumentInstance database])) {
return;
}
[[tableDocumentInstance parentWindow] endEditingFor:nil];
if ([tablesListView numberOfSelectedRows] != 1) return;
if (![[self tableName] length]) return;
[tablesListView editColumn:0 row:[tablesListView selectedRow] withEvent:nil select:YES];
}
/**
* Truncates the currently selected table(s).
*/
- (IBAction)truncateTable:(id)sender
{
if (![tablesListView numberOfSelectedRows])
return;
[[tableDocumentInstance parentWindow] endEditingFor:nil];
NSAlert *alert = [NSAlert alertWithMessageText:@""
defaultButton:NSLocalizedString(@"Truncate", @"truncate button")
alternateButton:NSLocalizedString(@"Cancel", @"cancel button")
otherButton:nil
informativeTextWithFormat:@""];
[alert setAlertStyle:NSCriticalAlertStyle];
NSArray *buttons = [alert buttons];
// Change the alert's cancel button to have the key equivalent of return
[[buttons objectAtIndex:0] setKeyEquivalent:@"t"];
[[buttons objectAtIndex:0] setKeyEquivalentModifierMask:NSCommandKeyMask];
[[buttons objectAtIndex:1] setKeyEquivalent:@"\r"];
if ([tablesListView numberOfSelectedRows] == 1) {
[alert setMessageText:[NSString stringWithFormat:NSLocalizedString(@"Truncate table '%@'?", @"truncate table message"), [filteredTables objectAtIndex:[tablesListView selectedRow]]]];
[alert setInformativeText:[NSString stringWithFormat:NSLocalizedString(@"Are you sure you want to delete ALL records in the table '%@'? This operation cannot be undone.", @"truncate table informative message"), [filteredTables objectAtIndex:[tablesListView selectedRow]]]];
}
else {
[alert setMessageText:NSLocalizedString(@"Truncate selected tables?", @"truncate tables message")];
[alert setInformativeText:NSLocalizedString(@"Are you sure you want to delete ALL records in the selected tables? This operation cannot be undone.", @"truncate tables informative message")];
}
[alert beginSheetModalForWindow:[tableDocumentInstance parentWindow] modalDelegate:self didEndSelector:@selector(sheetDidEnd:returnCode:contextInfo:) contextInfo:SPTruncateTable];
}
/**
* Open the table in a new tab.
*/
- (IBAction)openTableInNewTab:(id)sender
{
// Add a new tab to the window
[[[tableDocumentInstance parentWindow] windowController] addNewConnection:self];
[self _duplicateConnectionToFrontTab];
}
- (void)_duplicateConnectionToFrontTab
{
// Get the state of the document
NSDictionary *allStateDetails = @{
@"connection" : @YES,
@"history" : @YES,
@"session" : @YES,
@"query" : @YES,
@"password" : @YES
};
NSMutableDictionary *documentState = [NSMutableDictionary dictionaryWithDictionary:[tableDocumentInstance stateIncludingDetails:allStateDetails]];
// Ensure it's set to autoconnect
[documentState setObject:@YES forKey:@"auto_connect"];
// Set the connection on the new tab
[[SPAppDelegate frontDocument] setState:documentState];
}
- (IBAction)openTableInNewWindow:(id)sender
{
//create new window
[SPAppDelegate newWindow:self];
[self _duplicateConnectionToFrontTab];
}
/**
* Toggle whether the splitview is collapsed.
*/
- (IBAction)togglePaneCollapse:(id)sender
{
[tableListSplitView toggleCollapse:sender];
[[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithBool:[tableListSplitView isCollapsibleSubviewCollapsed]] forKey:SPTableInformationPanelCollapsed];
}
#endif
#pragma mark -
#pragma mark Alert sheet methods
/**
* Method for alert sheets.
*/
- (void)sheetDidEnd:(id)sheet returnCode:(NSInteger)returnCode contextInfo:(NSString *)contextInfo
{
// Order out current sheet to suppress overlapping of sheets
if ([sheet respondsToSelector:@selector(orderOut:)]) {
[sheet orderOut:nil];
}
else if ([sheet respondsToSelector:@selector(window)]) {
[[sheet window] orderOut:nil];
}
if ([contextInfo isEqualToString:SPAddRow]) {
alertSheetOpened = NO;
}
else if ([contextInfo isEqualToString:SPRemoveTable]) {
if (returnCode == NSAlertDefaultReturn) {
[self performSelector:@selector(_removeTable:)
withObject:[NSNumber numberWithInteger:[[(NSAlert *)sheet suppressionButton] state]]
afterDelay:0.0];
}
}
#ifndef SP_CODA
else if ([contextInfo isEqualToString:SPTruncateTable]) {
if (returnCode == NSAlertDefaultReturn) {
[self _truncateTable];
}
}
else
#endif
if ([contextInfo isEqualToString:SPAddNewTable]) {
[addTableCharsetHelper setEnabled:NO];
if (returnCode == NSOKButton) {
[self _addTable];
}
}
#ifndef SP_CODA
else if ([contextInfo isEqualToString:SPDuplicateTable]) {
if (returnCode == NSOKButton) {
[self _copyTable];
}
}
#endif
}
#pragma mark -
#pragma mark Additional methods
/**
* Sets the connection (received from SPDatabaseDocument) and makes things that have to be done only once
*/
- (void)setConnection:(SPMySQLConnection *)theConnection
{
mySQLConnection = theConnection;
[self updateTables:self];
}
/**
* Performs interface validation for various controls.
*/
- (void)controlTextDidChange:(NSNotification *)notification
{
id object = [notification object];
if (object == tableNameField) {
[addTableButton setEnabled:[self isTableNameValid:[tableNameField stringValue] forType: SPTableTypeTable]];
}
#ifndef SP_CODA
else if (object == copyTableNameField) {
[copyTableButton setEnabled:[self isTableNameValid:[copyTableNameField stringValue] forType:[self tableType]]];
}
#endif
}
/**
* Controls the NSTextField's press RETURN event of Add/Rename/Duplicate sheets
*/
- (void)controlTextDidEndEditing:(NSNotification *)notification
{
id object = [notification object];
// Only RETURN/ENTER will be recognized for Add/Rename/Duplicate sheets to
// activate the Add/Rename/Duplicate buttons
if([[[notification userInfo] objectForKey:@"NSTextMovement"] integerValue] != 0)
return;
if (object == tableNameField) {
[addTableButton performClick:object];
}
#ifndef SP_CODA
else if (object == copyTableNameField) {
[copyTableButton performClick:object];
}
#endif
}
/**
* Updates application state to match the current selection, including
* updating the interface selection if appropriate.
* Takes a dictionary of selection details, containing the selection name
* and type, and updates stored variables and the table list interface to
* match.
* Should be called on the main thread.
*/
- (void)setSelectionState:(NSDictionary *)selectionDetails
{
// First handle empty or multiple selections
if (!selectionDetails || ![selectionDetails objectForKey:@"name"]) {
#ifndef SP_CODA
NSIndexSet *indexes = [tablesListView selectedRowIndexes];
#endif
// Update the selected table name and type
if (selectedTableName) SPClear(selectedTableName);
#ifndef SP_CODA /* ui manipulation */
// Set gear menu items Remove/Duplicate table/view according to the table types
// if at least one item is selected
if ([indexes count]) {
NSUInteger currentIndex = [indexes lastIndex];
BOOL areTableTypeEqual = YES;
NSInteger lastType = [[filteredTableTypes objectAtIndex:currentIndex] integerValue];
while (currentIndex != NSNotFound)
{
if ([[filteredTableTypes objectAtIndex:currentIndex] integerValue] != lastType) {
areTableTypeEqual = NO;
break;
}
currentIndex = [indexes indexLessThanIndex:currentIndex];
}
if (areTableTypeEqual) {
switch (lastType)
{
case SPTableTypeTable:
[removeTableMenuItem setTitle:NSLocalizedString(@"Delete Tables", @"delete tables menu title")];
[truncateTableButton setTitle:NSLocalizedString(@"Truncate Tables", @"truncate tables menu item")];
[removeTableContextMenuItem setTitle:NSLocalizedString(@"Delete Tables", @"delete tables menu title")];
[truncateTableContextMenuItem setTitle:NSLocalizedString(@"Truncate Tables", @"truncate tables menu item")];
[truncateTableButton setHidden:NO];
[truncateTableContextMenuItem setHidden:NO];
break;
case SPTableTypeView:
[removeTableMenuItem setTitle:NSLocalizedString(@"Delete Views", @"delete views menu title")];
[removeTableContextMenuItem setTitle:NSLocalizedString(@"Delete Views", @"delete views menu title")];
[truncateTableButton setHidden:YES];
[truncateTableContextMenuItem setHidden:YES];
break;
case SPTableTypeProc:
[removeTableMenuItem setTitle:NSLocalizedString(@"Delete Procedures", @"delete procedures menu title")];
[removeTableContextMenuItem setTitle:NSLocalizedString(@"Delete Procedures", @"delete procedures menu title")];
[truncateTableButton setHidden:YES];
[truncateTableContextMenuItem setHidden:YES];
break;
case SPTableTypeFunc:
[removeTableMenuItem setTitle:NSLocalizedString(@"Delete Functions", @"delete functions menu title")];
[removeTableContextMenuItem setTitle:NSLocalizedString(@"Delete Functions", @"delete functions menu title")];
[truncateTableButton setHidden:YES];
[truncateTableContextMenuItem setHidden:YES];
break;
}
} else {
[removeTableMenuItem setTitle:NSLocalizedString(@"Delete Items", @"delete items menu title")];
[removeTableContextMenuItem setTitle:NSLocalizedString(@"Delete Items", @"delete items menu title")];
[truncateTableButton setHidden:YES];
[truncateTableContextMenuItem setHidden:YES];
}
}
// Context menu
[renameTableContextMenuItem setHidden:YES];
[openTableInNewTabContextMenuItem setHidden:YES];
[openTableInNewWindowContextMenuItem setHidden:YES];
[separatorTableContextMenuItem3 setHidden:YES];
[duplicateTableContextMenuItem setHidden:YES];
[separatorTableContextMenuItem setHidden:YES];
[separatorTableContextMenuItem2 setHidden:NO];
[showCreateSyntaxContextMenuItem setTitle:NSLocalizedString(@"Show Create Syntaxes...", @"show create syntaxes menu item")];
[showCreateSyntaxContextMenuItem setHidden:NO];
[copyCreateSyntaxContextMenuItem setTitle:NSLocalizedString(@"Copy Create Syntaxes",@"Table List : Context Menu : Copy CREATE syntax (multiple selection)")];
[copyCreateSyntaxContextMenuItem setHidden:NO];
// 'Gear' menu
[renameTableMenuItem setHidden:YES];
[openTableInNewTabMenuItem setHidden:YES];
[openTableInNewWindowMenuItem setHidden:YES];
[separatorTableMenuItem3 setHidden:YES];
[duplicateTableMenuItem setHidden:YES];
[separatorTableMenuItem setHidden:YES];
[separatorTableMenuItem2 setHidden:NO];
[showCreateSyntaxMenuItem setTitle:NSLocalizedString(@"Show Create Syntaxes...", @"show create syntaxes menu item")];
[showCreateSyntaxMenuItem setHidden:NO];
[copyCreateSyntaxMenuItem setTitle:NSLocalizedString(@"Copy Create Syntaxes", @"Table List : Gear Menu : Copy CREATE syntax (multiple selection)")];
[copyCreateSyntaxMenuItem setHidden:NO];
// Get main menu "Table"'s submenu
NSMenu *tableSubMenu = [[[NSApp mainMenu] itemWithTag:SPMainMenuTable] submenu];
[[tableSubMenu itemAtIndex:4] setTitle:NSLocalizedString(@"Copy Create Syntaxes", @"copy create syntaxes menu item")];
[[tableSubMenu itemAtIndex:5] setTitle:NSLocalizedString(@"Show Create Syntaxes...", @"show create syntaxes menu item")];
[[tableSubMenu itemAtIndex:7] setTitle:NSLocalizedString(@"Check Selected Items", @"check selected items menu item")];
[[tableSubMenu itemAtIndex:8] setTitle:NSLocalizedString(@"Repair Selected Items", @"repair selected items menu item")];
[[tableSubMenu itemAtIndex:10] setTitle:NSLocalizedString(@"Analyze Selected Items", @"analyze selected items menu item")];
[[tableSubMenu itemAtIndex:11] setTitle:NSLocalizedString(@"Optimize Selected Items", @"optimize selected items menu item")];
[[tableSubMenu itemAtIndex:12] setTitle:NSLocalizedString(@"Flush Selected Items", @"flush selected items menu item")];
[[tableSubMenu itemAtIndex:13] setTitle:NSLocalizedString(@"Checksum Selected Items", @"checksum selected items menu item")];
[[tableSubMenu itemAtIndex:4] setHidden:NO];
[[tableSubMenu itemAtIndex:5] setHidden:NO];
[[tableSubMenu itemAtIndex:6] setHidden:NO];
[[tableSubMenu itemAtIndex:7] setHidden:NO];
[[tableSubMenu itemAtIndex:8] setHidden:NO];
[[tableSubMenu itemAtIndex:9] setHidden:NO];
[[tableSubMenu itemAtIndex:10] setHidden:NO];
[[tableSubMenu itemAtIndex:11] setHidden:NO];
#endif
return;
}
// If a new selection has been provided, store variables and update the interface to match
NSString *selectedItemName = [selectionDetails objectForKey:@"name"];
SPTableType selectedItemType = (SPTableType)[[selectionDetails objectForKey:@"type"] integerValue];
// Update the selected table name and type
if (selectedTableName) [selectedTableName release];
selectedTableName = [[NSString alloc] initWithString:selectedItemName];
selectedTableType = selectedItemType;
#ifndef SP_CODA /* ui manipulation */
// Remove the "current selection" item for filtered lists if appropriate
if (isTableListFiltered && [tablesListView selectedRow] < (NSInteger)[filteredTables count] - 2 && [filteredTables count] > 2
&& [[filteredTableTypes objectAtIndex:[filteredTableTypes count]-2] integerValue] == SPTableTypeNone
&& [[filteredTables objectAtIndex:[filteredTables count]-2] isEqualToString:NSLocalizedString(@"CURRENT SELECTION",@"header for current selection in filtered list")])
{
[filteredTables removeObjectsInRange:NSMakeRange([filteredTables count]-2, 2)];
[filteredTableTypes removeObjectsInRange:NSMakeRange([filteredTableTypes count]-2, 2)];
[tablesListView reloadData];
}
// Show menu separators
[separatorTableMenuItem setHidden:NO];
[separatorTableContextMenuItem setHidden:NO];