/
SPDataImport.m
1807 lines (1554 loc) · 74.1 KB
/
SPDataImport.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
//
// SPDataImport.m
// sequel-pro
//
// Created by Lorenz Textor (lorenz@textor.ch) on Wed May 1, 2002.
// Copyright (c) 2002-2003 Lorenz Textor. All rights reserved.
// Copyright (c) 2012 Sequel Pro Team. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
//
// More info at <https://github.com/sequelpro/sequelpro>
#import "SPDataImport.h"
#import "SPDatabaseDocument.h"
#import "SPTablesList.h"
#import "SPTableStructure.h"
#import "SPDatabaseStructure.h"
#import "SPTableContent.h"
#import "SPCustomQuery.h"
#import "SPGrowlController.h"
#import "SPSQLParser.h"
#import "SPCSVParser.h"
#import "SPTableData.h"
#import "RegexKitLite.h"
#import "SPAlertSheets.h"
#import "SPFieldMapperController.h"
#import "SPFileHandle.h"
#import "SPEncodingPopupAccessory.h"
#import "SPThreadAdditions.h"
#import "SPFunctions.h"
#import <SPMySQL/SPMySQL.h>
#define SP_FILE_READ_ERROR_STRING NSLocalizedString(@"File read error", @"File read error title (Import Dialog)")
@interface SPDataImport ()
- (void)_startBackgroundImportTaskForFilename:(NSString *)filename;
- (void)_importBackgroundProcess:(NSDictionary *)userInfo;
- (void)_resetFieldMappingGlobals;
@end
@implementation SPDataImport
#pragma mark -
#pragma mark Initialisation
- (id)init
{
if ((self = [super init])) {
nibObjectsToRelease = [[NSMutableArray alloc] init];
geometryFields = [[NSMutableArray alloc] init];
geometryFieldsMapIndex = [[NSMutableIndexSet alloc] init];
bitFields = [[NSMutableArray alloc] init];
bitFieldsMapIndex = [[NSMutableIndexSet alloc] init];
nullableNumericFields = [[NSMutableArray alloc] init];
nullableNumericFieldsMapIndex = [[NSMutableIndexSet alloc] init];
fieldMappingArray = nil;
fieldMappingGlobalValueArray = nil;
fieldMappingTableColumnNames = nil;
fieldMappingTableDefaultValues = nil;
fieldMappingImportArray = nil;
csvImportTailString = nil;
csvImportHeaderString = nil;
csvImportMethodHasTail = NO;
fieldMappingImportArrayIsPreview = NO;
fieldMappingArrayHasGlobalVariables = NO;
importMethodIsUpdate = NO;
importIntoNewTable = NO;
insertRemainingRowsAfterUpdate = NO;
numberOfImportDataColumns = 0;
selectedTableTarget = nil;
targetTableDetails = nil;
prefs = nil;
lastFilename = nil;
_mainNibLoaded = NO;
}
return self;
}
- (void)awakeFromNib
{
if (_mainNibLoaded) return;
_mainNibLoaded = YES;
// Load the import accessory view, retaining a reference to the top-level objects that need releasing.
NSArray *importAccessoryTopLevelObjects = nil;
NSNib *nibLoader = [[NSNib alloc] initWithNibNamed:@"ImportAccessory" bundle:[NSBundle mainBundle]];
[nibLoader instantiateNibWithOwner:self topLevelObjects:&importAccessoryTopLevelObjects];
[nibObjectsToRelease addObjectsFromArray:importAccessoryTopLevelObjects];
[nibLoader release];
// Set the accessory view's tabview to tabless (left in for easier editing in IB)
[importTabView setTabViewType:NSNoTabsNoBorder];
// Set up the encodings menu
NSMutableArray *encodings = [NSMutableArray arrayWithArray:[SPEncodingPopupAccessory enabledEncodings]];
[importEncodingPopup removeAllItems];
[importEncodingPopup addItemWithTitle:NSLocalizedString(@"Autodetect", @"Encoding autodetect menu item")];
[[importEncodingPopup menu] addItem:[NSMenuItem separatorItem]];
for (NSNumber *encodingNumber in encodings) {
[importEncodingPopup addItemWithTitle:[NSString localizedNameOfStringEncoding:[encodingNumber unsignedIntegerValue]]];
[[importEncodingPopup lastItem] setTag:[encodingNumber unsignedIntegerValue]];
}
}
#pragma mark -
#pragma mark IBAction methods
/**
* Shows/hides the CSV options accessory view based on the selected format.
*/
- (IBAction)changeFormat:(id)sender
{
[importTabView selectTabViewItemAtIndex:[importFormatPopup indexOfSelectedItem]];
}
/**
* Cancels the current operation.
*/
- (IBAction)cancelProgressBar:(id)sender
{
progressCancelled = YES;
}
/**
* Common method for ending modal sessions
*/
- (IBAction)closeSheet:(id)sender
{
[NSApp endSheet:[sender window] returnCode:[sender tag]];
[[sender window] orderOut:self];
}
/**
* Convenience method for closing and restoring the progress sheet to default state.
*/
- (void)closeAndStopProgressSheet
{
SPMainQSync(^{
[NSApp endSheet:singleProgressSheet];
[singleProgressBar setIndeterminate:YES];
[singleProgressSheet orderOut:nil];
[singleProgressBar stopAnimation:self];
[singleProgressBar setMaxValue:100];
});
}
#pragma mark -
#pragma mark Import construction methods
/**
* Invoked when user clicks on an ImportFromClipboard menuitem.
*/
- (void)importFromClipboard
{
// clipboard textview with no wrapping
const CGFloat LargeNumberForText = 1.0e7f;
[[importFromClipboardTextView textContainer] setContainerSize:NSMakeSize(LargeNumberForText, LargeNumberForText)];
[[importFromClipboardTextView textContainer] setWidthTracksTextView:NO];
[[importFromClipboardTextView textContainer] setHeightTracksTextView:NO];
[importFromClipboardTextView setAutoresizingMask:NSViewNotSizable];
[importFromClipboardTextView setMaxSize:NSMakeSize(LargeNumberForText, LargeNumberForText)];
[importFromClipboardTextView setHorizontallyResizable:YES];
[importFromClipboardTextView setVerticallyResizable:YES];
[importFromClipboardTextView setFont:[NSFont fontWithName:@"Monaco" size:11.0f]];
if([[[NSPasteboard generalPasteboard] stringForType:NSStringPboardType] length] > 4000)
[importFromClipboardTextView setString:[[[[NSPasteboard generalPasteboard] stringForType:NSStringPboardType] substringToIndex:4000] stringByAppendingString:@"\n…"]];
else
[importFromClipboardTextView setString:[[NSPasteboard generalPasteboard] stringForType:NSStringPboardType]];
// Preset the accessory view with prefs defaults
[importFieldsTerminatedField setStringValue:[prefs objectForKey:SPCSVImportFieldTerminator]];
[importLinesTerminatedField setStringValue:[prefs objectForKey:SPCSVImportLineTerminator]];
[importFieldsEscapedField setStringValue:[prefs objectForKey:SPCSVImportFieldEscapeCharacter]];
[importFieldsEnclosedField setStringValue:[prefs objectForKey:SPCSVImportFieldEnclosedBy]];
[importFieldNamesSwitch setState:[[prefs objectForKey:SPCSVImportFirstLineIsHeader] boolValue]];
// Reset and disable the encoding menu
[importEncodingPopup selectItemWithTag:NSUTF8StringEncoding];
[importEncodingPopup setEnabled:NO];
// Add the view, and resize it to fit the accessory view size
[importFromClipboardAccessoryView addSubview:importView];
NSRect accessoryViewRect = [importFromClipboardAccessoryView frame];
[importView setFrame:NSMakeRect(0, 0, accessoryViewRect.size.width, accessoryViewRect.size.height)];
[NSApp beginSheet:importFromClipboardSheet
modalForWindow:[tableDocumentInstance parentWindow]
modalDelegate:self
didEndSelector:@selector(importFromClipboardSheetDidEnd:returnCode:contextInfo:)
contextInfo:nil];
}
/**
* Callback when the import from clipback sheet is closed
*/
- (void)importFromClipboardSheetDidEnd:(id)sheet returnCode:(NSInteger)returnCode contextInfo:(NSString *)contextInfo
{
// Reset the interface and store prefs
[importFromClipboardTextView setString:@""];
[prefs setObject:[[importFormatPopup selectedItem] title] forKey:@"importFormatPopupValue"];
// Check if the user canceled
if (returnCode != NSOKButton)
return;
// Reset progress cancelled from any previous runs
progressCancelled = NO;
NSString *importFileName = [NSString stringWithFormat:@"%@%@",
SPImportClipboardTempFileNamePrefix,
[[NSDate date] descriptionWithCalendarFormat:@"%H%M%S"
timeZone:nil
locale:[[NSUserDefaults standardUserDefaults] dictionaryRepresentation]]];
// Write clipboard content to temp file using the connection encoding
NSStringEncoding encoding;
if ([[[importFormatPopup selectedItem] title] isEqualToString:@"SQL"])
encoding = NSUTF8StringEncoding;
else
encoding = [mySQLConnection stringEncoding];
if(![[[NSPasteboard generalPasteboard] stringForType:NSStringPboardType] writeToFile:importFileName atomically:NO encoding:encoding error:nil]) {
NSBeep();
NSLog(@"Couldn't write clipboard content to temporary file.");
return;
}
if (importFileName == nil) return;
// Begin import process
[self _startBackgroundImportTaskForFilename:importFileName];
}
/**
* Invoked when user clicks on an import menuitem.
*/
- (void)importFile
{
// prepare open panel and accessory view
NSOpenPanel *openPanel = [NSOpenPanel openPanel];
// Preset the accessory view with prefs defaults
[importFieldsTerminatedField setStringValue:[prefs objectForKey:SPCSVImportFieldTerminator]];
[importLinesTerminatedField setStringValue:[prefs objectForKey:SPCSVImportLineTerminator]];
[importFieldsEscapedField setStringValue:[prefs objectForKey:SPCSVImportFieldEscapeCharacter]];
[importFieldsEnclosedField setStringValue:[prefs objectForKey:SPCSVImportFieldEnclosedBy]];
[importFieldNamesSwitch setState:[[prefs objectForKey:SPCSVImportFirstLineIsHeader] boolValue]];
[openPanel setAccessoryView:importView];
[openPanel setDelegate:self];
if ([prefs valueForKey:@"importFormatPopupValue"]) {
[importFormatPopup selectItemWithTitle:[prefs valueForKey:@"importFormatPopupValue"]];
[self changeFormat:self];
}
if (lastFilename && [lastFilename lastPathComponent]) {
[openPanel setNameFieldStringValue:[lastFilename lastPathComponent]];
}
NSString *openPath;
if((openPath = [prefs objectForKey:@"openPath"])) {
// Doc says calling +[NSURL URLWithString:] with nil is fine,
// but at least on 10.6 this will cause an exception
[openPanel setDirectoryURL:[NSURL URLWithString:openPath]];
}
[openPanel beginSheetModalForWindow:[tableDocumentInstance parentWindow] completionHandler:^(NSInteger returnCode) {
// Ensure text inputs are completed, preventing dead character entry
[openPanel makeFirstResponder:nil];
// Save values to preferences
[prefs setObject:[[openPanel directoryURL] path] forKey:@"openPath"];
[prefs setObject:[[importFormatPopup selectedItem] title] forKey:@"importFormatPopupValue"];
// Close NSOpenPanel sheet
[openPanel orderOut:self];
// Check if the user canceled
if (returnCode != NSOKButton) return;
// Reset progress cancelled from any previous runs
progressCancelled = NO;
if (lastFilename) SPClear(lastFilename);
lastFilename = [[NSString stringWithString:[[openPanel URL] path]] retain];
NSString *importFileName = [NSString stringWithString:lastFilename];
if (lastFilename == nil || ![lastFilename length]) {
NSBeep();
return;
}
if (importFileName == nil) return;
// Begin the import process
[self _startBackgroundImportTaskForFilename:importFileName];
}];
}
/**
* Invoked when the user opens a large file, and when warned, chooses "Import".
*/
- (void)startSQLImportProcessWithFile:(NSString *)filename
{
[importFormatPopup selectItemWithTitle:@"SQL"];
[self _startBackgroundImportTaskForFilename:filename];
}
#pragma mark -
#pragma mark SQL import
/**
* Streaming data processing method to import a supplied SQL file.
*
* The file is read in chunk by chunk; each chunk is then checked
* for line endings, which are used to split the data into parts
* which can be parsed to NSStrings in the appropriate encoding.
*
* The NSStrings are then fed to a SQL parser, which splits them
* into statements ready to be executed.
*/
- (void)importSQLFile:(NSString *)filename
{
NSAutoreleasePool *importPool;
SPFileHandle *sqlFileHandle;
NSMutableData *sqlDataBuffer;
const unsigned char *sqlDataBufferBytes;
NSData *fileChunk;
NSString *sqlString;
SPSQLParser *sqlParser;
NSString *query;
NSMutableString *errors = [NSMutableString string];
NSInteger fileChunkMaxLength = 1024 * 1024;
NSUInteger fileTotalLength = 0;
NSUInteger fileProcessedLength = 0;
NSInteger queriesPerformed = 0;
NSInteger dataBufferLength = 0;
NSInteger dataBufferPosition = 0;
NSInteger dataBufferLastQueryEndPosition = 0;
BOOL fileIsCompressed;
BOOL allDataRead = NO;
BOOL ignoreSQLErrors = ([importSQLErrorHandlingPopup selectedTag] == SPSQLImportIgnoreErrors);
BOOL ignoreCharsetError = NO;
NSStringEncoding sqlEncoding = NSUTF8StringEncoding;
NSString *connectionEncodingToRestore = nil;
NSCharacterSet *whitespaceAndNewlineCharset = [NSCharacterSet whitespaceAndNewlineCharacterSet];
// Start the notification timer to allow notifications to be shown, even if frontmost, for long queries
[[SPGrowlController sharedGrowlController] setVisibilityForNotificationName:@"Import Finished"];
// Open a filehandle for the SQL file
sqlFileHandle = [SPFileHandle fileHandleForReadingAtPath:filename];
if (!sqlFileHandle) {
SPOnewayAlertSheet(
NSLocalizedString(@"Import Error", @"Import Error title"),
[tableDocumentInstance parentWindow],
NSLocalizedString(@"The SQL file you selected could not be found or read.", @"SQL file open error")
);
if([filename hasPrefix:SPImportClipboardTempFileNamePrefix])
[[NSFileManager defaultManager] removeItemAtPath:filename error:nil];
return;
}
fileIsCompressed = ([sqlFileHandle compressionFormat] != SPNoCompression);
// Grab the file length
fileTotalLength = (NSUInteger)[[[[NSFileManager defaultManager] attributesOfItemAtPath:filename error:NULL] objectForKey:NSFileSize] longLongValue];
if (!fileTotalLength) fileTotalLength = 1;
SPMainQSync(^{
// Reset progress interface
[errorsView setString:@""];
[singleProgressTitle setStringValue:NSLocalizedString(@"Importing SQL", @"text showing that the application is importing SQL")];
[singleProgressText setStringValue:NSLocalizedString(@"Reading...", @"text showing that app is reading dump")];
[singleProgressBar setIndeterminate:NO];
[singleProgressBar setMaxValue:fileTotalLength];
[singleProgressBar setUsesThreadedAnimation:YES];
[singleProgressBar startAnimation:self];
// Open the progress sheet
[NSApp beginSheet:singleProgressSheet modalForWindow:[tableDocumentInstance parentWindow] modalDelegate:self didEndSelector:nil contextInfo:nil];
[singleProgressSheet makeKeyWindow];
});
[tableDocumentInstance setQueryMode:SPImportExportQueryMode];
// Determine the file encoding. The first item in the encoding menu is "Autodetect"; if
// this is selected, attempt to detect the encoding of the file
if (![importEncodingPopup indexOfSelectedItem]) {
sqlEncoding = [[NSFileManager defaultManager] detectEncodingforFileAtPath:filename];
if ([SPMySQLConnection mySQLCharsetForStringEncoding:sqlEncoding]) {
connectionEncodingToRestore = [mySQLConnection encoding];
[mySQLConnection queryString:[NSString stringWithFormat:@"SET NAMES '%@'", [SPMySQLConnection mySQLCharsetForStringEncoding:sqlEncoding]]];
}
// Otherwise, get the encoding to use from the menu
} else {
sqlEncoding = [importEncodingPopup selectedTag];
}
// Read in the file in a loop
sqlParser = [[SPSQLParser alloc] init];
[sqlParser setDelimiterSupport:YES];
sqlDataBuffer = [[NSMutableData alloc] init];
importPool = [[NSAutoreleasePool alloc] init];
while (1) {
if (progressCancelled) break;
@try {
fileChunk = [sqlFileHandle readDataOfLength:fileChunkMaxLength];
}
// Report file read errors, and bail
@catch (NSException *exception) {
if (connectionEncodingToRestore) {
[mySQLConnection queryString:[NSString stringWithFormat:@"SET NAMES '%@'", connectionEncodingToRestore]];
}
[self closeAndStopProgressSheet];
SPOnewayAlertSheet(
SP_FILE_READ_ERROR_STRING,
[tableDocumentInstance parentWindow],
[NSString stringWithFormat:NSLocalizedString(@"An error occurred when reading the file.\n\nOnly %ld queries were executed.\n\n(%@)", @"SQL read error, including detail from system"), (long)queriesPerformed, [exception reason]]
);
[sqlParser release];
[sqlDataBuffer release];
[importPool drain];
[tableDocumentInstance setQueryMode:SPInterfaceQueryMode];
if([filename hasPrefix:SPImportClipboardTempFileNamePrefix])
[[NSFileManager defaultManager] removeItemAtPath:filename error:nil];
return;
}
// If no data returned, end of file - set a marker to ensure full processing
if (!fileChunk || ![fileChunk length]) {
allDataRead = YES;
// Otherwise add the data to the read/parse buffer
} else {
[sqlDataBuffer appendData:fileChunk];
}
// Step through the data buffer, identifying line endings to parse the data with
sqlDataBufferBytes = [sqlDataBuffer bytes];
dataBufferLength = [sqlDataBuffer length];
for ( ; dataBufferPosition < dataBufferLength || allDataRead; dataBufferPosition++) {
if (sqlDataBufferBytes[dataBufferPosition] == 0x0A || sqlDataBufferBytes[dataBufferPosition] == 0x0D || allDataRead) {
// Keep reading through any other line endings
while (dataBufferPosition + 1 < dataBufferLength
&& (sqlDataBufferBytes[dataBufferPosition+1] == 0x0A
|| sqlDataBufferBytes[dataBufferPosition+1] == 0x0D))
{
dataBufferPosition++;
}
// Try to generate a NSString with the resulting data
sqlString = [[NSString alloc] initWithData:[sqlDataBuffer subdataWithRange:NSMakeRange(dataBufferLastQueryEndPosition, dataBufferPosition - dataBufferLastQueryEndPosition)]
encoding:sqlEncoding];
if (!sqlString) {
if (connectionEncodingToRestore) {
[mySQLConnection queryString:[NSString stringWithFormat:@"SET NAMES '%@'", connectionEncodingToRestore]];
}
[self closeAndStopProgressSheet];
NSString *displayEncoding;
if (![importEncodingPopup indexOfSelectedItem]) {
displayEncoding = [NSString stringWithFormat:@"%@ - %@", [importEncodingPopup titleOfSelectedItem], [NSString localizedNameOfStringEncoding:sqlEncoding]];
} else {
displayEncoding = [NSString localizedNameOfStringEncoding:sqlEncoding];
}
SPOnewayAlertSheet(
SP_FILE_READ_ERROR_STRING,
[tableDocumentInstance parentWindow],
[NSString stringWithFormat:NSLocalizedString(@"An error occurred when reading the file, as it could not be read in the encoding you selected (%@).\n\nOnly %ld queries were executed.", @"SQL encoding read error"), displayEncoding, (long)queriesPerformed]
);
[sqlParser release];
[sqlDataBuffer release];
[importPool drain];
[tableDocumentInstance setQueryMode:SPInterfaceQueryMode];
if([filename hasPrefix:SPImportClipboardTempFileNamePrefix])
[[NSFileManager defaultManager] removeItemAtPath:filename error:nil];
return;
}
// Add the NSString segment to the SQL parser and release it
[sqlParser appendString:sqlString];
[sqlString release];
if (allDataRead) break;
// Increment the query end position marker
dataBufferLastQueryEndPosition = dataBufferPosition;
}
}
// Trim the data buffer if part of it was used
if (dataBufferLastQueryEndPosition) {
[sqlDataBuffer setData:[sqlDataBuffer subdataWithRange:NSMakeRange(dataBufferLastQueryEndPosition, dataBufferLength - dataBufferLastQueryEndPosition)]];
dataBufferPosition -= dataBufferLastQueryEndPosition;
dataBufferLastQueryEndPosition = 0;
}
// Before entering the following loop, check that we actually have a connection.
// If not, check the connection if appropriate and then clean up and exit if appropriate.
if (![mySQLConnection isConnected] && ([mySQLConnection userTriggeredDisconnect] || ![mySQLConnection checkConnection])) {
if ([filename hasPrefix:SPImportClipboardTempFileNamePrefix])
[[NSFileManager defaultManager] removeItemAtPath:filename error:nil];
[self closeAndStopProgressSheet];
[errors appendString:NSLocalizedString(@"The connection to the server was lost during the import. The import is only partially complete.", @"Connection lost during import error message")];
[self showErrorSheetWithMessage:errors];
[sqlParser release];
[sqlDataBuffer release];
[importPool drain];
return;
}
// Extract and process any complete SQL queries that can be found in the strings parsed so far
while ((query = [sqlParser trimAndReturnStringToCharacter:';' trimmingInclusively:YES returningInclusively:NO])) {
if (progressCancelled) break;
fileProcessedLength += [query lengthOfBytesUsingEncoding:sqlEncoding] + 1;
// Ensure whitespace is removed from both ends, and normalise if necessary.
if ([sqlParser containsCarriageReturns]) {
query = [SPSQLParser normaliseQueryForExecution:query];
} else {
query = [query stringByTrimmingCharactersInSet:whitespaceAndNewlineCharset];
}
// Skip blank or whitespace-only queries to avoid errors
if (![query length]) continue;
// Run the query
[mySQLConnection queryString:query usingEncoding:sqlEncoding withResultType:SPMySQLResultAsResult];
// Check for any errors
if ([mySQLConnection queryErrored] && ![[mySQLConnection lastErrorMessage] isEqualToString:@"Query was empty"]) {
[errors appendFormat:NSLocalizedString(@"[ERROR in query %ld] %@\n", @"error text when multiple custom query failed"), (long)(queriesPerformed+1), [mySQLConnection lastErrorMessage]];
// if the error is about utf8mb4 not being supported by the server display a more helpful message.
// Note: the same error will occur when doing CREATE TABLE... with utf8mb4.
if([mySQLConnection lastErrorID] == 1115 && [[mySQLConnection lastErrorMessage] rangeOfString:@"utf8mb4" options:NSCaseInsensitiveSearch].location != NSNotFound && [query rangeOfString:@"SET NAMES" options:NSCaseInsensitiveSearch].location != NSNotFound) {
if(!ignoreCharsetError) {
__block NSInteger charsetErrorSheetReturnCode;
SPMainQSync(^{
NSAlert *charsetErrorAlert = [NSAlert alertWithMessageText:NSLocalizedString(@"Incompatible encoding in SQL file", @"sql import error message")
defaultButton:NSLocalizedString(@"Import Anyway", @"sql import : charset error alert : continue button")
alternateButton:NSLocalizedString(@"Cancel Import", @"sql import : charset error alert : cancel button")
otherButton:nil
informativeTextWithFormat:NSLocalizedString(@"The SQL file uses utf8mb4 encoding, but your MySQL version only supports the limited utf8 subset.\n\nYou can continue the import, but any non-BMP characters in the SQL file (eg. some typographic and scientific special characters, archaic CJK logograms, emojis) will be unrecoverably lost!", @"sql import : charset error alert : detail message")];
[charsetErrorAlert setAlertStyle:NSWarningAlertStyle];
charsetErrorSheetReturnCode = [charsetErrorAlert runModal];
});
switch (charsetErrorSheetReturnCode) {
// don't display the message a second time
case NSAlertDefaultReturn:
ignoreCharsetError = YES;
break;
// Otherwise, stop
default:
[errors appendString:NSLocalizedString(@"Import cancelled!\n", @"import cancelled message")];
progressCancelled = YES;
}
}
}
// If not set to ignore errors, ask what to do. Use NSAlert rather than
// SPBeginWaitingAlertSheet as there is already a modal sheet in progress.
else if (!ignoreSQLErrors) {
__block NSInteger sqlImportErrorSheetReturnCode;
SPMainQSync(^{
NSAlert *sqlErrorAlert = [NSAlert alertWithMessageText:NSLocalizedString(@"An error occurred while importing SQL", @"sql import error message")
defaultButton:NSLocalizedString(@"Continue", @"continue button")
alternateButton:NSLocalizedString(@"Ignore All Errors", @"ignore errors button")
otherButton:NSLocalizedString(@"Stop", @"stop button")
informativeTextWithFormat:NSLocalizedString(@"[ERROR in query %ld] %@\n", @"error text when multiple custom query failed"), (long)(queriesPerformed+1), [mySQLConnection lastErrorMessage]];
[sqlErrorAlert setAlertStyle:NSWarningAlertStyle];
sqlImportErrorSheetReturnCode = [sqlErrorAlert runModal];
});
switch (sqlImportErrorSheetReturnCode) {
// On "continue", no additional action is required
case NSAlertDefaultReturn:
break;
// Ignore all future errors if asked to
case NSAlertAlternateReturn:
ignoreSQLErrors = YES;
break;
// Otherwise, stop
default:
[errors appendString:NSLocalizedString(@"Import cancelled!\n", @"import cancelled message")];
progressCancelled = YES;
}
}
}
// Increment the processed queries count
queriesPerformed++;
// Update the progress bar
if (fileIsCompressed) {
[singleProgressBar setDoubleValue:[sqlFileHandle realDataReadLength]];
[singleProgressText setStringValue:[NSString stringWithFormat:NSLocalizedString(@"Imported %@ of SQL", @"SQL import progress text where total size is unknown"),
[NSString stringForByteSize:fileProcessedLength]]];
} else {
[singleProgressBar setDoubleValue:fileProcessedLength];
[singleProgressText setStringValue:[NSString stringWithFormat:NSLocalizedString(@"Imported %@ of %@", @"SQL import progress text"),
[NSString stringForByteSize:fileProcessedLength], [NSString stringForByteSize:fileTotalLength]]];
}
}
// If all the data has been read, break out of the processing loop
if (allDataRead) break;
// Reset the autorelease pool
[importPool drain];
importPool = [[NSAutoreleasePool alloc] init];
}
// If any text remains in the SQL parser, it's an unterminated query - execute it.
query = [sqlParser stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
if ([query length] && !progressCancelled) {
// Run the query
[mySQLConnection queryString:query usingEncoding:sqlEncoding withResultType:SPMySQLResultAsResult];
// Check for any errors
if ([mySQLConnection queryErrored] && ![[mySQLConnection lastErrorMessage] isEqualToString:@"Query was empty"]) {
[errors appendFormat:NSLocalizedString(@"[ERROR in query %ld] %@\n", @"error text when multiple custom query failed"), (long)(queriesPerformed+1), [mySQLConnection lastErrorMessage]];
}
// Increment the processed queries count
queriesPerformed++;
}
// Clean up
if (connectionEncodingToRestore) {
[mySQLConnection queryString:[NSString stringWithFormat:@"SET NAMES '%@'", connectionEncodingToRestore]];
}
[sqlParser release];
[sqlDataBuffer release];
[importPool drain];
[tableDocumentInstance setQueryMode:SPInterfaceQueryMode];
if([filename hasPrefix:SPImportClipboardTempFileNamePrefix])
[[NSFileManager defaultManager] removeItemAtPath:filename error:nil];
// Close progress sheet
[self closeAndStopProgressSheet];
// Display any errors
if ([errors length]) {
[self showErrorSheetWithMessage:errors];
}
// Update available databases
[[tableDocumentInstance onMainThread] setDatabases:self];
// Update current selected database
[tableDocumentInstance refreshCurrentDatabase];
// Update current database tables
[tablesListInstance updateTables:self];
// Re-query the structure of all databases in the background
[[tableDocumentInstance databaseStructureRetrieval] queryDbStructureInBackgroundWithUserInfo:@{@"forceUpdate" : @YES}];
// Import finished Growl notification
[[SPGrowlController sharedGrowlController] notifyWithTitle:@"Import Finished"
description:[NSString stringWithFormat:NSLocalizedString(@"Finished importing %@",@"description for finished importing growl notification"), [filename lastPathComponent]]
document:tableDocumentInstance
notificationName:@"Import Finished"];
}
#pragma mark -
#pragma mark CSV import
/**
* Streaming data processing method to import a supplied CSV file.
*
* The file is read in chunk by chunk; each chunk is then checked
* for line endings, which are used to split the data into parts
* which can be parsed to NSStrings in the appropriate encoding.
*
* The NSStrings are then fed to a CSV parser, which splits them
* into arrays of rows/cells. Once 100 have been read in, a field
* mapping sheet is displayed to allow columns to be mapped to
* fields in a table; the queries are then constructed for each of
* the rows, and the rest of the file is processed.
*/
- (void)importCSVFile:(NSString *)filename
{
NSAutoreleasePool *importPool;
SPFileHandle *csvFileHandle;
NSMutableData *csvDataBuffer;
const unsigned char *csvDataBufferBytes;
NSData *fileChunk;
NSString *csvString;
SPCSVParser *csvParser;
NSMutableString *query;
NSMutableString *errors = [NSMutableString string];
NSMutableString *insertBaseString = [NSMutableString string];
NSMutableString *insertRemainingBaseString = [NSMutableString string];
NSMutableArray *parsedRows = [[NSMutableArray alloc] init];
NSMutableArray *parsePositions = [[NSMutableArray alloc] init];
NSArray *csvRowArray;
NSInteger fileChunkMaxLength = 256 * 1024;
NSUInteger csvRowsPerQuery = 50;
NSUInteger csvRowsThisQuery;
NSUInteger fileTotalLength = 0;
BOOL fileIsCompressed;
NSInteger rowsImported = 0;
NSInteger dataBufferLength = 0;
NSInteger dataBufferPosition = 0;
NSInteger dataBufferLastQueryEndPosition = 0;
NSUInteger i;
BOOL allDataRead = NO;
BOOL insertBaseStringHasEntries;
__block NSStringEncoding csvEncoding;
fieldMappingArray = nil;
fieldMappingGlobalValueArray = nil;
[geometryFields removeAllObjects];
[geometryFieldsMapIndex removeAllIndexes];
[bitFields removeAllObjects];
[bitFieldsMapIndex removeAllIndexes];
[nullableNumericFields removeAllObjects];
[nullableNumericFieldsMapIndex removeAllIndexes];
// Start the notification timer to allow notifications to be shown even if frontmost for long queries
[[SPGrowlController sharedGrowlController] setVisibilityForNotificationName:@"Import Finished"];
// Open a filehandle for the CSV file
csvFileHandle = [SPFileHandle fileHandleForReadingAtPath:filename];
if (!csvFileHandle) {
SPOnewayAlertSheet(
NSLocalizedString(@"Import Error", @"Import Error title"),
[tableDocumentInstance parentWindow],
NSLocalizedString(@"The CSV file you selected could not be found or read.", @"CSV file open error")
);
if([filename hasPrefix:SPImportClipboardTempFileNamePrefix])
[[NSFileManager defaultManager] removeItemAtPath:filename error:nil];
return;
}
// Grab the file length and status
fileTotalLength = (NSUInteger)[[[[NSFileManager defaultManager] attributesOfItemAtPath:filename error:NULL] objectForKey:NSFileSize] longLongValue];
if (!fileTotalLength) fileTotalLength = 1;
fileIsCompressed = ([csvFileHandle compressionFormat] != SPNoCompression);
// Reset progress interface
SPMainQSync(^{
[errorsView setString:@""];
[singleProgressTitle setStringValue:NSLocalizedString(@"Importing CSV", @"text showing that the application is importing CSV")];
[singleProgressText setStringValue:NSLocalizedString(@"Reading...", @"text showing that app is reading dump")];
[singleProgressBar setIndeterminate:NO];
[singleProgressBar setUsesThreadedAnimation:YES];
[singleProgressBar startAnimation:self];
// Open the progress sheet
[NSApp beginSheet:singleProgressSheet modalForWindow:[tableDocumentInstance parentWindow] modalDelegate:self didEndSelector:nil contextInfo:nil];
[singleProgressSheet makeKeyWindow];
});
[tableDocumentInstance setQueryMode:SPImportExportQueryMode];
SPMainQSync(^{
// Determine the file encoding. The first item in the encoding menu is "Autodetect";
if (![importEncodingPopup indexOfSelectedItem]) {
csvEncoding = 0;
}
// Otherwise, get the encoding to use from the menu
else {
csvEncoding = [importEncodingPopup selectedTag];
}
});
// if "Autodetect" is selected, attempt to detect the encoding of the file.
if (!csvEncoding) {
csvEncoding = [[NSFileManager defaultManager] detectEncodingforFileAtPath:filename];
}
// Read in the file in a loop. The loop actually needs to perform three tasks: read in
// CSV data and parse them into row arrays; present the field mapping interface once it
// has some data to show within the interface; and use the field mapping data to construct
// and send queries to the server. The loop is mainly to perform the first of these; the
// other two must therefore be performed where possible.
csvParser = [[SPCSVParser alloc] init];
SPMainQSync(^{
// Store settings in prefs
[prefs setObject:[importFieldsEnclosedField stringValue] forKey:SPCSVImportFieldEnclosedBy];
[prefs setObject:[importFieldsEscapedField stringValue] forKey:SPCSVImportFieldEscapeCharacter];
[prefs setObject:[importLinesTerminatedField stringValue] forKey:SPCSVImportLineTerminator];
[prefs setObject:[importFieldsTerminatedField stringValue] forKey:SPCSVImportFieldTerminator];
[prefs setBool:[importFieldNamesSwitch state] forKey:SPCSVImportFirstLineIsHeader];
// Take CSV import setting from accessory view
[csvParser setFieldTerminatorString:[importFieldsTerminatedField stringValue] convertDisplayStrings:YES];
[csvParser setLineTerminatorString:[importLinesTerminatedField stringValue] convertDisplayStrings:YES];
[csvParser setFieldQuoteString:[importFieldsEnclosedField stringValue] convertDisplayStrings:YES];
if ([[importFieldsEscapedField stringValue] isEqualToString:@"\\ or \""]) {
[csvParser setEscapeString:@"\\" convertDisplayStrings:NO];
} else {
[csvParser setEscapeString:[importFieldsEscapedField stringValue] convertDisplayStrings:YES];
[csvParser setEscapeStringsAreMatchedStrictly:YES];
}
[csvParser setNullReplacementString:[prefs objectForKey:SPNullValue]];
});
csvDataBuffer = [[NSMutableData alloc] init];
importPool = [[NSAutoreleasePool alloc] init];
while (1) {
if (progressCancelled) break;
@try {
fileChunk = [csvFileHandle readDataOfLength:fileChunkMaxLength];
}
// Report file read errors, and bail
@catch (NSException *exception) {
[self closeAndStopProgressSheet];
SPOnewayAlertSheet(
SP_FILE_READ_ERROR_STRING,
[tableDocumentInstance parentWindow],
[NSString stringWithFormat:NSLocalizedString(@"An error occurred when reading the file.\n\nOnly %ld rows were imported.\n\n(%@)", @"CSV read error, including detail string from system"), (long)rowsImported, [exception reason]]
);
[csvParser release];
[csvDataBuffer release];
[parsedRows release];
[parsePositions release];
[self _resetFieldMappingGlobals];
[importPool drain];
[tableDocumentInstance setQueryMode:SPInterfaceQueryMode];
if([filename hasPrefix:SPImportClipboardTempFileNamePrefix])
[[NSFileManager defaultManager] removeItemAtPath:filename error:nil];
return;
}
// If no data returned, end of file - set a marker to ensure full processing
if (!fileChunk || ![fileChunk length]) {
allDataRead = YES;
// Otherwise add the data to the read/parse buffer
} else {
[csvDataBuffer appendData:fileChunk];
}
// Step through the data buffer, identifying line endings to parse the data with
csvDataBufferBytes = [csvDataBuffer bytes];
dataBufferLength = [csvDataBuffer length];
for ( ; dataBufferPosition < dataBufferLength || allDataRead; dataBufferPosition++) {
if (csvDataBufferBytes[dataBufferPosition] == 0x0A || csvDataBufferBytes[dataBufferPosition] == 0x0D || allDataRead) {
#warning This EOL detection logic will break for multibyte encodings (like UTF16)!
// Keep reading through any other line endings
while (dataBufferPosition + 1 < dataBufferLength
&& (csvDataBufferBytes[dataBufferPosition+1] == 0x0A
|| csvDataBufferBytes[dataBufferPosition+1] == 0x0D))
{
dataBufferPosition++;
}
// Try to generate a NSString with the resulting data
csvString = [[NSString alloc] initWithData:[csvDataBuffer subdataWithRange:NSMakeRange(dataBufferLastQueryEndPosition, dataBufferPosition - dataBufferLastQueryEndPosition)] encoding:csvEncoding];
if (!csvString) {
[self closeAndStopProgressSheet];
SPMainQSync(^{
NSString *displayEncoding;
if (![importEncodingPopup indexOfSelectedItem]) {
displayEncoding = [NSString stringWithFormat:@"%@ - %@", [importEncodingPopup titleOfSelectedItem], [NSString localizedNameOfStringEncoding:csvEncoding]];
} else {
displayEncoding = [NSString localizedNameOfStringEncoding:csvEncoding];
}
SPOnewayAlertSheet(
SP_FILE_READ_ERROR_STRING,
[tableDocumentInstance parentWindow],
[NSString stringWithFormat:NSLocalizedString(@"An error occurred when reading the file, as it could not be read using the encoding you selected (%@).\n\nOnly %ld rows were imported.", @"CSV encoding read error"), displayEncoding, (long)rowsImported]
);
});
[csvParser release];
[csvDataBuffer release];
[parsedRows release];
[parsePositions release];
[self _resetFieldMappingGlobals];
[importPool drain];
[tableDocumentInstance setQueryMode:SPInterfaceQueryMode];
if([filename hasPrefix:SPImportClipboardTempFileNamePrefix])
[[NSFileManager defaultManager] removeItemAtPath:filename error:nil];
return;
}
// Add the NSString segment to the CSV parser and release it
[csvParser appendString:csvString];
[csvString release];
if (allDataRead) break;
// Increment the buffer end position marker
dataBufferLastQueryEndPosition = dataBufferPosition;
}
}
// Trim the data buffer if part of it was used
if (dataBufferLastQueryEndPosition) {
[csvDataBuffer setData:[csvDataBuffer subdataWithRange:NSMakeRange(dataBufferLastQueryEndPosition, dataBufferLength - dataBufferLastQueryEndPosition)]];
dataBufferPosition -= dataBufferLastQueryEndPosition;
dataBufferLastQueryEndPosition = 0;
}
// Extract and process any full CSV rows found so far. Also trigger processing if all
// rows have been read, in order to ensure short files are still processed.
while ((csvRowArray = [csvParser getRowAsArrayAndTrimString:YES stringIsComplete:allDataRead]) || (allDataRead && [parsedRows count])) {
// If valid, add the row array and length to local storage
if (csvRowArray) {
[parsedRows addObject:csvRowArray];
[parsePositions addObject:@([csvParser totalLengthParsed])];
}
// If we have no field mapping array, and either the first hundred rows or all
// the rows, request the field mapping from the user.
if (!fieldMappingArray
&& ([parsedRows count] >= 100 || (!csvRowArray && allDataRead)))
{
[self closeAndStopProgressSheet];
if (![self buildFieldMappingArrayWithData:parsedRows isPreview:!allDataRead ofSoureFile:filename]) {
[csvParser release];
[csvDataBuffer release];
[parsedRows release];
[parsePositions release];
[self _resetFieldMappingGlobals];
[importPool drain];
[tableDocumentInstance setQueryMode:SPInterfaceQueryMode];
if([filename hasPrefix:SPImportClipboardTempFileNamePrefix])
[[NSFileManager defaultManager] removeItemAtPath:filename error:nil];
return;
}
// Reset progress interface and open the progress sheet
SPMainQSync(^{
[singleProgressBar setMaxValue:fileTotalLength];
[singleProgressBar setIndeterminate:NO];
[singleProgressBar startAnimation:self];
[NSApp beginSheet:singleProgressSheet modalForWindow:[tableDocumentInstance parentWindow] modalDelegate:nil didEndSelector:NULL contextInfo:NULL];
[singleProgressSheet makeKeyWindow];
});
// Set up index sets for use during row enumeration
for (i = 0; i < [fieldMappingArray count]; i++) {
if ([NSArrayObjectAtIndex(fieldMapperOperator, i) integerValue] == 0) {
NSString *fieldName = NSArrayObjectAtIndex(fieldMappingTableColumnNames, i);
if ([nullableNumericFields containsObject:fieldName]) {
[nullableNumericFieldsMapIndex addIndex:i];
}
}
}
// Set up the field names import string for INSERT or REPLACE INTO
[insertBaseString appendString:csvImportHeaderString];
if(!importMethodIsUpdate) {
NSString *fieldName;
[insertBaseString appendFormat:@"%@ (", [selectedTableTarget backtickQuotedString]];
insertBaseStringHasEntries = NO;
for (i = 0; i < [fieldMappingArray count]; i++) {
if ([NSArrayObjectAtIndex(fieldMapperOperator, i) integerValue] == 0) {
if (insertBaseStringHasEntries)