/
SPDatabaseDocument.m
6340 lines (5291 loc) · 233 KB
/
SPDatabaseDocument.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
//
// SPDatabaseDocument.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>
// Forward-declare for 10.7 compatibility
#if !defined(MAC_OS_X_VERSION_10_7) || MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_7
enum {
NSFullScreenWindowMask = 1 << 14
};
#endif
#import "SPDatabaseDocument.h"
#import "SPConnectionController.h"
#import "SPConnectionHandler.h"
#import "SPConnectionControllerInitializer.h"
#import "SPTablesList.h"
#import "SPTableStructure.h"
#import "SPDatabaseStructure.h"
#ifndef SP_CODA /* headers */
#import "SPFileHandle.h"
#import "SPKeychain.h"
#import "SPTableContent.h"
#import "SPTableContentFilter.h"
#import "SPCustomQuery.h"
#import "SPDataImport.h"
#import "ImageAndTextCell.h"
#import "SPGrowlController.h"
#import "SPExportController.h"
#import "SPSplitView.h"
#endif
#import "SPQueryController.h"
#import "SPQueryDocumentsController.h"
#ifndef SP_CODA /* headers */
#import "SPWindowController.h"
#endif
#import "SPNavigatorController.h"
#ifndef SP_CODA /* headers */
#import "SPSQLParser.h"
#import "SPTableData.h"
#endif
#import "SPDatabaseData.h"
#import "SPDatabaseStructure.h"
#ifndef SP_CODA /* headers */
#import "SPAppController.h"
#import "SPWindowManagement.h"
#import "SPExtendedTableInfo.h"
#import "SPHistoryController.h"
#import "SPPreferenceController.h"
#import "SPUserManager.h"
#import "SPEncodingPopupAccessory.h"
#import "YRKSpinningProgressIndicator.h"
#import "SPProcessListController.h"
#import "SPServerVariablesController.h"
#import "SPAlertSheets.h"
#import "SPLogger.h"
#import "SPDatabaseCopy.h"
#import "SPTableCopy.h"
#import "SPDatabaseRename.h"
#import "SPTableRelations.h"
#import "SPCopyTable.h"
#endif
#import "SPServerSupport.h"
#ifndef SP_CODA /* headers */
#import "SPTooltip.h"
#endif
#import "SPDatabaseViewController.h"
#ifndef SP_CODA /* headers */
#import "SPBundleHTMLOutputController.h"
#import "SPConnectionDelegate.h"
#endif
#import "SPThreadAdditions.h"
#import "RegexKitLite.h"
#import "SPTextView.h"
#import "SPFavoriteColorSupport.h"
#ifdef SP_CODA /* headers */
#import "SPAlertSheets.h"
#import "NSNotificationCenterThreadingAdditions.h"
#import "SPCustomQuery.h"
#import "SPDatabaseRename.h"
#endif
#import "SPCharsetCollationHelper.h"
#import "SPGotoDatabaseController.h"
#import <SPMySQL/SPMySQL.h>
// Constants
static NSString *SPRenameDatabaseAction = @"SPRenameDatabase";
static NSString *SPAlterDatabaseAction = @"SPAlterDatabase";
@interface SPDatabaseDocument ()
- (void)_addDatabase;
- (void)_alterDatabase;
#ifndef SP_CODA /* method decls */
- (void)_copyDatabase;
#endif
- (void)_renameDatabase;
- (void)_removeDatabase;
- (void)_selectDatabaseAndItem:(NSDictionary *)selectionDetails;
#ifndef SP_CODA /* method decls */
- (void)_processDatabaseChangedBundleTriggerActions;
#endif
@end
@implementation SPDatabaseDocument
#ifndef SP_CODA /* ivars */
@synthesize sqlFileURL;
@synthesize sqlFileEncoding;
@synthesize parentWindowController;
@synthesize parentTabViewItem;
#endif
@synthesize isProcessing;
@synthesize serverSupport;
@synthesize databaseStructureRetrieval;
#ifndef SP_CODA /* ivars */
@synthesize processID;
#endif
#ifdef SP_CODA /* ivars */
@synthesize allDatabases;
@synthesize delegate;
@synthesize tableDataInstance;
@synthesize customQueryInstance;
@synthesize queryProgressBar;
@synthesize databaseSheet;
@synthesize databaseNameField;
@synthesize databaseEncodingButton;
@synthesize addDatabaseButton;
@synthesize databaseDataInstance;
@synthesize databaseRenameSheet;
@synthesize databaseRenameNameField;
@synthesize renameDatabaseButton;
@synthesize chooseDatabaseButton;
@synthesize structureContentSwitcher;
#endif
#pragma mark -
- (id)init
{
if ((self = [super init])) {
#ifndef SP_CODA /* init ivars */
_mainNibLoaded = NO;
#endif
_isConnected = NO;
_isWorkingLevel = 0;
_isSavedInBundle = NO;
_supportsEncoding = NO;
databaseListIsSelectable = YES;
_queryMode = SPInterfaceQueryMode;
chooseDatabaseButton = nil;
#ifndef SP_CODA /* init ivars */
chooseDatabaseToolbarItem = nil;
#endif
connectionController = nil;
selectedTableName = nil;
selectedTableType = SPTableTypeNone;
structureLoaded = NO;
contentLoaded = NO;
statusLoaded = NO;
triggersLoaded = NO;
relationsLoaded = NO;
selectedDatabase = nil;
selectedDatabaseEncoding = [[NSString alloc] initWithString:@"latin1"];
mySQLConnection = nil;
mySQLVersion = nil;
allDatabases = nil;
allSystemDatabases = nil;
gotoDatabaseController = nil;
#ifndef SP_CODA /* init ivars */
mainToolbar = nil;
parentWindow = nil;
#endif
isProcessing = NO;
#ifndef SP_CODA /* init ivars */
printWebView = [[WebView alloc] init];
[printWebView setFrameLoadDelegate:self];
prefs = [NSUserDefaults standardUserDefaults];
undoManager = [[NSUndoManager alloc] init];
#endif
queryEditorInitString = nil;
#ifndef SP_CODA
sqlFileURL = nil;
spfFileURL = nil;
spfSession = nil;
spfPreferences = [[NSMutableDictionary alloc] init];
spfDocData = [[NSMutableDictionary alloc] init];
runningActivitiesArray = [[NSMutableArray alloc] init];
#endif
titleAccessoryView = nil;
#ifndef SP_CODA /* init ivars */
taskProgressWindow = nil;
taskDisplayIsIndeterminate = YES;
taskDisplayLastValue = 0;
taskProgressValue = 0;
taskProgressValueDisplayInterval = 1;
taskDrawTimer = nil;
taskFadeInStartDate = nil;
taskCanBeCancelled = NO;
taskCancellationCallbackObject = nil;
taskCancellationCallbackSelector = NULL;
#endif
alterDatabaseCharsetHelper = nil; //init in awakeFromNib
addDatabaseCharsetHelper = nil;
keyChainID = nil;
#ifndef SP_CODA /* init ivars */
statusValues = nil;
printThread = nil;
windowTitleStatusViewIsVisible = NO;
nibObjectsToRelease = [[NSMutableArray alloc] init];
// As this object is not an NSWindowController subclass, top-level objects in loaded nibs aren't
// automatically released. Keep track of the top-level objects for release on dealloc.
NSArray *dbViewTopLevelObjects = nil;
NSNib *nibLoader = [[NSNib alloc] initWithNibNamed:@"DBView" bundle:[NSBundle mainBundle]];
[nibLoader instantiateNibWithOwner:self topLevelObjects:&dbViewTopLevelObjects];
[nibLoader release];
[nibObjectsToRelease addObjectsFromArray:dbViewTopLevelObjects];
#endif
databaseStructureRetrieval = [[SPDatabaseStructure alloc] initWithDelegate:self];
}
return self;
}
- (void)awakeFromNib
{
#ifndef SP_CODA
if (_mainNibLoaded) return;
_mainNibLoaded = YES;
// Set up the toolbar
[self setupToolbar];
// Set collapsible behaviour on the table list so collapsing behaviour handles resize issus
[contentViewSplitter setCollapsibleSubviewIndex:0];
// Set up the connection controller
connectionController = [[SPConnectionController alloc] initWithDocument:self];
// Set the connection controller's delegate
[connectionController setDelegate:self];
// Register observers for when the DisplayTableViewVerticalGridlines preference changes
[prefs addObserver:self forKeyPath:SPDisplayTableViewVerticalGridlines options:NSKeyValueObservingOptionNew context:NULL];
[prefs addObserver:tableSourceInstance forKeyPath:SPDisplayTableViewVerticalGridlines options:NSKeyValueObservingOptionNew context:NULL];
[prefs addObserver:tableContentInstance forKeyPath:SPDisplayTableViewVerticalGridlines options:NSKeyValueObservingOptionNew context:NULL];
[prefs addObserver:customQueryInstance forKeyPath:SPDisplayTableViewVerticalGridlines options:NSKeyValueObservingOptionNew context:NULL];
[prefs addObserver:tableRelationsInstance forKeyPath:SPDisplayTableViewVerticalGridlines options:NSKeyValueObservingOptionNew context:NULL];
[prefs addObserver:[SPQueryController sharedQueryController] forKeyPath:SPDisplayTableViewVerticalGridlines options:NSKeyValueObservingOptionNew context:NULL];
// Register observers for the when the UseMonospacedFonts preference changes
[prefs addObserver:tableSourceInstance forKeyPath:SPUseMonospacedFonts options:NSKeyValueObservingOptionNew context:NULL];
[prefs addObserver:[SPQueryController sharedQueryController] forKeyPath:SPUseMonospacedFonts options:NSKeyValueObservingOptionNew context:NULL];
[prefs addObserver:tableContentInstance forKeyPath:SPGlobalResultTableFont options:NSKeyValueObservingOptionNew context:NULL];
[prefs addObserver:tableContentInstance forKeyPath:SPDisplayBinaryDataAsHex options:NSKeyValueObservingOptionNew context:NULL];
// Register observers for when the logging preference changes
[prefs addObserver:[SPQueryController sharedQueryController] forKeyPath:SPConsoleEnableLogging options:NSKeyValueObservingOptionNew context:NULL];
// Register a second observer for when the logging preference changes so we can tell the current connection about it
[prefs addObserver:self forKeyPath:SPConsoleEnableLogging options:NSKeyValueObservingOptionNew context:NULL];
#endif
// Register for notifications
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(willPerformQuery:)
name:@"SMySQLQueryWillBePerformed" object:self];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(hasPerformedQuery:)
name:@"SMySQLQueryHasBeenPerformed" object:self];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillTerminate:)
name:@"NSApplicationWillTerminateNotification" object:nil];
#ifndef SP_CODA
// Find the Database -> Database Encoding menu (it's not in our nib, so we can't use interface builder)
selectEncodingMenu = [[[[[NSApp mainMenu] itemWithTag:SPMainMenuDatabase] submenu] itemWithTag:1] submenu];
// Hide the tabs in the tab view (we only show them to allow switching tabs in interface builder)
[tableTabView setTabViewType:NSNoTabsNoBorder];
// Hide the activity list
[self setActivityPaneHidden:[NSNumber numberWithInteger:1]];
// Load additional nibs, keeping track of the top-level objects to allow correct release
NSArray *connectionDialogTopLevelObjects = nil;
NSNib *nibLoader = [[NSNib alloc] initWithNibNamed:@"ConnectionErrorDialog" bundle:[NSBundle mainBundle]];
if (![nibLoader instantiateNibWithOwner:self topLevelObjects:&connectionDialogTopLevelObjects]) {
NSLog(@"Connection error dialog could not be loaded; connection failure handling will not function correctly.");
} else {
[nibObjectsToRelease addObjectsFromArray:connectionDialogTopLevelObjects];
}
[nibLoader release];
// SP_CODA can't use progress indicator because of BWToolkit dependency
NSArray *progressIndicatorLayerTopLevelObjects = nil;
nibLoader = [[NSNib alloc] initWithNibNamed:@"ProgressIndicatorLayer" bundle:[NSBundle mainBundle]];
if (![nibLoader instantiateNibWithOwner:self topLevelObjects:&progressIndicatorLayerTopLevelObjects]) {
NSLog(@"Progress indicator layer could not be loaded; progress display will not function correctly.");
} else {
[nibObjectsToRelease addObjectsFromArray:progressIndicatorLayerTopLevelObjects];
}
[nibLoader release];
// Retain the icon accessory view to allow it to be added and removed from windows
[titleAccessoryView retain];
#endif
#ifndef SP_CODA
// Set up the progress indicator child window and layer - change indicator color and size
[taskProgressIndicator setForeColor:[NSColor whiteColor]];
NSShadow *progressIndicatorShadow = [[NSShadow alloc] init];
[progressIndicatorShadow setShadowOffset:NSMakeSize(1.0f, -1.0f)];
[progressIndicatorShadow setShadowBlurRadius:1.0f];
[progressIndicatorShadow setShadowColor:[NSColor colorWithCalibratedWhite:0.0f alpha:0.75f]];
[taskProgressIndicator setShadow:progressIndicatorShadow];
[progressIndicatorShadow release];
taskProgressWindow = [[NSWindow alloc] initWithContentRect:[taskProgressLayer bounds] styleMask:NSBorderlessWindowMask backing:NSBackingStoreBuffered defer:NO];
[taskProgressWindow setReleasedWhenClosed:NO];
[taskProgressWindow setOpaque:NO];
[taskProgressWindow setBackgroundColor:[NSColor clearColor]];
[taskProgressWindow setAlphaValue:0.0f];
[taskProgressWindow setContentView:taskProgressLayer];
[self updateTitlebarStatusVisibilityForcingHide:NO];
#endif
alterDatabaseCharsetHelper = [[SPCharsetCollationHelper alloc] initWithCharsetButton:databaseAlterEncodingButton CollationButton:databaseAlterCollationButton];
addDatabaseCharsetHelper = [[SPCharsetCollationHelper alloc] initWithCharsetButton:databaseEncodingButton CollationButton:databaseCollationButton];
}
#pragma mark -
#ifdef SP_CODA /* glue */
- (SPConnectionController*)createConnectionController
{
// Set up the connection controller
connectionController = [[SPConnectionController alloc] initWithDocument:self];
// Set the connection controller's delegate
[connectionController setDelegate:self];
return connectionController;
}
- (void)setTableSourceInstance:(SPTableStructure*)source
{
tableSourceInstance = source;
}
- (void)setTableContentInstance:(SPTableContent*)content
{
tableContentInstance = content;
}
#endif
#ifndef SP_CODA /* password sheet and history navigation */
/**
* Set the return code for entering the encryption passowrd sheet
*/
- (IBAction)closePasswordSheet:(id)sender
{
passwordSheetReturnCode = 0;
if([sender tag]) {
[NSApp stopModal];
passwordSheetReturnCode = 1;
}
[NSApp abortModal];
}
/**
* Go backward or forward in the history depending on the menu item selected.
*/
- (IBAction)backForwardInHistory:(id)sender
{
// Ensure history navigation is permitted - trigger end editing and any required saves
if (![self couldCommitCurrentViewActions]) return;
switch ([sender tag])
{
// Go backward
case 0:
[spHistoryControllerInstance goBackInHistory];
break;
// Go forward
case 1:
[spHistoryControllerInstance goForwardInHistory];
break;
}
}
#endif
#pragma mark -
#pragma mark Connection callback and methods
- (void)setConnection:(SPMySQLConnection *)theConnection
{
if ([theConnection userTriggeredDisconnect]) {
return;
}
_isConnected = YES;
mySQLConnection = [theConnection retain];
// Now that we have a connection, determine what functionality the database supports.
// Note that this must be done before anything else as it's used by nearly all of the main controllers.
serverSupport = [[SPServerSupport alloc] initWithMajorVersion:[mySQLConnection serverMajorVersion]
minor:[mySQLConnection serverMinorVersion]
release:[mySQLConnection serverReleaseVersion]];
#ifndef SP_CODA
// Set the fileURL and init the preferences (query favs, filters, and history) if available for that URL
[self setFileURL:[[SPQueryController sharedQueryController] registerDocumentWithFileURL:[self fileURL] andContextInfo:spfPreferences]];
// ...but hide the icon while the document is temporary
if ([self isUntitled]) [[parentWindow standardWindowButton:NSWindowDocumentIconButton] setImage:nil];
#endif
// Get the mysql version
mySQLVersion = [[NSString alloc] initWithString:[mySQLConnection serverVersionString]];
// Update the selected database if appropriate
if ([connectionController database] && ![[connectionController database] isEqualToString:@""]) {
if (selectedDatabase) [selectedDatabase release], selectedDatabase = nil;
selectedDatabase = [[NSString alloc] initWithString:[connectionController database]];
#ifndef SP_CODA /* [spHistoryControllerInstance updateHistoryEntries] */
[spHistoryControllerInstance updateHistoryEntries];
#endif
}
// Ensure the connection encoding is set to utf8 for database/table name retrieval
[mySQLConnection setEncoding:@"utf8"];
// Update the database list
[self setDatabases:self];
[chooseDatabaseButton setEnabled:!_isWorkingLevel];
// Set the connection on the database structure builder
[databaseStructureRetrieval setConnectionToClone:mySQLConnection];
[databaseDataInstance setConnection:mySQLConnection];
// Pass the support class to the data instance
[databaseDataInstance setServerSupport:serverSupport];
#ifdef SP_CODA /* glue */
tablesListInstance = [[SPTablesList alloc] init];
[tablesListInstance setDatabaseDocument:self];
[tablesListInstance awakeFromNib];
#endif
// Set the connection on the tables list instance - this updates the table list while the connection
// is still UTF8
[tablesListInstance setConnection:mySQLConnection];
#ifndef SP_CODA /* set connection encoding from prefs */
// Set the connection encoding if necessary
NSNumber *encodingType = [prefs objectForKey:SPDefaultEncoding];
if ([encodingType intValue] != SPEncodingAutodetect) {
[self setConnectionEncoding:[self mysqlEncodingFromEncodingTag:encodingType] reloadingViews:NO];
} else {
#endif
[[self onMainThread] updateEncodingMenuWithSelectedEncoding:[self encodingTagFromMySQLEncoding:[mySQLConnection encoding]]];
#ifndef SP_CODA
}
#endif
// For each of the main controllers, assign the current connection
[tableSourceInstance setConnection:mySQLConnection];
[tableContentInstance setConnection:mySQLConnection];
[tableRelationsInstance setConnection:mySQLConnection];
[tableTriggersInstance setConnection:mySQLConnection];
[customQueryInstance setConnection:mySQLConnection];
[tableDumpInstance setConnection:mySQLConnection];
#ifndef SP_CODA
[exportControllerInstance setConnection:mySQLConnection];
#endif
[tableDataInstance setConnection:mySQLConnection];
[extendedTableInfoInstance setConnection:mySQLConnection];
// Set the custom query editor's MySQL version
[customQueryInstance setMySQLversion:mySQLVersion];
#ifndef SP_CODA
[self updateWindowTitle:self];
// Connected Growl notification
NSString *serverDisplayName = nil;
if ([parentWindowController selectedTableDocument] == self) {
serverDisplayName = [parentWindow title];
} else {
serverDisplayName = [parentTabViewItem label];
}
[[SPGrowlController sharedGrowlController] notifyWithTitle:@"Connected"
description:[NSString stringWithFormat:NSLocalizedString(@"Connected to %@",@"description for connected growl notification"), serverDisplayName]
document:self
notificationName:@"Connected"];
// Init Custom Query editor with the stored queries in a spf file if given.
[spfDocData setObject:[NSNumber numberWithBool:NO] forKey:@"save_editor_content"];
if (spfSession != nil && [spfSession objectForKey:@"queries"]) {
[spfDocData setObject:[NSNumber numberWithBool:YES] forKey:@"save_editor_content"];
if ([[spfSession objectForKey:@"queries"] isKindOfClass:[NSData class]]) {
NSString *q = [[NSString alloc] initWithData:[[spfSession objectForKey:@"queries"] decompress] encoding:NSUTF8StringEncoding];
[self initQueryEditorWithString:q];
[q release];
}
else
[self initQueryEditorWithString:[spfSession objectForKey:@"queries"]];
}
// Insert queryEditorInitString into the Query Editor if defined
if (queryEditorInitString && [queryEditorInitString length]) {
[self viewQuery:self];
[customQueryInstance doPerformLoadQueryService:queryEditorInitString];
[queryEditorInitString release];
queryEditorInitString = nil;
}
if (spfSession != nil) {
// Restore vertical split view divider for tables' list and right view (Structure, Content, etc.)
if([spfSession objectForKey:@"windowVerticalDividerPosition"])
[contentViewSplitter setPosition:[[spfSession objectForKey:@"windowVerticalDividerPosition"] floatValue] ofDividerAtIndex:0];
// Start a task to restore the session details
[self startTaskWithDescription:NSLocalizedString(@"Restoring session...", @"Restoring session task description")];
if ([NSThread isMainThread])
[NSThread detachNewThreadWithName:@"SPDatabaseDocument session load task" target:self selector:@selector(restoreSession) object:nil];
else
[self restoreSession];
}
else {
switch ([prefs integerForKey:SPDefaultViewMode] > 0 ? [prefs integerForKey:SPDefaultViewMode] : [prefs integerForKey:SPLastViewMode]) {
default:
case SPStructureViewMode:
[self viewStructure:self];
break;
case SPContentViewMode:
[self viewContent:self];
break;
case SPRelationsViewMode:
[self viewRelations:self];
break;
case SPTableInfoViewMode:
[self viewStatus:self];
break;
case SPQueryEditorViewMode:
[self viewQuery:self];
break;
case SPTriggersViewMode:
[self viewTriggers:self];
break;
}
}
if ([self database]) [self detectDatabaseEncoding];
// If not on the query view, alter initial focus - set focus to table list filter
// field if visible, otherwise set focus to Table List view
if (![[self selectedToolbarItemIdentifier] isEqualToString:SPMainToolbarCustomQuery]) {
[[tablesListInstance onMainThread] makeTableListFilterHaveFocus];
}
#endif
#ifdef SP_CODA /* glue */
if ( delegate && [delegate respondsToSelector:@selector(databaseDocumentDidConnect:)] )
[delegate performSelector:@selector(databaseDocumentDidConnect:) withObject:self];
#endif
}
/**
* Returns the current connection associated with this document.
*
* @return The document's connection
*/
- (SPMySQLConnection *) getConnection
{
return mySQLConnection;
}
/**
* Sets this connection's Keychain ID.
*/
- (void)setKeychainID:(NSString *)theID
{
keyChainID = [[NSString stringWithString:theID] retain];
}
#pragma mark -
#pragma mark Database methods
/**
* sets up the database select toolbar item
*/
- (IBAction)setDatabases:(id)sender;
{
#ifndef SP_CODA /* ui manipulation */
if (!chooseDatabaseButton) return;
[chooseDatabaseButton removeAllItems];
[chooseDatabaseButton addItemWithTitle:NSLocalizedString(@"Choose Database...", @"menu item for choose db")];
[[chooseDatabaseButton menu] addItem:[NSMenuItem separatorItem]];
[[chooseDatabaseButton menu] addItemWithTitle:NSLocalizedString(@"Add Database...", @"menu item to add db") action:@selector(addDatabase:) keyEquivalent:@""];
[[chooseDatabaseButton menu] addItemWithTitle:NSLocalizedString(@"Refresh Databases", @"menu item to refresh databases") action:@selector(setDatabases:) keyEquivalent:@""];
[[chooseDatabaseButton menu] addItem:[NSMenuItem separatorItem]];
#endif
if (allDatabases) [allDatabases release];
if (allSystemDatabases) [allSystemDatabases release];
NSArray *theDatabaseList = [mySQLConnection databases];
allDatabases = [[NSMutableArray alloc] initWithCapacity:[theDatabaseList count]];
allSystemDatabases = [[NSMutableArray alloc] initWithCapacity:2];
for (NSString *databaseName in theDatabaseList) {
// If the database is either information_schema or mysql then it is classed as a
// system table; similarly, for 5.5.3+, performance_schema
if ([databaseName isEqualToString:SPMySQLDatabase] ||
[databaseName isEqualToString:SPMySQLInformationSchemaDatabase] ||
[databaseName isEqualToString:SPMySQLPerformanceSchemaDatabase]) {
[allSystemDatabases addObject:databaseName];
}
else {
[allDatabases addObject:databaseName];
}
}
#ifndef SP_CODA /* ui manipulation */
// Add system databases
for (NSString *db in allSystemDatabases)
{
[chooseDatabaseButton addItemWithTitle:db];
}
// Add a separator between the system and user databases
if ([allSystemDatabases count] > 0) {
[[chooseDatabaseButton menu] addItem:[NSMenuItem separatorItem]];
}
// Add user databases
for (NSString *db in allDatabases)
{
[chooseDatabaseButton addItemWithTitle:db];
}
(![self database]) ? [chooseDatabaseButton selectItemAtIndex:0] : [chooseDatabaseButton selectItemWithTitle:[self database]];
#endif
}
#ifndef SP_CODA /* chooseDatabase: */
/**
* Selects the database choosen by the user, using a child task if necessary,
* and displaying errors in an alert sheet on failure.
*/
- (IBAction)chooseDatabase:(id)sender
{
if (![tablesListInstance selectionShouldChangeInTableView:nil]) {
[chooseDatabaseButton selectItemWithTitle:[self database]];
return;
}
if ( [chooseDatabaseButton indexOfSelectedItem] == 0 ) {
if ([self database]) {
[chooseDatabaseButton selectItemWithTitle:[self database]];
}
return;
}
// Lock editability again if performing a task
if (_isWorkingLevel) databaseListIsSelectable = NO;
// Select the database
[self selectDatabase:[chooseDatabaseButton titleOfSelectedItem] item:[self table]];
}
#endif
/**
* Select the specified database and, optionally, table.
*/
- (void)selectDatabase:(NSString *)database item:(NSString *)item
{
#ifndef SP_CODA /* update navigator controller */
// Do not update the navigator since nothing is changed
[[SPNavigatorController sharedNavigatorController] setIgnoreUpdate:NO];
// If Navigator runs in syncMode let it follow the selection
if([[SPNavigatorController sharedNavigatorController] syncMode]) {
NSMutableString *schemaPath = [NSMutableString string];
[schemaPath setString:[self connectionID]];
if([chooseDatabaseButton titleOfSelectedItem] && [[chooseDatabaseButton titleOfSelectedItem] length]) {
[schemaPath appendString:SPUniqueSchemaDelimiter];
[schemaPath appendString:[chooseDatabaseButton titleOfSelectedItem]];
}
[[SPNavigatorController sharedNavigatorController] selectPath:schemaPath];
}
#endif
// Start a task
[self startTaskWithDescription:[NSString stringWithFormat:NSLocalizedString(@"Loading database '%@'...", @"Loading database task string"), [chooseDatabaseButton titleOfSelectedItem]]];
NSDictionary *selectionDetails = [NSDictionary dictionaryWithObjectsAndKeys:database, @"database", item, @"item", nil];
if ([NSThread isMainThread]) {
[NSThread detachNewThreadWithName:@"SPDatabaseDocument database and table load task" target:self selector:@selector(_selectDatabaseAndItem:) object:selectionDetails];
}
else {
[self _selectDatabaseAndItem:selectionDetails];
}
}
/**
* opens the add-db sheet and creates the new db
*/
- (IBAction)addDatabase:(id)sender
{
if (![tablesListInstance selectionShouldChangeInTableView:nil]) return;
[databaseNameField setStringValue:@""];
NSString *defaultCharset = [databaseDataInstance getServerDefaultCharacterSet];
NSString *defaultCollation = [databaseDataInstance getServerDefaultCollation];
// Setup the charset and collation dropdowns
[addDatabaseCharsetHelper setDatabaseData:databaseDataInstance];
[addDatabaseCharsetHelper setServerSupport:serverSupport];
[addDatabaseCharsetHelper setPromoteUTF8:YES];
[addDatabaseCharsetHelper setSelectedCharset:nil];
[addDatabaseCharsetHelper setSelectedCollation:nil];
[addDatabaseCharsetHelper setDefaultCharset:defaultCharset];
[addDatabaseCharsetHelper setDefaultCollation:defaultCollation];
[addDatabaseCharsetHelper setEnabled:YES];
[NSApp beginSheet:databaseSheet
modalForWindow:parentWindow
modalDelegate:self
didEndSelector:@selector(sheetDidEnd:returnCode:contextInfo:)
contextInfo:@"addDatabase"];
}
/**
* Show UI for the ALTER DATABASE statement
* @warning Make sure this method is only called on mysql 4.1+ servers!
*/
- (IBAction)alterDatabase:(id)sender
{
//once the database is created the charset and collation are written
//to the db.opt file regardless if they were explicity given or not.
//So there is no longer a "Default" option.
NSString *currentCharset = [databaseDataInstance getDatabaseDefaultCharacterSet];
NSString *currentCollation = [databaseDataInstance getDatabaseDefaultCollation];
// Setup the charset and collation dropdowns
[alterDatabaseCharsetHelper setDatabaseData:databaseDataInstance];
[alterDatabaseCharsetHelper setServerSupport:serverSupport];
[alterDatabaseCharsetHelper setPromoteUTF8:YES];
[alterDatabaseCharsetHelper setSelectedCharset:currentCharset];
[alterDatabaseCharsetHelper setSelectedCollation:currentCollation];
[alterDatabaseCharsetHelper setEnabled:YES];
[NSApp beginSheet:databaseAlterSheet
modalForWindow:parentWindow
modalDelegate:self
didEndSelector:@selector(sheetDidEnd:returnCode:contextInfo:)
contextInfo:SPAlterDatabaseAction];
}
#ifndef SP_CODA /* operations on whole databases */
/**
* opens the copy database sheet and copies the databsae
*/
- (IBAction)copyDatabase:(id)sender
{
if (![tablesListInstance selectionShouldChangeInTableView:nil]) return;
[databaseCopyNameField setStringValue:selectedDatabase];
[copyDatabaseMessageField setStringValue:selectedDatabase];
[NSApp beginSheet:databaseCopySheet
modalForWindow:parentWindow
modalDelegate:self
didEndSelector:@selector(sheetDidEnd:returnCode:contextInfo:)
contextInfo:@"copyDatabase"];
}
#endif
/**
* opens the rename database sheet and renames the databsae
*/
- (IBAction)renameDatabase:(id)sender
{
if (![tablesListInstance selectionShouldChangeInTableView:nil]) return;
[databaseRenameNameField setStringValue:selectedDatabase];
[renameDatabaseMessageField setStringValue:[NSString stringWithFormat:NSLocalizedString(@"Rename database '%@' to:", @"rename database message"), selectedDatabase]];
[NSApp beginSheet:databaseRenameSheet
modalForWindow:parentWindow
modalDelegate:self
didEndSelector:@selector(sheetDidEnd:returnCode:contextInfo:)
contextInfo:SPRenameDatabaseAction];
}
/**
* opens sheet to ask user if he really wants to delete the db
*/
- (IBAction)removeDatabase:(id)sender
{
#ifndef SP_CODA
// No database selected, bail
if ([chooseDatabaseButton indexOfSelectedItem] == 0) return;
#endif
if (![tablesListInstance selectionShouldChangeInTableView:nil]) return;
NSAlert *alert = [NSAlert alertWithMessageText:[NSString stringWithFormat:NSLocalizedString(@"Delete database '%@'?", @"delete database message"), [self database]]
defaultButton:NSLocalizedString(@"Delete", @"delete button")
alternateButton:NSLocalizedString(@"Cancel", @"cancel button")
otherButton:nil
informativeTextWithFormat:NSLocalizedString(@"Are you sure you want to delete the database '%@'? This operation cannot be undone.", @"delete database informative message"), [self database]];
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:1] setKeyEquivalent:@"\e"]; // Esc = Cancel
[[buttons objectAtIndex:0] setKeyEquivalent:@"\r"]; // Return = OK
#endif
[alert setAlertStyle:NSCriticalAlertStyle];
[alert beginSheetModalForWindow:parentWindow modalDelegate:self didEndSelector:@selector(sheetDidEnd:returnCode:contextInfo:) contextInfo:@"removeDatabase"];
}
/**
* Refreshes the tables list by calling SPTablesList's updateTables.
*/
- (IBAction)refreshTables:(id)sender
{
[tablesListInstance updateTables:self];
}
#ifndef SP_CODA
/**
* Displays the database server variables sheet.
*/
- (IBAction)showServerVariables:(id)sender
{
if (!serverVariablesController) {
serverVariablesController = [[SPServerVariablesController alloc] init];
[serverVariablesController setConnection:mySQLConnection];
// Register to obeserve table view vertical grid line pref changes
[prefs addObserver:serverVariablesController forKeyPath:SPDisplayTableViewVerticalGridlines options:NSKeyValueObservingOptionNew context:NULL];
}
[serverVariablesController displayServerVariablesSheetAttachedToWindow:parentWindow];
}
/**
* Displays the database process list sheet.
*/
- (IBAction)showServerProcesses:(id)sender
{
if (!processListController) {
processListController = [[SPProcessListController alloc] init];
[processListController setConnection:mySQLConnection];
// Register to obeserve table view vertical grid line pref changes
[prefs addObserver:processListController forKeyPath:SPDisplayTableViewVerticalGridlines options:NSKeyValueObservingOptionNew context:NULL];
}
[processListController displayProcessListWindow];
}
#endif
/**
* Returns an array of all available database names
*/
- (NSArray *)allDatabaseNames
{
return allDatabases;
}
/**
* Returns an array of all available system database names
*/
- (NSArray *)allSystemDatabaseNames
{
return allSystemDatabases;
}
/**
* Alert sheet method. Invoked when an alert sheet is dismissed.
*
* if contextInfo == removeDatabase -> Remove the selected database
* if contextInfo == addDatabase -> Add a new database
* if contextInfo == copyDatabase -> Duplicate the selected database
* if contextInfo == renameDatabase -> Rename the selected database
*/
- (void)sheetDidEnd:(id)sheet returnCode:(NSInteger)returnCode contextInfo:(NSString *)contextInfo
{
#ifndef SP_CODA
if([contextInfo isEqualToString:@"saveDocPrefSheetStatus"]) {
saveDocPrefSheetStatus = returnCode;
return;
}
#endif
// 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];
// Remove the current database
if ([contextInfo isEqualToString:@"removeDatabase"]) {
if (returnCode == NSAlertDefaultReturn) {
[self _removeDatabase];
}
#ifdef SP_CODA
else {
// Reset chooseDatabaseButton
if ([[self database] length]) {
[chooseDatabaseButton selectItemWithTitle:[self database]];
}