/
SPTableContent.m
4222 lines (3529 loc) · 157 KB
/
SPTableContent.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
//
// SPTableContent.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 "SPTableContent.h"
#import "SPTableContentFilter.h"
#import "SPDatabaseDocument.h"
#import "SPTableStructure.h"
#import "SPTableInfo.h"
#import "SPTablesList.h"
#import "SPImageView.h"
#import "SPCopyTable.h"
#import "SPDataCellFormatter.h"
#import "SPTableData.h"
#import "SPQueryController.h"
#import "SPQueryDocumentsController.h"
#import "SPTextAndLinkCell.h"
#ifndef SP_CODA
#import "SPSplitView.h"
#endif
#import "SPFieldEditorController.h"
#import "SPTooltip.h"
#import "RegexKitLite.h"
#import "SPContentFilterManager.h"
#import "SPDataStorage.h"
#import "SPAlertSheets.h"
#import "SPHistoryController.h"
#import "SPGeometryDataView.h"
#import "SPTextView.h"
#import "SPDatabaseViewController.h"
#ifndef SP_CODA /* headers */
#import "SPAppController.h"
#import "SPBundleHTMLOutputController.h"
#endif
#import "SPCustomQuery.h"
#import "SPThreadAdditions.h"
#import "SPTableFilterParser.h"
#import <pthread.h>
#import <SPMySQL/SPMySQL.h>
#include <stdlib.h>
#ifndef SP_CODA
static NSString *SPTableFilterSetDefaultOperator = @"SPTableFilterSetDefaultOperator";
#endif
@interface SPTableContent (SPTableContentDataSource_Private_API)
- (id)_contentValueForTableColumn:(NSUInteger)columnIndex row:(NSUInteger)rowIndex asPreview:(BOOL)asPreview;
@end
@interface SPTableContent ()
- (BOOL)cancelRowEditing;
@end
@implementation SPTableContent
#ifdef SP_CODA
@synthesize addButton;
@synthesize argumentField;
@synthesize betweenTextField;
@synthesize compareField;
@synthesize duplicateButton;
@synthesize fieldField;
@synthesize filterButton;
@synthesize firstBetweenField;
@synthesize paginationNextButton;
@synthesize paginationPageField;
@synthesize paginationPreviousButton;
@synthesize reloadButton;
@synthesize removeButton;
@synthesize secondBetweenField;
@synthesize tableContentView;
@synthesize tableDataInstance;
@synthesize tableDocumentInstance;
@synthesize tableSourceInstance;
@synthesize tablesListInstance;
#endif
#pragma mark -
- (id)init
{
if ((self = [super init])) {
_mainNibLoaded = NO;
isWorking = NO;
pthread_mutex_init(&tableValuesLock, NULL);
#ifndef SP_CODA
nibObjectsToRelease = [[NSMutableArray alloc] init];
#endif
tableValues = [[SPDataStorage alloc] init];
dataColumns = [[NSMutableArray alloc] init];
oldRow = [[NSMutableArray alloc] init];
#ifndef SP_CODA
filterTableData = [[NSMutableDictionary alloc] initWithCapacity:1];
#endif
tableRowsCount = 0;
previousTableRowsCount = 0;
#ifndef SP_CODA
filterTableNegate = NO;
filterTableDistinct = NO;
filterTableIsSwapped = NO;
lastEditedFilterTableValue = nil;
activeFilter = 0;
schemeFilter = nil;
paginationPopover = nil;
#endif
selectedTable = nil;
sortCol = nil;
isDesc = NO;
keys = nil;
currentlyEditingRow = -1;
contentPage = 1;
sortColumnToRestore = nil;
sortColumnToRestoreIsAsc = YES;
pageToRestore = 1;
selectionToRestore = nil;
selectionViewportToRestore = NSZeroRect;
filterFieldToRestore = nil;
filterComparisonToRestore = nil;
filterValueToRestore = nil;
firstBetweenValueToRestore = nil;
secondBetweenValueToRestore = nil;
tableRowsSelectable = YES;
contentFilterManager = nil;
isFirstChangeInView = YES;
isFiltered = NO;
isLimited = NO;
isInterruptedLoad = NO;
prefs = [NSUserDefaults standardUserDefaults];
usedQuery = [[NSString alloc] initWithString:@""];
tableLoadTimer = nil;
tableLoadingCondition = [NSCondition new];
blackColor = [NSColor blackColor];
lightGrayColor = [NSColor lightGrayColor];
blueColor = [NSColor blueColor];
whiteColor = [NSColor whiteColor];
// Init default filters for Content Browser
contentFilters = nil;
contentFilters = [[NSMutableDictionary alloc] init];
numberOfDefaultFilters = [[NSMutableDictionary alloc] init];
NSError *readError = nil;
NSString *convError = nil;
NSPropertyListFormat format;
NSData *defaultFilterData = [NSData dataWithContentsOfFile:[NSBundle pathForResource:@"ContentFilters.plist" ofType:nil inDirectory:[[NSBundle mainBundle] bundlePath]]
options:NSMappedRead error:&readError];
[contentFilters setDictionary:[NSPropertyListSerialization propertyListFromData:defaultFilterData
mutabilityOption:NSPropertyListMutableContainersAndLeaves format:&format errorDescription:&convError]];
if (contentFilters == nil || readError != nil || convError != nil) {
NSLog(@"Error while reading 'ContentFilters.plist':\n%@\n%@", [readError localizedDescription], convError);
NSBeep();
}
else {
[numberOfDefaultFilters setObject:[NSNumber numberWithInteger:[[contentFilters objectForKey:@"number"] count]] forKey:@"number"];
[numberOfDefaultFilters setObject:[NSNumber numberWithInteger:[[contentFilters objectForKey:@"date"] count]] forKey:@"date"];
[numberOfDefaultFilters setObject:[NSNumber numberWithInteger:[[contentFilters objectForKey:@"string"] count]] forKey:@"string"];
[numberOfDefaultFilters setObject:[NSNumber numberWithInteger:[[contentFilters objectForKey:@"spatial"] count]] forKey:@"spatial"];
}
kCellEditorErrorNoMatch = NSLocalizedString(@"Field is not editable. No matching record found.\nReload table, check the encoding, or try to add\na primary key field or more fields\nin the view declaration of '%@' to identify\nfield origin unambiguously.", @"Table Content result editing error - could not identify original row");
kCellEditorErrorNoMultiTabDb = NSLocalizedString(@"Field is not editable. Field has no or multiple table or database origin(s).",@"field is not editable due to no table/database");
kCellEditorErrorTooManyMatches = NSLocalizedString(@"Field is not editable. Couldn't identify field origin unambiguously (%ld matches).", @"Query result editing error - could not match row being edited uniquely");
}
return self;
}
- (void)awakeFromNib
{
if (_mainNibLoaded) return;
_mainNibLoaded = YES;
#ifndef SP_CODA /* ui manipulation */
// Temporary to avoid nib conflicts during WIP
[contentSplitView setCollapsibleSubviewIndex:0];
[contentSplitView setCollapsibleSubviewCollapsed:YES animate:NO];
[contentSplitView setMaxSize:0.f ofSubviewAtIndex:0];
// Set the table content view's vertical gridlines if required
[tableContentView setGridStyleMask:([prefs boolForKey:SPDisplayTableViewVerticalGridlines]) ? NSTableViewSolidVerticalGridLineMask : NSTableViewGridNone];
[filterTableView setGridStyleMask:([prefs boolForKey:SPDisplayTableViewVerticalGridlines]) ? NSTableViewSolidVerticalGridLineMask : NSTableViewGridNone];
// Set the double-click action in blank areas of the table to create new rows
[tableContentView setEmptyDoubleClickAction:@selector(addRow:)];
// Load the pagination view, keeping references to the top-level objects for later release
NSArray *paginationViewTopLevelObjects = nil;
NSNib *nibLoader = [[NSNib alloc] initWithNibNamed:@"ContentPaginationView" bundle:[NSBundle mainBundle]];
if (![nibLoader instantiateNibWithOwner:self topLevelObjects:&paginationViewTopLevelObjects]) {
NSLog(@"Content pagination nib could not be loaded; pagination will not function correctly.");
}
else {
[nibObjectsToRelease addObjectsFromArray:paginationViewTopLevelObjects];
}
[nibLoader release];
#if __MAC_OS_X_VERSION_MAX_ALLOWED >= __MAC_10_7
//let's see if we can use the NSPopover (10.7+) or have to make do with our legacy clone.
//this is using reflection right now, as our SDK is 10.8 but our minimum supported version is 10.6
Class popOverClass = NSClassFromString(@"NSPopover");
if(popOverClass)
{
paginationPopover = [[popOverClass alloc] init];
[paginationPopover setDelegate:(SPTableContent<NSPopoverDelegate> *)self];
[paginationPopover setContentViewController:paginationViewController];
[paginationPopover setBehavior:NSPopoverBehaviorTransient];
}
else
#endif
{
[paginationBox setContentView:[paginationViewController view]];
// Add the pagination view to the content area
NSRect paginationViewFrame = [paginationView frame];
NSRect paginationButtonFrame = [paginationButton frame];
paginationViewHeight = paginationViewFrame.size.height;
paginationViewFrame.origin.x = paginationButtonFrame.origin.x + paginationButtonFrame.size.width - paginationViewFrame.size.width;
paginationViewFrame.origin.y = paginationButtonFrame.origin.y + paginationButtonFrame.size.height - 2;
paginationViewFrame.size.height = 0;
[paginationView setFrame:paginationViewFrame];
[contentViewPane addSubview:paginationView];
}
// Modify the filter table split view sizes
[filterTableSplitView setMinSize:135 ofSubviewAtIndex:1];
#endif
[tableContentView setFieldEditorSelectedRange:NSMakeRange(0,0)];
#ifndef SP_CODA
// Init Filter Table GUI
[filterTableDistinctCheckbox setState:(filterTableDistinct) ? NSOnState : NSOffState];
[filterTableNegateCheckbox setState:(filterTableNegate) ? NSOnState : NSOffState];
[filterTableLiveSearchCheckbox setState:NSOffState];
#endif
#ifndef SP_CODA /* patch */
filterTableDefaultOperator = [[self escapeFilterTableDefaultOperator:[prefs objectForKey:SPFilterTableDefaultOperator]] retain];
#else
// filterTableDefaultOperator = [[self escapeFilterTableDefaultOperator:nil] retain];
#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];
}
#pragma mark -
#pragma mark Table loading methods and information
/**
* Loads aTable, retrieving column information and updating the tableViewColumns before
* reloading table data into the data array and redrawing the table.
*
* @param aTable The to be loaded table name
*/
- (void)loadTable:(NSString *)aTable
{
// Abort the reload if the user is still editing a row
if (isEditingRow) return;
// If no table has been supplied, clear the table interface and return
if (!aTable || [aTable isEqualToString:@""]) {
[[self onMainThread] setTableDetails:nil];
return;
}
// Attempt to retrieve the table encoding; if that fails (indicating an error occurred
// while retrieving table data), or if the Rows variable is null, clear and return
if (![tableDataInstance tableEncoding] || [[[tableDataInstance statusValues] objectForKey:@"Rows"] isNSNull]) {
[[self onMainThread] setTableDetails:nil];
return;
}
// Post a notification that a query will be performed
[[NSNotificationCenter defaultCenter] postNotificationOnMainThreadWithName:@"SMySQLQueryWillBePerformed" object:tableDocumentInstance];
// Set up the table details for the new table, and trigger an interface update
NSDictionary *tableDetails = [NSDictionary dictionaryWithObjectsAndKeys:
aTable, @"name",
[tableDataInstance columns], @"columns",
[tableDataInstance columnNames], @"columnNames",
[tableDataInstance getConstraints], @"constraints",
nil];
[[self onMainThread] setTableDetails:tableDetails];
// Init copyTable with necessary information for copying selected rows as SQL INSERT
[tableContentView setTableInstance:self withTableData:tableValues withColumns:dataColumns withTableName:selectedTable withConnection:mySQLConnection];
// Trigger a data refresh
[self loadTableValues];
// Restore the view origin if appropriate
if (!NSEqualRects(selectionViewportToRestore, NSZeroRect)) {
// Scroll the viewport to the saved location
selectionViewportToRestore.size = [tableContentView visibleRect].size;
[(SPCopyTable*)[tableContentView onMainThread] scrollRectToVisible:selectionViewportToRestore];
}
// Update display if necessary
if (!NSEqualRects(selectionViewportToRestore, NSZeroRect))
[[tableContentView onMainThread] setNeedsDisplayInRect:selectionViewportToRestore];
else
[[tableContentView onMainThread] setNeedsDisplay:YES];
// Post the notification that the query is finished
[[NSNotificationCenter defaultCenter] postNotificationOnMainThreadWithName:@"SMySQLQueryHasBeenPerformed" object:tableDocumentInstance];
// Clear any details to restore now that they have been restored
[self clearDetailsToRestore];
}
/**
* Update stored table details and update the interface to match the supplied
* table details.
* Should be called on the main thread.
*/
- (void) setTableDetails:(NSDictionary *)tableDetails
{
NSString *newTableName;
NSInteger i, sortColumnNumberToRestore = NSNotFound;
#ifndef SP_CODA
NSNumber *colWidth;
#endif
NSArray *columnNames;
NSDictionary *columnDefinition;
NSMutableDictionary *preservedColumnWidths = nil;
NSTableColumn *theCol;
#ifndef SP_CODA
NSTableColumn *filterCol;
#endif
BOOL enableInteraction =
#ifndef SP_CODA /* checking toolbar state */
![[tableDocumentInstance selectedToolbarItemIdentifier] isEqualToString:SPMainToolbarTableContent] ||
#endif
![tableDocumentInstance isWorking];
if (!tableDetails) {
// If no table is currently selected, no action required - return.
if (!selectedTable) return;
newTableName = nil;
} else {
newTableName = [tableDetails objectForKey:@"name"];
}
#ifndef SP_CODA
// Ensure the pagination view hides itself if visible, after a tiny delay for smoothness
[self performSelector:@selector(setPaginationViewVisibility:) withObject:nil afterDelay:0.1];
#endif
// Reset table key store for use in argumentForRow:
if (keys) SPClear(keys);
// Reset data column store
[dataColumns removeAllObjects];
// Check the supplied table name. If it matches the old one, a reload is being performed;
// reload the data in-place to maintain table state if possible.
if ([selectedTable isEqualToString:newTableName]) {
previousTableRowsCount = tableRowsCount;
// Store the column widths for later restoration
preservedColumnWidths = [NSMutableDictionary dictionaryWithCapacity:[[tableContentView tableColumns] count]];
for (NSTableColumn *eachColumn in [tableContentView tableColumns]) {
[preservedColumnWidths setObject:[NSNumber numberWithFloat:[eachColumn width]] forKey:[[eachColumn headerCell] stringValue]];
}
// Otherwise store the newly selected table name and reset the data
} else {
if (selectedTable) SPClear(selectedTable);
if (newTableName) selectedTable = [[NSString alloc] initWithString:newTableName];
previousTableRowsCount = 0;
contentPage = 1;
[paginationPageField setStringValue:@"1"];
// Clear the selection
[tableContentView deselectAll:self];
// Restore the table content view to the top left
[tableContentView scrollRowToVisible:0];
[tableContentView scrollColumnToVisible:0];
// Set the maximum table rows to an estimated count pre-load
maxNumRows = [[tableDataInstance statusValueForKey:@"Rows"] integerValue];
maxNumRowsIsEstimate = YES;
}
// If no table has been supplied, reset the view to a blank table and disabled elements.
if (!newTableName) {
// Remove existing columns from the table
while ([[tableContentView tableColumns] count]) {
[tableContentView removeTableColumn:NSArrayObjectAtIndex([tableContentView tableColumns], 0)];
}
// Empty the stored data arrays, including emptying the tableValues array
// by ressignment for thread safety.
previousTableRowsCount = 0;
[self clearTableValues];
[tableContentView reloadData];
isFiltered = NO;
isLimited = NO;
#ifndef SP_CODA
[countText setStringValue:@""];
#endif
// Reset sort column
if (sortCol) SPClear(sortCol);
isDesc = NO;
// Empty and disable filter options
[fieldField setEnabled:NO];
[fieldField removeAllItems];
[fieldField addItemWithTitle:NSLocalizedString(@"field", @"popup menuitem for field (showing only if disabled)")];
[compareField setEnabled:NO];
[compareField removeAllItems];
[compareField addItemWithTitle:@"="];
[argumentField setHidden:NO];
[argumentField setEnabled:NO];
[firstBetweenField setEnabled:NO];
[secondBetweenField setEnabled:NO];
[firstBetweenField setStringValue:@""];
[secondBetweenField setStringValue:@""];
[argumentField setStringValue:@""];
[filterButton setEnabled:NO];
// Hide BETWEEN operator controls
[firstBetweenField setHidden:YES];
[secondBetweenField setHidden:YES];
[betweenTextField setHidden:YES];
// Disable pagination
[paginationPreviousButton setEnabled:NO];
#ifndef SP_CODA
[paginationButton setEnabled:NO];
[paginationButton setTitle:@""];
#endif
[paginationNextButton setEnabled:NO];
// Disable table action buttons
[addButton setEnabled:NO];
[duplicateButton setEnabled:NO];
[removeButton setEnabled:NO];
// Clear restoration settings
[self clearDetailsToRestore];
#ifndef SP_CODA
// Clear filter table
while ([[filterTableView tableColumns] count]) {
[filterTableView removeTableColumn:NSArrayObjectAtIndex([filterTableView tableColumns], 0)];
}
// Clear filter table data
[filterTableData removeAllObjects];
[filterTableWhereClause setString:@""];
activeFilter = 0;
#endif
return;
}
// Otherwise, prepare to set up the new table - the table data instance already has table details set.
// Remove existing columns from the table
while ([[tableContentView tableColumns] count]) {
[tableContentView removeTableColumn:NSArrayObjectAtIndex([tableContentView tableColumns], 0)];
}
#ifndef SP_CODA
// Remove existing columns from the filter table
[filterTableView abortEditing];
while ([[filterTableView tableColumns] count]) {
[filterTableView removeTableColumn:NSArrayObjectAtIndex([filterTableView tableColumns], 0)];
}
// Clear filter table data
[filterTableData removeAllObjects];
[filterTableWhereClause setString:@""];
activeFilter = 0;
#endif
// Retrieve the field names and types for this table from the data cache. This is used when requesting all data as part
// of the fieldListForQuery method, and also to decide whether or not to preserve the current filter/sort settings.
[dataColumns addObjectsFromArray:[tableDetails objectForKey:@"columns"]];
columnNames = [tableDetails objectForKey:@"columnNames"];
// Retrieve the constraints, and loop through them to add up to one foreign key to each column
NSArray *constraints = [tableDetails objectForKey:@"constraints"];
for (NSDictionary *constraint in constraints)
{
NSString *firstColumn = [[constraint objectForKey:@"columns"] objectAtIndex:0];
NSString *firstRefColumn = [[constraint objectForKey:@"ref_columns"] objectAtIndex:0];
NSUInteger columnIndex = [columnNames indexOfObject:firstColumn];
if (columnIndex != NSNotFound && ![[dataColumns objectAtIndex:columnIndex] objectForKey:@"foreignkeyreference"]) {
NSDictionary *refDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
[constraint objectForKey:@"ref_table"], @"table",
firstRefColumn, @"column",
nil];
NSMutableDictionary *rowDictionary = [NSMutableDictionary dictionaryWithDictionary:[dataColumns objectAtIndex:columnIndex]];
[rowDictionary setObject:refDictionary forKey:@"foreignkeyreference"];
[dataColumns replaceObjectAtIndex:columnIndex withObject:rowDictionary];
}
}
NSString *nullValue = [prefs objectForKey:SPNullValue];
#ifndef SP_CODA /* get font from prefs */
NSFont *tableFont = [NSUnarchiver unarchiveObjectWithData:[prefs dataForKey:SPGlobalResultTableFont]];
#else
NSFont *tableFont = [NSFont systemFontOfSize:[NSFont smallSystemFontSize]];
#endif
[tableContentView setRowHeight:2.0f+NSSizeToCGSize([@"{ǞṶḹÜ∑zgyf" sizeWithAttributes:@{NSFontAttributeName : tableFont}]).height];
// Add the new columns to the table and filterTable
for ( i = 0 ; i < (NSInteger)[dataColumns count] ; i++ ) {
columnDefinition = NSArrayObjectAtIndex(dataColumns, i);
// Set up the column
theCol = [[NSTableColumn alloc] initWithIdentifier:[columnDefinition objectForKey:@"datacolumnindex"]];
[[theCol headerCell] setStringValue:[columnDefinition objectForKey:@"name"]];
[theCol setHeaderToolTip:[NSString stringWithFormat:@"%@ – %@%@%@%@",
[columnDefinition objectForKey:@"name"],
[columnDefinition objectForKey:@"type"],
([columnDefinition objectForKey:@"length"]) ? [NSString stringWithFormat:@"(%@)", [columnDefinition objectForKey:@"length"]] : @"",
([columnDefinition objectForKey:@"values"]) ? [NSString stringWithFormat:@"(\n- %@\n)", [[columnDefinition objectForKey:@"values"] componentsJoinedByString:@"\n- "]] : @"",
([columnDefinition objectForKey:@"comment"] && [(NSString *)[columnDefinition objectForKey:@"comment"] length]) ? [NSString stringWithFormat:@"\n%@", [[columnDefinition objectForKey:@"comment"] stringByReplacingOccurrencesOfString:@"\\n" withString:@"\n"]] : @""
]];
// Copy in the width if present in a reloaded table
if ([preservedColumnWidths objectForKey:[columnDefinition objectForKey:@"name"]]) {
[theCol setWidth:[[preservedColumnWidths objectForKey:[columnDefinition objectForKey:@"name"]] floatValue]];
}
[theCol setEditable:YES];
#ifndef SP_CODA
// Set up column for filterTable
filterCol = [[NSTableColumn alloc] initWithIdentifier:[columnDefinition objectForKey:@"datacolumnindex"]];
[[filterCol headerCell] setStringValue:[columnDefinition objectForKey:@"name"]];
[filterCol setEditable:YES];
SPTextAndLinkCell *filterDataCell = [[[SPTextAndLinkCell alloc] initTextCell:@""] autorelease];
[filterDataCell setEditable:YES];
[filterCol setDataCell:filterDataCell];
[filterTableView addTableColumn:filterCol];
[filterCol release];
[filterTableData setObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
[columnDefinition objectForKey:@"name"], @"name",
[columnDefinition objectForKey:@"typegrouping"], @"typegrouping",
[NSMutableArray arrayWithObjects:@"", @"", @"", @"", @"", @"", @"", @"", @"", @"", nil], SPTableContentFilterKey,
nil] forKey:[columnDefinition objectForKey:@"datacolumnindex"]];
#endif
// Set up the data cell depending on the column type
id dataCell;
if ([[columnDefinition objectForKey:@"typegrouping"] isEqualToString:@"enum"]) {
dataCell = [[[NSComboBoxCell alloc] initTextCell:@""] autorelease];
[dataCell setButtonBordered:NO];
[dataCell setBezeled:NO];
[dataCell setDrawsBackground:NO];
[dataCell setCompletes:YES];
[dataCell setControlSize:NSSmallControlSize];
// add prefs NULL value representation if NULL value is allowed for that field
if([[columnDefinition objectForKey:@"null"] boolValue])
[dataCell addItemWithObjectValue:nullValue];
[dataCell addItemsWithObjectValues:[columnDefinition objectForKey:@"values"]];
// Add a foreign key arrow if applicable
} else if ([columnDefinition objectForKey:@"foreignkeyreference"]) {
dataCell = [[[SPTextAndLinkCell alloc] initTextCell:@""] autorelease];
[dataCell setTarget:self action:@selector(clickLinkArrow:)];
// Otherwise instantiate a text-only cell
} else {
dataCell = [[[SPTextAndLinkCell alloc] initTextCell:@""] autorelease];
}
// Set the column to right-aligned for numeric data types
if ([[columnDefinition objectForKey:@"typegrouping"] isEqualToString:@"integer"]
|| [[columnDefinition objectForKey:@"typegrouping"] isEqualToString:@"float"])
{
[dataCell setAlignment:NSRightTextAlignment];
}
[dataCell setEditable:YES];
// Set the line break mode and an NSFormatter subclass which displays line breaks nicely
[dataCell setLineBreakMode:NSLineBreakByTruncatingTail];
[dataCell setFormatter:[[SPDataCellFormatter new] autorelease]];
// Set field length limit if field is a varchar to match varchar length
if ([[columnDefinition objectForKey:@"typegrouping"] isEqualToString:@"string"]
|| [[columnDefinition objectForKey:@"typegrouping"] isEqualToString:@"bit"]) {
[[dataCell formatter] setTextLimit:[[columnDefinition objectForKey:@"length"] integerValue]];
}
// Set field type for validations
[[dataCell formatter] setFieldType:[columnDefinition objectForKey:@"type"]];
// Set the data cell font according to the preferences
[dataCell setFont:tableFont];
// Assign the data cell
[theCol setDataCell:dataCell];
#ifndef SP_CODA /* prefs access */
// Set the width of this column to saved value if exists
colWidth = [[[[prefs objectForKey:SPTableColumnWidths] objectForKey:[NSString stringWithFormat:@"%@@%@", [tableDocumentInstance database], [tableDocumentInstance host]]] objectForKey:[tablesListInstance tableName]] objectForKey:[columnDefinition objectForKey:@"name"]];
if ( colWidth ) {
[theCol setWidth:[colWidth floatValue]];
}
#endif
// Set the column to be reselected for sorting if appropriate
if (sortColumnToRestore && [sortColumnToRestore isEqualToString:[columnDefinition objectForKey:@"name"]])
sortColumnNumberToRestore = [[columnDefinition objectForKey:@"datacolumnindex"] integerValue];
// Add the column to the table
[tableContentView addTableColumn:theCol];
[theCol release];
}
#ifndef SP_CODA
[filterTableView setDelegate:self];
[filterTableView setDataSource:self];
[filterTableView reloadData];
#endif
// If the table has been reloaded and the previously selected sort column is still present, reselect it.
if (sortColumnNumberToRestore != NSNotFound) {
theCol = [tableContentView tableColumnWithIdentifier:[NSString stringWithFormat:@"%lld", (long long)sortColumnNumberToRestore]];
if (sortCol) [sortCol release];
sortCol = [[NSNumber alloc] initWithInteger:sortColumnNumberToRestore];
[tableContentView setHighlightedTableColumn:theCol];
isDesc = !sortColumnToRestoreIsAsc;
if ( isDesc ) {
[tableContentView setIndicatorImage:[NSImage imageNamed:@"NSDescendingSortIndicator"] inTableColumn:theCol];
} else {
[tableContentView setIndicatorImage:[NSImage imageNamed:@"NSAscendingSortIndicator"] inTableColumn:theCol];
}
// Otherwise, clear sorting
} else {
if (sortCol) {
SPClear(sortCol);
}
isDesc = NO;
}
// Store the current first responder so filter field doesn't steal focus
id currentFirstResponder = [[tableDocumentInstance parentWindow] firstResponder];
// Enable and initialize filter fields (with tags for position of menu item and field position)
[fieldField setEnabled:YES];
[fieldField removeAllItems];
NSArray *columnTitles = ([prefs boolForKey:SPAlphabeticalTableSorting])? [columnNames sortedArrayUsingSelector:@selector(compare:)] : columnNames;
[fieldField addItemsWithTitles:columnTitles];
[compareField setEnabled:YES];
[self setCompareTypes:self];
[argumentField setEnabled:YES];
[argumentField setStringValue:@""];
[filterButton setEnabled:enableInteraction];
// Restore preserved filter settings if appropriate and valid
if (filterFieldToRestore) {
[fieldField selectItemWithTitle:filterFieldToRestore];
[self setCompareTypes:self];
if ([fieldField itemWithTitle:filterFieldToRestore]
&& ((!filterComparisonToRestore && filterValueToRestore)
|| [compareField itemWithTitle:filterComparisonToRestore]))
{
if (filterComparisonToRestore) [compareField selectItemWithTitle:filterComparisonToRestore];
if([filterComparisonToRestore isEqualToString:@"BETWEEN"]) {
[argumentField setHidden:YES];
if (firstBetweenValueToRestore) [firstBetweenField setStringValue:firstBetweenValueToRestore];
if (secondBetweenValueToRestore) [secondBetweenField setStringValue:secondBetweenValueToRestore];
} else {
if (filterValueToRestore) [argumentField setStringValue:filterValueToRestore];
}
[self toggleFilterField:self];
}
}
// Restore page number if limiting is set
if ([prefs boolForKey:SPLimitResults])
contentPage = pageToRestore;
// Restore first responder
[[tableDocumentInstance parentWindow] makeFirstResponder:currentFirstResponder];
// Set the state of the table buttons
[addButton setEnabled:(enableInteraction && [tablesListInstance tableType] == SPTableTypeTable)];
[duplicateButton setEnabled:NO];
[removeButton setEnabled:NO];
// Reset the table store if required - basically if the table is being changed,
// reassigning before emptying for thread safety.
if (!previousTableRowsCount) {
[self clearTableValues];
}
#ifndef SP_CODA
[filterTableView reloadData];
#endif
}
/**
* Remove all items from the current table value store. Do this by
* reassigning the tableValues store and releasing the old location,
* while setting thread safety flags.
*/
- (void) clearTableValues
{
SPDataStorage *tableValuesTransition;
tableValuesTransition = tableValues;
pthread_mutex_lock(&tableValuesLock);
tableRowsCount = 0;
tableValues = [[SPDataStorage alloc] init];
[tableContentView setTableData:tableValues];
pthread_mutex_unlock(&tableValuesLock);
[tableValuesTransition release];
}
/**
* Reload the table data without reconfiguring the tableView,
* using filters and limits as appropriate.
* Will not refresh the table view itself.
* Note that this does not empty the table array - see use of previousTableRowsCount.
*/
- (void) loadTableValues
{
// If no table is selected, return
if (!selectedTable) return;
NSMutableString *queryString;
NSString *queryStringBeforeLimit = nil;
NSString *filterString;
SPMySQLStreamingResultStore *resultStore;
NSInteger rowsToLoad = [[tableDataInstance statusValueForKey:@"Rows"] integerValue];
#ifndef SP_CODA
[[countText onMainThread] setStringValue:NSLocalizedString(@"Loading table data...", @"Loading table data string")];
#endif
// Notify any listeners that a query has started
[[NSNotificationCenter defaultCenter] postNotificationOnMainThreadWithName:@"SMySQLQueryWillBePerformed" object:tableDocumentInstance];
// Start construction of the query string
queryString = [NSMutableString stringWithFormat:@"SELECT %@%@ FROM %@",
#ifndef SP_CODA
(activeFilter == 1 && [self tableFilterString] && filterTableDistinct) ? @"DISTINCT " :
#endif
@"",
[self fieldListForQuery], [selectedTable backtickQuotedString]];
// Add a filter string if appropriate
filterString = [[self onMainThread] tableFilterString];
if (filterString) {
[queryString appendFormat:@" WHERE %@", filterString];
isFiltered = YES;
} else {
isFiltered = NO;
}
// Add sorting details if appropriate
if (sortCol) {
[queryString appendFormat:@" ORDER BY %@", [[[dataColumns objectAtIndex:[sortCol integerValue]] objectForKey:@"name"] backtickQuotedString]];
if (isDesc) [queryString appendString:@" DESC"];
}
// Check to see if a limit needs to be applied
if ([prefs boolForKey:SPLimitResults])
{
// Ensure the page supplied is within the appropriate limits
if (contentPage <= 0)
contentPage = 1;
else if (contentPage > 1 && (NSInteger)(contentPage - 1) * [prefs integerForKey:SPLimitResultsValue] >= maxNumRows)
contentPage = ceilf((CGFloat)maxNumRows / [prefs floatForKey:SPLimitResultsValue]);
// If the result set is from a late page, take a copy of the string to allow resetting limit
// if no results are found
if (contentPage > 1) {
queryStringBeforeLimit = [NSString stringWithString:queryString];
}
// Append the limit settings
[queryString appendFormat:@" LIMIT %ld,%ld", (long)((contentPage-1)*[prefs integerForKey:SPLimitResultsValue]), (long)[prefs integerForKey:SPLimitResultsValue]];
// Update the approximate count of the rows to load
rowsToLoad = rowsToLoad - (contentPage-1)*[prefs integerForKey:SPLimitResultsValue];
if (rowsToLoad > [prefs integerForKey:SPLimitResultsValue]) rowsToLoad = [prefs integerForKey:SPLimitResultsValue];
}
// If within a task, allow this query to be cancelled
[tableDocumentInstance enableTaskCancellationWithTitle:NSLocalizedString(@"Stop", @"stop button") callbackObject:nil callbackFunction:NULL];
// Perform and process the query
[tableContentView performSelectorOnMainThread:@selector(noteNumberOfRowsChanged) withObject:nil waitUntilDone:YES];
[self setUsedQuery:queryString];
resultStore = [[mySQLConnection resultStoreFromQueryString:queryString] retain];
// Ensure the number of columns are unchanged; if the column count has changed, abort the load
// and queue a full table reload.
BOOL fullTableReloadRequired = NO;
if (resultStore && [dataColumns count] != [resultStore numberOfFields]) {
[tableDocumentInstance disableTaskCancellation];
[mySQLConnection cancelCurrentQuery];
[resultStore cancelResultLoad];
fullTableReloadRequired = YES;
}
// Process the result into the data store
if (!fullTableReloadRequired && resultStore) {
[self updateResultStore:resultStore approximateRowCount:rowsToLoad];
}
if (resultStore) [resultStore release];
// If the result is empty, and a late page is selected, reset the page
if (!fullTableReloadRequired && [prefs boolForKey:SPLimitResults] && queryStringBeforeLimit && !tableRowsCount && ![mySQLConnection lastQueryWasCancelled]) {
contentPage = 1;
previousTableRowsCount = tableRowsCount;
queryString = [NSMutableString stringWithFormat:@"%@ LIMIT 0,%ld", queryStringBeforeLimit, (long)[prefs integerForKey:SPLimitResultsValue]];
[self setUsedQuery:queryString];
resultStore = [[mySQLConnection resultStoreFromQueryString:queryString] retain];
if (resultStore) {
[self updateResultStore:resultStore approximateRowCount:[prefs integerForKey:SPLimitResultsValue]];
[resultStore release];
}
}
if ([mySQLConnection lastQueryWasCancelled] || [mySQLConnection queryErrored])
isInterruptedLoad = YES;
else
isInterruptedLoad = NO;
// End cancellation ability
[tableDocumentInstance disableTaskCancellation];
// Restore selection indexes if appropriate
if (selectionToRestore) {
BOOL previousTableRowsSelectable = tableRowsSelectable;
tableRowsSelectable = YES;
NSMutableIndexSet *selectionSet = [NSMutableIndexSet indexSet];
// Currently two types of stored selection are supported: primary keys and direct index sets.
if ([[selectionToRestore objectForKey:@"type"] isEqualToString:SPSelectionDetailTypePrimaryKeyed]) {
// Check whether the keys are still present and get their positions
BOOL columnsFound = YES;
NSArray *primaryKeyFieldNames = [selectionToRestore objectForKey:@"keys"];
NSUInteger primaryKeyFieldCount = [primaryKeyFieldNames count];
NSUInteger *primaryKeyFieldIndexes = calloc(primaryKeyFieldCount, sizeof(NSUInteger));
for (NSUInteger i = 0; i < primaryKeyFieldCount; i++) {
primaryKeyFieldIndexes[i] = [[tableDataInstance columnNames] indexOfObject:[primaryKeyFieldNames objectAtIndex:i]];
if (primaryKeyFieldIndexes[i] == NSNotFound) {
columnsFound = NO;
}
}
// Only proceed with reselection if all columns were found
if (columnsFound && primaryKeyFieldCount) {
NSDictionary *selectionKeysToRestore = [selectionToRestore objectForKey:@"rows"];
NSUInteger rowsToSelect = [selectionKeysToRestore count];
BOOL rowMatches = NO;
for (NSUInteger i = 0; i < tableRowsCount; i++) {
// For single-column primary keys look up the cell value in the dictionary for a match
if (primaryKeyFieldCount == 1) {
if ([selectionKeysToRestore objectForKey:SPDataStorageObjectAtRowAndColumn(tableValues, i, primaryKeyFieldIndexes[0])]) {
rowMatches = YES;
}
// For multi-column primary keys, convert all the cells to a string for lookup.
} else {
NSMutableString *lookupString = [[NSMutableString alloc] initWithString:[SPDataStorageObjectAtRowAndColumn(tableValues, i, primaryKeyFieldIndexes[0]) description]];
for (NSUInteger j = 1; j < primaryKeyFieldCount; j++) {
[lookupString appendString:SPUniqueSchemaDelimiter];
[lookupString appendString:[SPDataStorageObjectAtRowAndColumn(tableValues, i, primaryKeyFieldIndexes[j]) description]];
}
if ([selectionKeysToRestore objectForKey:lookupString]) rowMatches = YES;
[lookupString release];
}
if (rowMatches) {
[selectionSet addIndex:i];
rowsToSelect--;
if (rowsToSelect <= 0) break;
rowMatches = NO;
}
}
}
free(primaryKeyFieldIndexes);
} else if ([[selectionToRestore objectForKey:@"type"] isEqualToString:SPSelectionDetailTypeIndexed]) {
selectionSet = [selectionToRestore objectForKey:@"rows"];
}
[[tableContentView onMainThread] selectRowIndexes:selectionSet byExtendingSelection:NO];
tableRowsSelectable = previousTableRowsSelectable;
}
if ([prefs boolForKey:SPLimitResults] && (contentPage > 1 || (NSInteger)tableRowsCount == [prefs integerForKey:SPLimitResultsValue]))
{
isLimited = YES;
} else {
isLimited = NO;
}
// Update the rows count as necessary
[self updateNumberOfRows];
// Set the filter text
[self updateCountText];
// Update pagination
[[self onMainThread] updatePaginationState];
// Retrieve and cache the column definitions for editing views
if (cqColumnDefinition) [cqColumnDefinition release];
cqColumnDefinition = [[resultStore fieldDefinitions] retain];
// Notify listenters that the query has finished
[[NSNotificationCenter defaultCenter] postNotificationOnMainThreadWithName:@"SMySQLQueryHasBeenPerformed" object:tableDocumentInstance];
if ([mySQLConnection queryErrored] && ![mySQLConnection lastQueryWasCancelled]) {
#ifndef SP_CODA
if(activeFilter == 0) {
#endif
if(filterString)
SPBeginAlertSheet(NSLocalizedString(@"Error", @"error"), NSLocalizedString(@"OK", @"OK button"), nil, nil, [tableDocumentInstance parentWindow], self, nil, nil,
[NSString stringWithFormat:NSLocalizedString(@"The table data couldn't be loaded presumably due to used filter clause. \n\nMySQL said: %@", @"message of panel when loading of table failed and presumably due to used filter argument"), [mySQLConnection lastErrorMessage]]);
else
SPBeginAlertSheet(NSLocalizedString(@"Error", @"error"), NSLocalizedString(@"OK", @"OK button"), nil, nil, [tableDocumentInstance parentWindow], self, nil, nil,
[NSString stringWithFormat:NSLocalizedString(@"The table data couldn't be loaded.\n\nMySQL said: %@", @"message of panel when loading of table failed"), [mySQLConnection lastErrorMessage]]);
}
#ifndef SP_CODA
// Filter task came from filter table
else if(activeFilter == 1){
[filterTableWindow setTitle:[NSString stringWithFormat:@"%@ – %@", NSLocalizedString(@"Filter", @"filter label"), NSLocalizedString(@"WHERE clause not valid", @"WHERE clause not valid")]];
}