/
SPTableStructure.m
2928 lines (2447 loc) · 112 KB
/
SPTableStructure.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
//
// SPTableStructure.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 "SPTableStructure.h"
#import "SPDatabaseStructure.h"
#import "SPDatabaseDocument.h"
#import "SPTableInfo.h"
#import "SPTablesList.h"
#import "SPTableData.h"
#import "SPTableView.h"
#import "SPDatabaseData.h"
#import "SPSQLParser.h"
#import "SPAlertSheets.h"
#import "SPIndexesController.h"
#import "RegexKitLite.h"
#import "SPTableFieldValidation.h"
#import "SPThreadAdditions.h"
#import "SPServerSupport.h"
#import "SPExtendedTableInfo.h"
#import "SPFunctions.h"
#import "SPPillAttachmentCell.h"
#import "SPIdMenu.h"
#import "SPComboBoxCell.h"
#import <SPMySQL/SPMySQL.h>
static NSString *SPRemoveField = @"SPRemoveField";
static NSString *SPRemoveFieldAndForeignKey = @"SPRemoveFieldAndForeignKey";
@interface SPFieldTypeHelp ()
@property(copy,readwrite) NSString *typeName;
@property(copy,readwrite) NSString *typeDefinition;
@property(copy,readwrite) NSString *typeRange;
@property(copy,readwrite) NSString *typeDescription;
@end
@implementation SPFieldTypeHelp
@synthesize typeName;
@synthesize typeDefinition;
@synthesize typeRange;
@synthesize typeDescription;
- (void)dealloc
{
[self setTypeName:nil];
[self setTypeDefinition:nil];
[self setTypeRange:nil];
[self setTypeDescription:nil];
[super dealloc];
}
@end
static inline SPFieldTypeHelp *MakeFieldTypeHelp(NSString *typeName,NSString *typeDefinition,NSString *typeRange,NSString *typeDescription) {
SPFieldTypeHelp *obj = [[SPFieldTypeHelp alloc] init];
[obj setTypeName: typeName];
[obj setTypeDefinition: typeDefinition];
[obj setTypeRange: typeRange];
[obj setTypeDescription:typeDescription];
return [obj autorelease];
}
struct _cmpMap {
NSString *title; // the title of the "pill"
NSString *tooltipPart; // the tooltip of the menuitem
NSString *cmpWith; // the string to match against
};
/**
* This function will compare the representedObject of every item in menu against
* every map->cmpWith. If they match it will append a pill-like (similar to a TokenFieldCell's token)
* element labelled map->title to the menu item's title. If map->tooltipPart is set,
* it will also be added to the menu item's tooltip.
*
* This is used with the encoding/collation popup menus to add visual indicators for the
* table-level and default encoding/collation.
*/
static void _BuildMenuWithPills(NSMenu *menu,struct _cmpMap *map,size_t mapEntries);
@interface SPTableStructure ()
- (void)sheetDidEnd:(id)sheet returnCode:(NSInteger)returnCode contextInfo:(NSString *)contextInfo;
- (void)_removeFieldAndForeignKey:(NSNumber *)removeForeignKey;
- (NSString *)_buildPartialColumnDefinitionString:(NSDictionary *)theRow;
#pragma mark - SPTableStructureDelegate
- (void)_displayFieldTypeHelpIfPossible:(SPComboBoxCell *)cell;
@end
@implementation SPTableStructure
#ifdef SP_CODA
@synthesize indexesController;
@synthesize indexesTableView;
@synthesize addFieldButton;
@synthesize duplicateFieldButton;
@synthesize removeFieldButton;
@synthesize reloadFieldsButton;
#endif
#pragma mark -
#pragma mark Initialisation
- (id)init
{
if ((self = [super init])) {
tableFields = [[NSMutableArray alloc] init];
oldRow = [[NSMutableDictionary alloc] init];
enumFields = [[NSMutableDictionary alloc] init];
defaultValues = nil;
selectedTable = nil;
typeSuggestions = nil;
extraFieldSuggestions = nil;
currentlyEditingRow = -1;
isCurrentExtraAutoIncrement = NO;
autoIncrementIndex = nil;
fieldValidation = [[SPTableFieldValidation alloc] init];
prefs = [NSUserDefaults standardUserDefaults];
}
return self;
}
- (void)awakeFromNib
{
// Set the structure and index view's vertical gridlines if required
[tableSourceView setGridStyleMask:[prefs boolForKey:SPDisplayTableViewVerticalGridlines] ? NSTableViewSolidVerticalGridLineMask : NSTableViewGridNone];
[indexesTableView setGridStyleMask:[prefs boolForKey:SPDisplayTableViewVerticalGridlines] ? NSTableViewSolidVerticalGridLineMask : NSTableViewGridNone];
// Set the double-click action in blank areas of the table to create new rows
[tableSourceView setEmptyDoubleClickAction:@selector(addField:)];
BOOL useMonospacedFont = [prefs boolForKey:SPUseMonospacedFonts];
NSInteger monospacedFontSize = [prefs integerForKey:SPMonospacedFontSize] > 0 ? [prefs integerForKey:SPMonospacedFontSize] : [NSFont smallSystemFontSize];
// Set the strutcture and index view's font
[tableSourceView setFont:useMonospacedFont ? [NSFont fontWithName:SPDefaultMonospacedFontName size:monospacedFontSize] : [NSFont systemFontOfSize:[NSFont smallSystemFontSize]]];
[indexesTableView setFont:useMonospacedFont ? [NSFont fontWithName:SPDefaultMonospacedFontName size:monospacedFontSize] : [NSFont systemFontOfSize:[NSFont smallSystemFontSize]]];
extraFieldSuggestions = [@[
@"None",
@"auto_increment",
@"on update CURRENT_TIMESTAMP",
@"SERIAL DEFAULT VALUE"
] retain];
// Note that changing the contents or ordering of this array will affect the implementation of
// SPTableFieldValidation. See it's implementation file for more details.
typeSuggestions = [@[
SPMySQLTinyIntType,
SPMySQLSmallIntType,
SPMySQLMediumIntType,
SPMySQLIntType,
SPMySQLBigIntType,
SPMySQLFloatType,
SPMySQLDoubleType,
SPMySQLDoublePrecisionType,
SPMySQLRealType,
SPMySQLDecimalType,
SPMySQLBitType,
SPMySQLSerialType,
SPMySQLBoolType,
SPMySQLBoolean,
SPMySQLDecType,
SPMySQLFixedType,
SPMySQLNumericType,
@"--------",
SPMySQLCharType,
SPMySQLVarCharType,
SPMySQLTinyTextType,
SPMySQLTextType,
SPMySQLMediumTextType,
SPMySQLLongTextType,
SPMySQLTinyBlobType,
SPMySQLMediumBlobType,
SPMySQLBlobType,
SPMySQLLongBlobType,
SPMySQLBinaryType,
SPMySQLVarBinaryType,
SPMySQLJsonType,
SPMySQLEnumType,
SPMySQLSetType,
@"--------",
SPMySQLDateType,
SPMySQLDatetimeType,
SPMySQLTimestampType,
SPMySQLTimeType,
SPMySQLYearType,
@"--------",
SPMySQLGeometryType,
SPMySQLPointType,
SPMySQLLineStringType,
SPMySQLPolygonType,
SPMySQLMultiPointType,
SPMySQLMultiLineStringType,
SPMySQLMultiPolygonType,
SPMySQLGeometryCollectionType] retain];
[fieldValidation setFieldTypes:typeSuggestions];
// 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];
// Init the view column submenu according to saved hidden status;
// menu items are identified by their tag number which represents the initial column index
for (NSMenuItem *item in [viewColumnsMenu itemArray]) [item setState:NSOnState]; // Set all items to NSOnState
for (NSTableColumn *col in [tableSourceView tableColumns])
{
if ([col isHidden]) {
if ([[col identifier] isEqualToString:@"Key"])
[[viewColumnsMenu itemWithTag:7] setState:NSOffState];
else if ([[col identifier] isEqualToString:@"encoding"])
[[viewColumnsMenu itemWithTag:10] setState:NSOffState];
else if ([[col identifier] isEqualToString:@"collation"])
[[viewColumnsMenu itemWithTag:11] setState:NSOffState];
else if ([[col identifier] isEqualToString:@"comment"])
[[viewColumnsMenu itemWithTag:12] setState:NSOffState];
}
}
[tableSourceView reloadData];
}
#pragma mark -
#pragma mark Edit methods
/**
* Adds an empty row to the tableSource-array and goes into edit mode
*/
- (IBAction)addField:(id)sender
{
// Check whether table editing is permitted (necessary as some actions - eg table double-click - bypass validation)
if ([tableDocumentInstance isWorking] || [tablesListInstance tableType] != SPTableTypeTable) return;
// Check whether a save of the current row is required.
if (![self saveRowOnDeselect]) return;
NSInteger insertIndex = ([tableSourceView numberOfSelectedRows] == 0 ? [tableSourceView numberOfRows] : [tableSourceView selectedRow] + 1);
#ifndef SP_CODA /* prefs access */
BOOL allowNull = [[[tableDataInstance statusValueForKey:@"Engine"] uppercaseString] isEqualToString:@"CSV"] ? NO : [prefs boolForKey:SPNewFieldsAllowNulls];
[tableFields insertObject:[NSMutableDictionary
dictionaryWithObjects:[NSArray arrayWithObjects:@"", @"INT", @"", @"0", @"0", @"0", allowNull ? @"1" : @"0", @"", [prefs stringForKey:SPNullValue], @"None", @"", nil]
forKeys:@[@"name", @"type", @"length", @"unsigned", @"zerofill", @"binary", @"null", @"Key", @"default", @"Extra", @"comment"]]
atIndex:insertIndex];
#else
[tableFields insertObject:[NSMutableDictionary
dictionaryWithObjects:[NSArray arrayWithObjects:@"", @"INT", @"", @"0", @"0", @"0", @"1", @"", @"NULL", @"None", @"", @0, @0, nil]
forKeys:[NSArray arrayWithObjects:@"name", @"type", @"length", @"unsigned", @"zerofill", @"binary", @"null", @"Key", @"default", @"Extra", @"comment", @"encoding", @"collation", nil]]
atIndex:insertIndex];
#endif
[tableSourceView reloadData];
[tableSourceView selectRowIndexes:[NSIndexSet indexSetWithIndex:insertIndex] byExtendingSelection:NO];
isEditingRow = YES;
isEditingNewRow = YES;
currentlyEditingRow = [tableSourceView selectedRow];
[tableSourceView editColumn:0 row:insertIndex withEvent:nil select:YES];
}
/**
* Show optimized field type for selected field
*/
- (IBAction)showOptimizedFieldType:(id)sender
{
SPMySQLResult *theResult = [mySQLConnection queryString:[NSString stringWithFormat:@"SELECT %@ FROM %@ PROCEDURE ANALYSE(0,8192)",
[[[tableFields objectAtIndex:[tableSourceView selectedRow]] objectForKey:@"name"] backtickQuotedString],
[selectedTable backtickQuotedString]]];
// Check for errors
if ([mySQLConnection queryErrored]) {
NSString *message = NSLocalizedString(@"Error while fetching the optimized field type", @"error while fetching the optimized field type message");
if ([mySQLConnection isConnected]) {
[[NSAlert alertWithMessageText:message
defaultButton:@"OK"
alternateButton:nil
otherButton:nil
informativeTextWithFormat:NSLocalizedString(@"An error occurred while fetching the optimized field type.\n\nMySQL said:%@", @"an error occurred while fetching the optimized field type.\n\nMySQL said:%@"), [mySQLConnection lastErrorMessage]]
beginSheetModalForWindow:[tableDocumentInstance parentWindow]
modalDelegate:self
didEndSelector:NULL
contextInfo:NULL];
}
return;
}
[theResult setReturnDataAsStrings:YES];
NSDictionary *analysisResult = [theResult getRowAsDictionary];
NSString *type = [analysisResult objectForKey:@"Optimal_fieldtype"];
if (!type || [type isNSNull] || ![type length]) {
type = NSLocalizedString(@"No optimized field type found.", @"no optimized field type found. message");
}
[[NSAlert alertWithMessageText:[NSString stringWithFormat:NSLocalizedString(@"Optimized type for field '%@'", @"Optimized type for field %@"), [[tableFields objectAtIndex:[tableSourceView selectedRow]] objectForKey:@"name"]]
defaultButton:@"OK"
alternateButton:nil
otherButton:nil
informativeTextWithFormat:@"%@", type]
beginSheetModalForWindow:[tableDocumentInstance parentWindow]
modalDelegate:self
didEndSelector:NULL
contextInfo:NULL];
}
/**
* Control the visibility of the columns
*/
- (IBAction)toggleColumnView:(NSMenuItem *)sender
{
NSString *columnIdentifierName = nil;
switch([sender tag]) {
case 7:
columnIdentifierName = @"Key";
break;
case 10:
columnIdentifierName = @"encoding";
break;
case 11:
columnIdentifierName = @"collation";
break;
case 12:
columnIdentifierName = @"comment";
break;
default:
return;
}
for(NSTableColumn *col in [tableSourceView tableColumns]) {
if([[col identifier] isEqualToString:columnIdentifierName]) {
[col setHidden:([sender state] == NSOffState) ? NO : YES];
[(NSMenuItem *)sender setState:![sender state]];
break;
}
}
[tableSourceView reloadData];
}
/**
* Copies a field and goes in edit mode for the new field
*/
- (IBAction)duplicateField:(id)sender
{
NSMutableDictionary *tempRow;
NSUInteger rowToCopy;
// Store the row to duplicate, as saveRowOnDeselect and subsequent reloads may trigger a deselection
if ([tableSourceView numberOfSelectedRows]) {
rowToCopy = [tableSourceView selectedRow];
} else {
rowToCopy = [tableSourceView numberOfRows]-1;
}
// Check whether a save of the current row is required.
if ( ![self saveRowOnDeselect] ) return;
//add copy of selected row and go in edit mode
tempRow = [NSMutableDictionary dictionaryWithDictionary:[tableFields objectAtIndex:rowToCopy]];
[tempRow setObject:[[tempRow objectForKey:@"name"] stringByAppendingString:@"Copy"] forKey:@"name"];
[tempRow setObject:@"" forKey:@"Key"];
[tempRow setObject:@"None" forKey:@"Extra"];
[tableFields addObject:tempRow];
[tableSourceView reloadData];
[tableSourceView selectRowIndexes:[NSIndexSet indexSetWithIndex:[tableSourceView numberOfRows]-1] byExtendingSelection:NO];
isEditingRow = YES;
isEditingNewRow = YES;
currentlyEditingRow = [tableSourceView selectedRow];
[tableSourceView editColumn:0 row:[tableSourceView numberOfRows]-1 withEvent:nil select:YES];
}
/**
* Ask the user to confirm that they really want to remove the selected field.
*/
- (IBAction)removeField:(id)sender
{
if (![tableSourceView numberOfSelectedRows]) return;
// Check whether a save of the current row is required.
if (![self saveRowOnDeselect]) return;
NSInteger anIndex = [tableSourceView selectedRow];
if ((anIndex == -1) || (anIndex > (NSInteger)([tableFields count] - 1))) return;
// Check if the user tries to delete the last defined field in table
// Note that because of better menu item validation, this check will now never evaluate to true.
if ([tableSourceView numberOfRows] < 2) {
NSAlert *alert = [NSAlert alertWithMessageText:NSLocalizedString(@"Error while deleting field", @"Error while deleting field")
defaultButton:NSLocalizedString(@"OK", @"OK button")
alternateButton:nil
otherButton:nil
informativeTextWithFormat:NSLocalizedString(@"You cannot delete the last field in a table. Delete the table instead.", @"You cannot delete the last field in a table. Delete the table instead.")];
[alert setAlertStyle:NSCriticalAlertStyle];
[alert beginSheetModalForWindow:[tableDocumentInstance parentWindow] modalDelegate:self didEndSelector:@selector(sheetDidEnd:returnCode:contextInfo:) contextInfo:@"cannotremovefield"];
}
NSString *field = [[tableFields objectAtIndex:anIndex] objectForKey:@"name"];
BOOL hasForeignKey = NO;
NSString *referencedTable = @"";
// Check to see whether the user is attempting to remove a field that has foreign key constraints and thus
// would result in an error if not dropped before removing the field.
for (NSDictionary *constraint in [tableDataInstance getConstraints])
{
for (NSString *column in [constraint objectForKey:@"columns"])
{
if ([column isEqualToString:field]) {
hasForeignKey = YES;
referencedTable = [constraint objectForKey:@"ref_table"];
break;
}
}
}
NSAlert *alert = [NSAlert alertWithMessageText:[NSString stringWithFormat:NSLocalizedString(@"Delete field '%@'?", @"delete field message"), field]
defaultButton:NSLocalizedString(@"Delete", @"delete button")
alternateButton:NSLocalizedString(@"Cancel", @"cancel button")
otherButton:nil
informativeTextWithFormat:hasForeignKey ? NSLocalizedString(@"This field is part of a foreign key relationship with the table '%@'. This relationship must be removed before the field can be deleted.\n\nAre you sure you want to continue to delete the relationship and the field? This action cannot be undone.", @"delete field and foreign key informative message"), referencedTable : NSLocalizedString(@"Are you sure you want to delete the field '%@'? This action cannot be undone.", @"delete field informative message"), field];
[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"];
[[buttons objectAtIndex:1] setKeyEquivalent:@"\e"];
#endif
[alert beginSheetModalForWindow:[tableDocumentInstance parentWindow]
modalDelegate:self
didEndSelector:@selector(removeFieldSheetDidEnd:returnCode:contextInfo:)
contextInfo:hasForeignKey ? SPRemoveFieldAndForeignKey : SPRemoveField];
}
/**
* Resets the auto increment value of a table.
*/
- (IBAction)resetAutoIncrement:(id)sender
{
if ([sender tag] == 1) {
[resetAutoIncrementLine setHidden:YES];
if ([tableDocumentInstance currentlySelectedView] == SPTableViewStructure){
[resetAutoIncrementLine setHidden:NO];
}
// Begin the sheet
[NSApp beginSheet:resetAutoIncrementSheet
modalForWindow:[tableDocumentInstance parentWindow]
modalDelegate:self
didEndSelector:@selector(resetAutoincrementSheetDidEnd:returnCode:contextInfo:)
contextInfo:nil];
[resetAutoIncrementValue setStringValue:@"1"];
}
else if ([sender tag] == 2) {
[self setAutoIncrementTo:@1];
}
}
/**
* Process the autoincrement sheet closing, resetting if the user confirmed the action.
*/
- (void)resetAutoincrementSheetDidEnd:(NSWindow *)theSheet returnCode:(NSInteger)returnCode contextInfo:(void *)contextInfo
{
// Order out current sheet to suppress overlapping of sheets
[theSheet orderOut:nil];
if (returnCode == NSAlertDefaultReturn) {
[self takeAutoIncrementFrom:resetAutoIncrementValue];
}
}
- (void)takeAutoIncrementFrom:(NSTextField *)field
{
id obj = [field objectValue];
//nil is handled by -setAutoIncrementTo:
if (obj && ![obj isKindOfClass:[NSNumber class]]) {
[NSException raise:NSInternalInconsistencyException format:@"[$field objectValue] should return NSNumber *, but was %@",[obj class]];
}
[self setAutoIncrementTo:(NSNumber *)obj];
}
/**
* Process the remove field sheet closing, performing the delete if the user
* confirmed the action.
*/
- (void)removeFieldSheetDidEnd:(NSAlert *)alert returnCode:(NSInteger)returnCode contextInfo:(void *)contextInfo
{
// Order out current sheet to suppress overlapping of sheets
[[alert window] orderOut:nil];
if (returnCode == NSAlertDefaultReturn) {
[tableDocumentInstance startTaskWithDescription:NSLocalizedString(@"Removing field...", @"removing field task status message")];
NSNumber *removeKey = [NSNumber numberWithBool:[(NSString *)contextInfo isEqualToString:SPRemoveFieldAndForeignKey]];
if ([NSThread isMainThread]) {
[NSThread detachNewThreadWithName:SPCtxt(@"SPTableStructure field and key removal task", tableDocumentInstance)
target:self
selector:@selector(_removeFieldAndForeignKey:)
object:removeKey];
[tableDocumentInstance enableTaskCancellationWithTitle:NSLocalizedString(@"Cancel", @"cancel button")
callbackObject:self
callbackFunction:NULL];
}
else {
[self _removeFieldAndForeignKey:removeKey];
}
}
}
/**
* Cancel active row editing, replacing the previous row if there was one
* and resetting state.
* Returns whether row editing was cancelled.
*/
- (BOOL)cancelRowEditing
{
if (!isEditingRow) return NO;
if (isEditingNewRow) {
isEditingNewRow = NO;
[tableFields removeObjectAtIndex:currentlyEditingRow];
}
else {
[tableFields replaceObjectAtIndex:currentlyEditingRow withObject:[NSMutableDictionary dictionaryWithDictionary:oldRow]];
}
isEditingRow = NO;
isCurrentExtraAutoIncrement = [tableDataInstance tableHasAutoIncrementField];
autoIncrementIndex = nil;
[tableSourceView reloadData];
currentlyEditingRow = -1;
[[tableDocumentInstance parentWindow] makeFirstResponder:tableSourceView];
return YES;
}
#pragma mark -
#pragma mark Other IB action methods
- (IBAction)unhideIndexesView:(id)sender
{
#ifndef SP_CODA
[tablesIndexesSplitView setPosition:[tablesIndexesSplitView frame].size.height-130 ofDividerAtIndex:0];
#endif
}
#pragma mark -
#pragma mark Index sheet methods
/**
* Closes the current sheet and stops the modal session.
*/
- (IBAction)closeSheet:(id)sender
{
[NSApp endSheet:[sender window] returnCode:[sender tag]];
[[sender window] orderOut:self];
}
#pragma mark -
#pragma mark Additional methods
/**
* Try table's auto_increment to a specific value
*
* @param valueAsString The new auto_increment integer as NSString
*/
- (void)setAutoIncrementTo:(NSNumber *)value
{
NSString *selTable = [tablesListInstance tableName];
if (selTable == nil || ![selTable length]) return;
if (value == nil) {
// reload data and bail
[tableDataInstance resetAllData];
#ifndef SP_CODA
[extendedTableInfoInstance loadTable:selTable];
[tableInfoInstance tableChanged:nil];
#endif
return;
}
// only int and float types can be AUTO_INCREMENT and right now BIGINT = 64 Bit (<= long long) is the largest type mysql supports
[mySQLConnection queryString:[NSString stringWithFormat:@"ALTER TABLE %@ AUTO_INCREMENT = %llu", [selTable backtickQuotedString], [value unsignedLongLongValue]]];
if ([mySQLConnection queryErrored]) {
SPOnewayAlertSheet(
NSLocalizedString(@"Error", @"error"),
[NSApp mainWindow],
[NSString stringWithFormat:NSLocalizedString(@"An error occurred while trying to reset AUTO_INCREMENT of table '%@'.\n\nMySQL said: %@", @"error resetting auto_increment informative message"),selTable, [mySQLConnection lastErrorMessage]]
);
}
// reload data
[tableDataInstance resetStatusData];
if([tableDocumentInstance currentlySelectedView] == SPTableViewStatus) {
[tableDataInstance resetAllData];
#ifndef SP_CODA
[extendedTableInfoInstance loadTable:selTable];
#endif
}
#ifndef SP_CODA
[tableInfoInstance tableChanged:nil];
#endif
}
/**
* Converts the supplied result to an array containing a (mutable) dictionary for each row
*/
- (NSArray *)convertIndexResultToArray:(SPMySQLResult *)theResult
{
NSUInteger numOfRows = (NSUInteger)[theResult numberOfRows];
NSMutableArray *tempResult = [NSMutableArray arrayWithCapacity:numOfRows];
NSMutableDictionary *tempRow;
NSArray *keys;
NSInteger i;
id prefsNullValue = [prefs objectForKey:SPNullValue];
// Ensure table information is returned as strings to avoid problems with some server versions
[theResult setReturnDataAsStrings:YES];
for ( i = 0 ; i < (NSInteger)numOfRows ; i++ ) {
tempRow = [NSMutableDictionary dictionaryWithDictionary:[theResult getRowAsDictionary]];
// Replace NSNull instances with the NULL string from preferences
keys = [tempRow allKeys];
for (id theKey in keys) {
if ([[tempRow objectForKey:theKey] isNSNull])
[tempRow setObject:prefsNullValue forKey:theKey];
}
// Update some fields to be more human-readable or GUI compatible
if ([[tempRow objectForKey:@"Extra"] isEqualToString:@""]) {
[tempRow setObject:@"None" forKey:@"Extra"];
}
if ([[tempRow objectForKey:@"Null"] isEqualToString:@"YES"]) {
[tempRow setObject:@"1" forKey:@"Null"];
} else {
[tempRow setObject:@"0" forKey:@"Null"];
}
[tempResult addObject:tempRow];
}
return tempResult;
}
/**
* A method to be called whenever the selection changes or the table would be reloaded
* or altered; checks whether the current row is being edited, and if so attempts to save
* it. Returns YES if no save was necessary or the save was successful, and NO if a save
* was necessary but failed - also reselecting the row for re-editing.
*/
- (BOOL)saveRowOnDeselect
{
// Save any edits which have been made but not saved to the table yet;
// but not for any NSSearchFields which could cause a crash for undo, redo.
id currentFirstResponder = [[tableDocumentInstance parentWindow] firstResponder];
if (currentFirstResponder && [currentFirstResponder isKindOfClass:[NSView class]] && [(NSView *)currentFirstResponder isDescendantOf:tableSourceView]) {
[[tableDocumentInstance parentWindow] endEditingFor:nil];
}
// If no rows are currently being edited, or a save is already in progress, return success at once.
if (!isEditingRow || isSavingRow) return YES;
isSavingRow = YES;
// Attempt to save the row, and return YES if the save succeeded.
if ([self addRowToDB]) {
isSavingRow = NO;
return YES;
}
// Saving failed - return failure.
isSavingRow = NO;
return NO;
}
/**
* Tries to write row to mysql-db
* returns YES if row written to db, otherwies NO
* returns YES if no row is beeing edited and nothing has to be written to db
*/
- (BOOL)addRowToDB
{
if ((!isEditingRow) || (currentlyEditingRow == -1)) return YES;
if (alertSheetOpened) return NO;
// Save any edits which have been started but not saved to the underlying table/data structures
// yet - but not if currently undoing/redoing, as this can cause a processing loop
if (![[[[tableSourceView window] firstResponder] undoManager] isUndoing] && ![[[[tableSourceView window] firstResponder] undoManager] isRedoing]) {
[[tableSourceView window] endEditingFor:nil];
}
NSDictionary *theRow = [tableFields objectAtIndex:currentlyEditingRow];
if ([autoIncrementIndex isEqualToString:@"PRIMARY KEY"]) {
// If the field isn't set to be unsigned and we're making it the primary key then make it unsigned
if (![[theRow objectForKey:@"unsigned"] boolValue]) {
NSMutableDictionary *rowCpy = [theRow mutableCopy];
[rowCpy setObject:@YES forKey:@"unsigned"];
theRow = [rowCpy autorelease];
}
}
NSMutableString *queryString = [NSMutableString stringWithFormat:@"ALTER TABLE %@",[selectedTable backtickQuotedString]];
[queryString appendString:@" "];
if (isEditingNewRow) {
[queryString appendString:@"ADD"];
}
else {
[queryString appendFormat:@"CHANGE %@",[[oldRow objectForKey:@"name"] backtickQuotedString]];
}
[queryString appendString:@" "];
[queryString appendString:[self _buildPartialColumnDefinitionString:theRow]];
// Process index if given for fields set to AUTO_INCREMENT
if (autoIncrementIndex) {
// User wants to add PRIMARY KEY
if ([autoIncrementIndex isEqualToString:@"PRIMARY KEY"]) {
[queryString appendString:@"\n PRIMARY KEY"];
// Add AFTER ... only if the user added a new field
if (isEditingNewRow) {
[queryString appendFormat:@"\n AFTER %@", [[[tableFields objectAtIndex:(currentlyEditingRow -1)] objectForKey:@"name"] backtickQuotedString]];
}
}
else {
// Add AFTER ... only if the user added a new field
if (isEditingNewRow) {
[queryString appendFormat:@"\n AFTER %@", [[[tableFields objectAtIndex:(currentlyEditingRow -1)] objectForKey:@"name"] backtickQuotedString]];
}
[queryString appendFormat:@"\n, ADD %@ (%@)", autoIncrementIndex, [[theRow objectForKey:@"name"] backtickQuotedString]];
}
}
// Add AFTER ... only if the user added a new field
else if (isEditingNewRow) {
[queryString appendFormat:@"\n AFTER %@", [[[tableFields objectAtIndex:(currentlyEditingRow -1)] objectForKey:@"name"] backtickQuotedString]];
}
isCurrentExtraAutoIncrement = NO;
autoIncrementIndex = nil;
// Execute query
[mySQLConnection queryString:queryString];
if (![mySQLConnection queryErrored]) {
isEditingRow = NO;
isEditingNewRow = NO;
currentlyEditingRow = -1;
[tableDataInstance resetAllData];
[tableDocumentInstance setStatusRequiresReload:YES];
[self loadTable:selectedTable];
// Mark the content table for refresh
[tableDocumentInstance setContentRequiresReload:YES];
// Query the structure of all databases in the background
[[tableDocumentInstance databaseStructureRetrieval] queryDbStructureInBackgroundWithUserInfo:[NSDictionary dictionaryWithObjectsAndKeys:@YES, @"forceUpdate", selectedTable, @"affectedItem", [NSNumber numberWithInteger:[tablesListInstance tableType]], @"affectedItemType", nil]];
return YES;
}
else {
alertSheetOpened = YES;
if([mySQLConnection lastErrorID] == 1146) { // If the current table doesn't exist anymore
SPOnewayAlertSheet(
NSLocalizedString(@"Error", @"error"),
[tableDocumentInstance parentWindow],
[NSString stringWithFormat:NSLocalizedString(@"An error occurred while trying to alter table '%@'.\n\nMySQL said: %@", @"error while trying to alter table message"),selectedTable, [mySQLConnection lastErrorMessage]]
);
isEditingRow = NO;
isEditingNewRow = NO;
currentlyEditingRow = -1;
[tableFields removeAllObjects];
[tableSourceView reloadData];
[indexesTableView reloadData];
[addFieldButton setEnabled:NO];
[duplicateFieldButton setEnabled:NO];
[removeFieldButton setEnabled:NO];
#ifndef SP_CODA
[addIndexButton setEnabled:NO];
[removeIndexButton setEnabled:NO];
[editTableButton setEnabled:NO];
#endif
[tablesListInstance updateTables:self];
return NO;
}
// Problem: alert sheet doesn't respond to first click
if (isEditingNewRow) {
SPBeginAlertSheet(NSLocalizedString(@"Error adding field", @"error adding field message"),
NSLocalizedString(@"Edit row", @"Edit row button"),
NSLocalizedString(@"Discard changes", @"discard changes button"), nil, [tableDocumentInstance parentWindow], self, @selector(addRowErrorSheetDidEnd:returnCode:contextInfo:), NULL,
[NSString stringWithFormat:NSLocalizedString(@"An error occurred when trying to add the field '%@' via\n\n%@\n\nMySQL said: %@", @"error adding field informative message"),
[theRow objectForKey:@"name"], queryString, [mySQLConnection lastErrorMessage]]);
}
else {
SPBeginAlertSheet(NSLocalizedString(@"Error changing field", @"error changing field message"),
NSLocalizedString(@"Edit row", @"Edit row button"),
NSLocalizedString(@"Discard changes", @"discard changes button"), nil, [tableDocumentInstance parentWindow], self, @selector(addRowErrorSheetDidEnd:returnCode:contextInfo:), NULL,
[NSString stringWithFormat:NSLocalizedString(@"An error occurred when trying to change the field '%@' via\n\n%@\n\nMySQL said: %@", @"error changing field informative message"),
[theRow objectForKey:@"name"], queryString, [mySQLConnection lastErrorMessage]]);
}
return NO;
}
}
/**
* Takes the column definition from a dictionary and returns the it to be used
* with an ALTER statement, e.g.:
* `col1` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT
*/
- (NSString *)_buildPartialColumnDefinitionString:(NSDictionary *)theRow
{
NSMutableString *queryString;
BOOL fieldDefIncludesLen = NO;
NSString *theRowType = @"";
NSString *theRowExtra = @"";
BOOL specialFieldTypes = NO;
if ([theRow objectForKey:@"type"])
theRowType = [[[theRow objectForKey:@"type"] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
if ([theRow objectForKey:@"Extra"])
theRowExtra = [[[theRow objectForKey:@"Extra"] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
queryString = [NSMutableString stringWithString:[[theRow objectForKey:@"name"] backtickQuotedString]];
[queryString appendString:@" "];
[queryString appendString:theRowType];
// Check for pre-defined field type SERIAL
if([theRowType isEqualToString:@"SERIAL"]) {
specialFieldTypes = YES;
}
// Check for pre-defined field type BOOL(EAN)
else if([theRowType rangeOfRegex:@"(?i)bool(ean)?"].length) {
specialFieldTypes = YES;
if ([[theRow objectForKey:@"null"] integerValue] == 0) {
[queryString appendString:@"\n NOT NULL"];
} else {
[queryString appendString:@"\n NULL"];
}
// If a NULL value has been specified, and NULL is allowed, specify DEFAULT NULL
if ([[theRow objectForKey:@"default"] isEqualToString:[prefs objectForKey:SPNullValue]])
{
if ([[theRow objectForKey:@"null"] integerValue] == 1) {
[queryString appendString:@"\n DEFAULT NULL "];
}
}
else if (![(NSString *)[theRow objectForKey:@"default"] length]) {
;
}
// Otherwise, use the provided default
else {
[queryString appendFormat:@"\n DEFAULT %@ ", [mySQLConnection escapeAndQuoteString:[theRow objectForKey:@"default"]]];
}
}
// Check for Length specification
else if ([theRow objectForKey:@"length"] && [[[theRow objectForKey:@"length"] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length]) {
fieldDefIncludesLen = YES;
[queryString appendFormat:@"(%@)", [theRow objectForKey:@"length"]];
}
if(!specialFieldTypes) {
if ([theRowType isEqualToString:@"JSON"]) {
// we "see" JSON as a string, but it is not internally to MySQL and so doesn't allow CHARACTER SET/BINARY/COLLATE either.
}
else if ([fieldValidation isFieldTypeString:theRowType]) {
BOOL charsetSupport = [[tableDocumentInstance serverSupport] supportsPost41CharacterSetHandling];
// Add CHARSET
NSString *fieldEncoding = [theRow objectForKey:@"encodingName"];
if(charsetSupport && [fieldEncoding length]) {
[queryString appendFormat:@"\n CHARACTER SET %@", fieldEncoding];
}
if ([[theRow objectForKey:@"binary"] integerValue] == 1) {
[queryString appendString:@"\n BINARY"];
}
else {
// ADD COLLATE
// Note: a collate without charset is valid in MySQL. The charset can be determined from a collation.
NSString *fieldCollation = [theRow objectForKey:@"collationName"];
if(charsetSupport && [fieldCollation length]) {
[queryString appendFormat:@"\n COLLATE %@", fieldCollation];
}
}
}
else if ([fieldValidation isFieldTypeNumeric:theRowType] && (![theRowType isEqualToString:@"BIT"])) {
if ([[theRow objectForKey:@"unsigned"] integerValue] == 1) {
[queryString appendString:@"\n UNSIGNED"];
}
if ( [[theRow objectForKey:@"zerofill"] integerValue] == 1) {
[queryString appendString:@"\n ZEROFILL"];
}
}
if ([[theRow objectForKey:@"null"] integerValue] == 0 || [theRowExtra isEqualToString:@"SERIAL DEFAULT VALUE"]) {
[queryString appendString:@"\n NOT NULL"];
}
else {
[queryString appendString:@"\n NULL"];
}