aboutsummaryrefslogtreecommitdiffstats
path: root/Source/SPDataImport.m
diff options
context:
space:
mode:
authorstuconnolly <stuart02@gmail.com>2010-07-06 22:44:42 +0000
committerstuconnolly <stuart02@gmail.com>2010-07-06 22:44:42 +0000
commit6119b140f51a57fcc9abcf28b14029bb97d13b48 (patch)
tree932cf5b913dd614fa70693a0e9441825993d7dd0 /Source/SPDataImport.m
parent98321e0139af73928307da87ed31245b858e86d0 (diff)
downloadsequelpro-6119b140f51a57fcc9abcf28b14029bb97d13b48.tar.gz
sequelpro-6119b140f51a57fcc9abcf28b14029bb97d13b48.tar.bz2
sequelpro-6119b140f51a57fcc9abcf28b14029bb97d13b48.zip
Rename TableDump to SPDataImport and fix export selected tables functionality.
Diffstat (limited to 'Source/SPDataImport.m')
-rw-r--r--Source/SPDataImport.m1438
1 files changed, 1438 insertions, 0 deletions
diff --git a/Source/SPDataImport.m b/Source/SPDataImport.m
new file mode 100644
index 00000000..7b55c812
--- /dev/null
+++ b/Source/SPDataImport.m
@@ -0,0 +1,1438 @@
+//
+// $Id$
+//
+// SPDataImport.m
+// sequel-pro
+//
+// Created by lorenz textor (lorenz@textor.ch) on Wed May 01 2002.
+// Copyright (c) 2002-2003 Lorenz Textor. All rights reserved.
+//
+// This program is free software; you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation; either version 2 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with this program; if not, write to the Free Software
+// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+//
+// More info at <http://code.google.com/p/sequel-pro/>
+
+#import "SPDataImport.h"
+#import "SPDatabaseDocument.h"
+#import "SPTablesList.h"
+#import "SPTableStructure.h"
+#import "SPTableContent.h"
+#import "SPCustomQuery.h"
+#import "SPGrowlController.h"
+#import "SPSQLParser.h"
+#import "SPCSVParser.h"
+#import "SPTableData.h"
+#import "SPStringAdditions.h"
+#import "SPArrayAdditions.h"
+#import "RegexKitLite.h"
+#import "SPConstants.h"
+#import "SPAlertSheets.h"
+#import "SPFieldMapperController.h"
+#import "SPMainThreadTrampoline.h"
+#import "SPNotLoaded.h"
+#import "SPFileHandle.h"
+
+@implementation SPDataImport
+
+#pragma mark -
+#pragma mark Initialisation
+
+/**
+ * Init.
+ */
+- (id)init
+{
+ if ((self = [super init])) {
+
+ nibObjectsToRelease = [[NSMutableArray alloc] init];
+ fieldMappingArray = nil;
+ fieldMappingGlobalValueArray = nil;
+ fieldMappingTableColumnNames = nil;
+ fieldMappingTableDefaultValues = nil;
+ fieldMappingImportArray = nil;
+ csvImportTailString = nil;
+ csvImportHeaderString = nil;
+ csvImportMethodHasTail = NO;
+ fieldMappingImportArrayIsPreview = NO;
+ fieldMappingArrayHasGlobalVariables = NO;
+ importMethodIsUpdate = NO;
+ insertRemainingRowsAfterUpdate = NO;
+ numberOfImportDataColumns = 0;
+
+ prefs = nil;
+ lastFilename = nil;
+ _mainNibLoaded = NO;
+ }
+
+ return self;
+}
+
+/**
+ * UI setup.
+ */
+- (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];
+}
+
+#pragma mark -
+#pragma mark IBAction methods
+
+/**
+ * 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
+{
+ if (![NSThread isMainThread]) {
+ [self performSelectorOnMainThread:@selector(closeAndStopProgressSheet) withObject:nil waitUntilDone:YES];
+ return;
+ }
+
+ [NSApp endSheet:singleProgressSheet];
+ [singleProgressSheet orderOut:nil];
+ [[singleProgressBar onMainThread] stopAnimation:self];
+ [[singleProgressBar onMainThread] setMaxValue:100];
+}
+
+/**
+ * When the compression setting on export is altered, update the filename
+ * and if appropriate the required extension.
+ */
+- (IBAction)updateExportCompressionSetting:(id)sender
+{
+ if (exportMode == SPExportingSQL) {
+ if ([sender state] == NSOnState) {
+ [currentExportPanel setAllowedFileTypes:[NSArray arrayWithObjects:[NSString stringWithFormat:@"%@.gz", SPFileExtensionSQL], @"gz", nil]];
+
+ // if file name text view is the first responder re-select the path name only without '.sql.gz'
+ if([[currentExportPanel firstResponder] isKindOfClass:[NSTextView class]]) {
+ NSTextView *filenameTextView = (NSTextView *)[currentExportPanel firstResponder];
+ if([filenameTextView selectedRange].length > 4 && [[filenameTextView string] hasSuffix:[NSString stringWithFormat:@".%@.gz", SPFileExtensionSQL]]) {
+ NSRange selRange = [filenameTextView selectedRange];
+ selRange.length -= 4;
+ [filenameTextView setSelectedRange:selRange];
+ }
+ }
+
+ } else {
+ [currentExportPanel setAllowedFileTypes:[NSArray arrayWithObject:SPFileExtensionSQL]];
+ }
+
+ [prefs setBool:([sender state] == NSOnState) forKey:SPSQLExportUseCompression];
+ }
+}
+
+#pragma mark -
+#pragma mark Import methods
+
+/**
+ * Invoked when user clicks on an ImportFromClipboard menuitem.
+ */
+- (void)importFromClipboard
+{
+
+ // clipboard textview with no wrapping
+ const CGFloat LargeNumberForText = 1.0e7;
+ [[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]];
+ [importFromClipboardAccessoryView addSubview:importCSVView];
+
+ [NSApp beginSheet:importFromClipboardSheet
+ modalForWindow:[tableDocumentInstance parentWindow]
+ modalDelegate:self
+ didEndSelector:@selector(openPanelDidEnd:returnCode:contextInfo:)
+ contextInfo:@"importFromClipboard"];
+}
+
+/**
+ * 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:importCSVView];
+ [openPanel setDelegate:self];
+ if ([prefs valueForKey:@"importFormatPopupValue"]) {
+ [importFormatPopup selectItemWithTitle:[prefs valueForKey:@"importFormatPopupValue"]];
+ [self changeFormat:self];
+ }
+
+ // Show openPanel
+ [openPanel beginSheetForDirectory:[prefs objectForKey:@"openPath"]
+ file:[lastFilename lastPathComponent]
+ modalForWindow:[tableDocumentInstance parentWindow]
+ modalDelegate:self
+ didEndSelector:@selector(openPanelDidEnd:returnCode:contextInfo:)
+ contextInfo:nil];
+}
+
+/**
+ * Shows/hides the CSV options accessory view based on the selected format.
+ */
+- (IBAction)changeFormat:(id)sender
+{
+ [importCSVBox setHidden:![[[importFormatPopup selectedItem] title] isEqualToString:@"CSV"]];
+}
+
+/**
+ * Starts the import process on a background thread.
+ */
+- (void)importBackgroundProcess:(NSString*)filename
+{
+ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
+ NSString *fileType = [[importFormatPopup selectedItem] title];
+
+ // Use the appropriate processing function for the file type
+ if ([fileType isEqualToString:@"SQL"])
+ [self importSQLFile:filename];
+ else if ([fileType isEqualToString:@"CSV"])
+ [self importCSVFile:filename];
+
+ [pool release];
+}
+
+/**
+ *
+ */
+- (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 importSQLAsUTF8 = YES;
+ BOOL allDataRead = NO;
+ NSStringEncoding sqlEncoding = NSUTF8StringEncoding;
+ 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) {
+ SPBeginAlertSheet(NSLocalizedString(@"Import Error title", @"Import Error"),
+ NSLocalizedString(@"OK button label", @"OK button"),
+ nil, nil, [tableDocumentInstance parentWindow], self, nil, nil,
+ NSLocalizedString(@"SQL file open error", @"The SQL file you selected could not be found or read."));
+ if([filename hasPrefix:SPImportClipboardTempFileNamePrefix])
+ [[NSFileManager defaultManager] removeItemAtPath:filename error:nil];
+ return;
+ }
+ fileIsCompressed = [sqlFileHandle isCompressed];
+
+ // Grab the file length
+ fileTotalLength = [[[[NSFileManager defaultManager] attributesOfItemAtPath:filename error:NULL] objectForKey:NSFileSize] longLongValue];
+ if (!fileTotalLength) fileTotalLength = 1;
+
+ // Reset progress interface
+ [errorsView setString:@""];
+ [[singleProgressTitle onMainThread] setStringValue:NSLocalizedString(@"Importing SQL", @"text showing that the application is importing SQL")];
+ [[singleProgressText onMainThread] setStringValue:NSLocalizedString(@"Reading...", @"text showing that app is reading dump")];
+ [[singleProgressBar onMainThread] setIndeterminate:NO];
+ [[singleProgressBar onMainThread] setMaxValue:fileTotalLength];
+ [[singleProgressBar onMainThread] setUsesThreadedAnimation:YES];
+ [[singleProgressBar onMainThread] startAnimation:self];
+
+ // Open the progress sheet
+ [[NSApp onMainThread] beginSheet:singleProgressSheet modalForWindow:[tableDocumentInstance parentWindow] modalDelegate:self didEndSelector:nil contextInfo:nil];
+ [[singleProgressSheet onMainThread] makeKeyWindow];
+
+ [tableDocumentInstance setQueryMode:SPImportExportQueryMode];
+
+ // 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) {
+ [self closeAndStopProgressSheet];
+ SPBeginAlertSheet(NSLocalizedString(@"SQL read error title", @"File read error"),
+ NSLocalizedString(@"OK", @"OK button"),
+ nil, nil, [tableDocumentInstance parentWindow], self, nil, nil,
+ [NSString stringWithFormat:NSLocalizedString(@"SQL read error", @"An error occurred when reading the file.\n\nOnly %ld queries were executed.\n\n(%@)"), (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
+ if (importSQLAsUTF8) {
+ sqlString = [[NSString alloc] initWithData:[sqlDataBuffer subdataWithRange:NSMakeRange(dataBufferLastQueryEndPosition, dataBufferPosition - dataBufferLastQueryEndPosition)]
+ encoding:NSUTF8StringEncoding];
+ if (!sqlString) {
+ importSQLAsUTF8 = NO;
+ sqlEncoding = [MCPConnection encodingForMySQLEncoding:[[tableDocumentInstance connectionEncoding] UTF8String]];
+ }
+ }
+ if (!importSQLAsUTF8) {
+ sqlString = [[NSString alloc] initWithData:[sqlDataBuffer subdataWithRange:NSMakeRange(dataBufferLastQueryEndPosition, dataBufferPosition - dataBufferLastQueryEndPosition)]
+ encoding:[MCPConnection encodingForMySQLEncoding:[[tableDocumentInstance connectionEncoding] UTF8String]]];
+ if (!sqlString) {
+ [self closeAndStopProgressSheet];
+ SPBeginAlertSheet(NSLocalizedString(@"SQL read error title", @"File read error"),
+ NSLocalizedString(@"OK", @"OK button"),
+ nil, nil, [tableDocumentInstance parentWindow], self, nil, nil,
+ [NSString stringWithFormat:NSLocalizedString(@"SQL encoding read error", @"An error occurred when reading the file, as it could not be read in either UTF-8 or %@.\n\nOnly %ld queries were executed."), [[tableDocumentInstance connectionEncoding] UTF8String], (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, bail.
+ if (![mySQLConnection isConnected]) {
+ if([filename hasPrefix:SPImportClipboardTempFileNamePrefix])
+ [[NSFileManager defaultManager] removeItemAtPath:filename error:nil];
+ 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;
+
+ // Skip blank or whitespace-only queries to avoid errors
+ query = [query stringByTrimmingCharactersInSet:whitespaceAndNewlineCharset];
+ if (![query length]) continue;
+
+ // Run the query
+ [mySQLConnection queryString:query usingEncoding:sqlEncoding streamingResult:NO];
+
+ // Check for any errors
+ if ([mySQLConnection queryErrored] && ![[mySQLConnection getLastErrorMessage] isEqualToString:@"Query was empty"]) {
+ [errors appendString:[NSString stringWithFormat:NSLocalizedString(@"[ERROR in query %ld] %@\n", @"error text when multiple custom query failed"), (long)(queriesPerformed+1), [mySQLConnection getLastErrorMessage]]];
+ }
+
+ // 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 streamingResult:NO];
+
+ // Check for any errors
+ if ([mySQLConnection queryErrored] && ![[mySQLConnection getLastErrorMessage] isEqualToString:@"Query was empty"]) {
+ [errors appendString:[NSString stringWithFormat:NSLocalizedString(@"[ERROR in query %ld] %@\n", @"error text when multiple custom query failed"), (long)(queriesPerformed+1), [mySQLConnection getLastErrorMessage]]];
+ }
+
+ // Increment the processed queries count
+ queriesPerformed++;
+ }
+
+ // Clean up
+ [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 setDatabases:self];
+
+ // Update current selected database
+ [[tableDocumentInstance onMainThread] refreshCurrentDatabase];
+
+ // Update current database tables
+ [tablesListInstance updateTables:self];
+
+ // Query the structure of all databases in the background
+ [NSThread detachNewThreadSelector:@selector(queryDbStructureWithUserInfo:) toTarget:mySQLConnection withObject:[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], @"forceUpdate", nil]];
+
+ // 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"];
+}
+
+/**
+ *
+ */
+- (void)importCSVFile:(NSString *)filename
+{
+ NSAutoreleasePool *importPool;
+ NSFileHandle *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;
+ NSInteger csvRowsPerQuery = 50;
+ NSUInteger csvRowsThisQuery;
+ NSUInteger fileTotalLength = 0;
+ NSInteger rowsImported = 0;
+ NSInteger dataBufferLength = 0;
+ NSInteger dataBufferPosition = 0;
+ NSInteger dataBufferLastQueryEndPosition = 0;
+ NSInteger i;
+ BOOL allDataRead = NO;
+ BOOL insertBaseStringHasEntries;
+
+ NSStringEncoding csvEncoding = [MCPConnection encodingForMySQLEncoding:[[tableDocumentInstance connectionEncoding] UTF8String]];
+
+ fieldMappingArray = nil;
+ fieldMappingGlobalValueArray = nil;
+
+ // 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 = [NSFileHandle fileHandleForReadingAtPath:filename];
+ if (!csvFileHandle) {
+ SPBeginAlertSheet(NSLocalizedString(@"Import Error title", @"Import Error"),
+ NSLocalizedString(@"OK button label", @"OK button"),
+ nil, nil, [tableDocumentInstance parentWindow], self, nil, nil,
+ NSLocalizedString(@"CSV file open error", @"The CSV file you selected could not be found or read."));
+ if([filename hasPrefix:SPImportClipboardTempFileNamePrefix])
+ [[NSFileManager defaultManager] removeItemAtPath:filename error:nil];
+ return;
+ }
+
+ // Grab the file length
+ fileTotalLength = [[[[NSFileManager defaultManager] attributesOfItemAtPath:filename error:NULL] objectForKey:NSFileSize] longLongValue];
+ if (!fileTotalLength) fileTotalLength = 1;
+
+ // Reset progress interface
+ [errorsView setString:@""];
+ [[singleProgressTitle onMainThread] setStringValue:NSLocalizedString(@"Importing CSV", @"text showing that the application is importing CSV")];
+ [[singleProgressText onMainThread] setStringValue:NSLocalizedString(@"Reading...", @"text showing that app is reading dump")];
+ [[singleProgressBar onMainThread] setIndeterminate:YES];
+ [[singleProgressBar onMainThread] setUsesThreadedAnimation:YES];
+ [[singleProgressBar onMainThread] startAnimation:self];
+
+ // Open the progress sheet
+ [[NSApp onMainThread] beginSheet:singleProgressSheet modalForWindow:[tableDocumentInstance parentWindow] modalDelegate:self didEndSelector:nil contextInfo:nil];
+ [[singleProgressSheet onMainThread] makeKeyWindow];
+
+ [tableDocumentInstance setQueryMode:SPImportExportQueryMode];
+
+ // 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];
+
+ // 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];
+ [csvParser setEscapeString:[importFieldsEscapedField stringValue] convertDisplayStrings: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];
+ SPBeginAlertSheet(NSLocalizedString(@"CSV read error title", @"File read error"),
+ NSLocalizedString(@"OK", @"OK button"),
+ nil, nil, [tableDocumentInstance parentWindow], self, nil, nil,
+ [NSString stringWithFormat:NSLocalizedString(@"CSV read error", @"An error occurred when reading the file.\n\nOnly %ld rows were imported.\n\n(%@)"), (long)rowsImported, [exception reason]]);
+ [csvParser release];
+ [csvDataBuffer release];
+ [parsedRows release];
+ [parsePositions release];
+ if(csvImportTailString) [csvImportTailString release], csvImportTailString = nil;
+ if(csvImportHeaderString) [csvImportHeaderString release], csvImportHeaderString = nil;
+ if(fieldMappingArray) [fieldMappingArray release], fieldMappingArray = nil;
+ if(fieldMappingGlobalValueArray) [fieldMappingGlobalValueArray release], fieldMappingGlobalValueArray = nil;
+ if(fieldMappingTableColumnNames) [fieldMappingTableColumnNames release], fieldMappingTableColumnNames = nil;
+ if(fieldMappingTableDefaultValues) [fieldMappingTableDefaultValues release], fieldMappingTableDefaultValues = nil;
+ if(fieldMapperOperator) [fieldMapperOperator release], fieldMapperOperator = nil;
+ [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) {
+
+ // 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];
+ SPBeginAlertSheet(NSLocalizedString(@"CSV read error title", @"File read error"),
+ NSLocalizedString(@"OK", @"OK button"),
+ nil, nil, [tableDocumentInstance parentWindow], self, nil, nil,
+ [NSString stringWithFormat:NSLocalizedString(@"CSV encoding read error", @"An error occurred when reading the file, as it could not be read using %@.\n\nOnly %ld rows were imported."), [[tableDocumentInstance connectionEncoding] UTF8String], (long)rowsImported]);
+ [csvParser release];
+ [csvDataBuffer release];
+ [parsedRows release];
+ [parsePositions release];
+ if(csvImportTailString) [csvImportTailString release], csvImportTailString = nil;
+ if(csvImportHeaderString) [csvImportHeaderString release], csvImportHeaderString = nil;
+ if(fieldMappingArray) [fieldMappingArray release], fieldMappingArray = nil;
+ if(fieldMappingGlobalValueArray) [fieldMappingGlobalValueArray release], fieldMappingGlobalValueArray = nil;
+ if(fieldMappingTableColumnNames) [fieldMappingTableColumnNames release], fieldMappingTableColumnNames = nil;
+ if(fieldMappingTableDefaultValues) [fieldMappingTableDefaultValues release], fieldMappingTableDefaultValues = nil;
+ if(fieldMapperOperator) [fieldMapperOperator release], fieldMapperOperator = nil;
+ [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:[NSNumber numberWithUnsignedInteger:[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];
+ if(csvImportTailString) [csvImportTailString release], csvImportTailString = nil;
+ if(csvImportHeaderString) [csvImportHeaderString release], csvImportHeaderString = nil;
+ if(fieldMappingArray) [fieldMappingArray release], fieldMappingArray = nil;
+ if(fieldMappingGlobalValueArray) [fieldMappingGlobalValueArray release], fieldMappingGlobalValueArray = nil;
+ if(fieldMappingTableColumnNames) [fieldMappingTableColumnNames release], fieldMappingTableColumnNames = nil;
+ if(fieldMappingTableDefaultValues) [fieldMappingTableDefaultValues release], fieldMappingTableDefaultValues = nil;
+ if(fieldMapperOperator) [fieldMapperOperator release], fieldMapperOperator = nil;
+ [importPool drain];
+ [tableDocumentInstance setQueryMode:SPInterfaceQueryMode];
+ if([filename hasPrefix:SPImportClipboardTempFileNamePrefix])
+ [[NSFileManager defaultManager] removeItemAtPath:filename error:nil];
+ return;
+ }
+
+ // Reset progress interface and open the progress sheet
+ [[singleProgressBar onMainThread] setIndeterminate:NO];
+ [[singleProgressBar onMainThread] setMaxValue:fileTotalLength];
+ [[singleProgressBar onMainThread] startAnimation:self];
+ [[NSApp onMainThread] beginSheet:singleProgressSheet modalForWindow:[tableDocumentInstance parentWindow] modalDelegate:self didEndSelector:nil contextInfo:nil];
+ [[singleProgressSheet onMainThread] makeKeyWindow];
+
+ // Set up the field names import string for INSERT or REPLACE INTO
+ [insertBaseString appendString:csvImportHeaderString];
+ if(!importMethodIsUpdate) {
+ [insertBaseString appendString:[selectedTableTarget backtickQuotedString]];
+ [insertBaseString appendString:@" ("];
+ insertBaseStringHasEntries = NO;
+ for (i = 0; i < [fieldMappingArray count]; i++) {
+ if ([NSArrayObjectAtIndex(fieldMapperOperator, i) integerValue] == 0) {
+ if (insertBaseStringHasEntries) [insertBaseString appendString:@","];
+ else insertBaseStringHasEntries = YES;
+ [insertBaseString appendString:[NSArrayObjectAtIndex(fieldMappingTableColumnNames, i) backtickQuotedString]];
+ }
+ }
+ [insertBaseString appendString:@") VALUES\n"];
+ }
+
+ // Remove the header row from the data set if appropriate
+ if ([importFieldNamesSwitch state] == NSOnState) {
+ [parsedRows removeObjectAtIndex:0];
+ [parsePositions removeObjectAtIndex:0];
+ }
+ }
+ if (!fieldMappingArray) continue;
+
+ // Before entering the following loop, check that we actually have a connection. If not, bail.
+ if (![mySQLConnection isConnected]) {
+ [self closeAndStopProgressSheet];
+ [csvParser release];
+ [csvDataBuffer release];
+ [parsedRows release];
+ [parsePositions release];
+ if(csvImportTailString) [csvImportTailString release], csvImportTailString = nil;
+ if(csvImportHeaderString) [csvImportHeaderString release], csvImportHeaderString = nil;
+ if(fieldMappingArray) [fieldMappingArray release], fieldMappingArray = nil;
+ if(fieldMappingGlobalValueArray) [fieldMappingGlobalValueArray release], fieldMappingGlobalValueArray = nil;
+ if(fieldMappingTableColumnNames) [fieldMappingTableColumnNames release], fieldMappingTableColumnNames = nil;
+ if(fieldMappingTableDefaultValues) [fieldMappingTableDefaultValues release], fieldMappingTableDefaultValues = nil;
+ if(fieldMapperOperator) [fieldMapperOperator release], fieldMapperOperator = nil;
+ [importPool drain];
+ [tableDocumentInstance setQueryMode:SPInterfaceQueryMode];
+ if([filename hasPrefix:SPImportClipboardTempFileNamePrefix])
+ [[NSFileManager defaultManager] removeItemAtPath:filename error:nil];
+ return;
+ }
+
+ // If we have more than the csvRowsPerQuery amount, or if we're at the end of the
+ // available data, construct and run a query.
+ while ([parsedRows count] >= csvRowsPerQuery
+ || (!csvRowArray && allDataRead && [parsedRows count]))
+ {
+ if (progressCancelled) break;
+ csvRowsThisQuery = 0;
+ if(!importMethodIsUpdate) {
+ query = [[NSMutableString alloc] initWithString:insertBaseString];
+ for (i = 0; i < csvRowsPerQuery && i < [parsedRows count]; i++) {
+ if (i > 0) [query appendString:@",\n"];
+ [query appendString:[[self mappedValueStringForRowArray:[parsedRows objectAtIndex:i]] description]];
+ csvRowsThisQuery++;
+ if ([query length] > 250000) break;
+ }
+
+ // Perform the query
+ if(csvImportMethodHasTail)
+ [mySQLConnection queryString:[NSString stringWithFormat:@"%@ %@", query, csvImportTailString]];
+ else
+ [mySQLConnection queryString:query];
+ [query release];
+ } else {
+ if(insertRemainingRowsAfterUpdate) {
+ [insertRemainingBaseString setString:@"INSERT INTO "];
+ [insertRemainingBaseString appendString:[selectedTableTarget backtickQuotedString]];
+ [insertRemainingBaseString appendString:@" ("];
+ insertBaseStringHasEntries = NO;
+ for (i = 0; i < [fieldMappingArray count]; i++) {
+ if ([NSArrayObjectAtIndex(fieldMapperOperator, i) integerValue] == 0) {
+ if (insertBaseStringHasEntries) [insertBaseString appendString:@","];
+ else insertBaseStringHasEntries = YES;
+ [insertRemainingBaseString appendString:[NSArrayObjectAtIndex(fieldMappingTableColumnNames, i) backtickQuotedString]];
+ }
+ }
+ [insertRemainingBaseString appendString:@") VALUES\n"];
+ }
+ for (i = 0; i < [parsedRows count]; i++) {
+ if (progressCancelled) break;
+
+ query = [[NSMutableString alloc] initWithString:insertBaseString];
+ [query appendString:[self mappedUpdateSetStatementStringForRowArray:[parsedRows objectAtIndex:i]]];
+
+ // Perform the query
+ if(csvImportMethodHasTail)
+ [mySQLConnection queryString:[NSString stringWithFormat:@"%@ %@", query, csvImportTailString]];
+ else
+ [mySQLConnection queryString:query];
+ [query release];
+
+ if ([mySQLConnection queryErrored]) {
+ [tableDocumentInstance showConsole:nil];
+ [errors appendString:[NSString stringWithFormat:
+ NSLocalizedString(@"[ERROR in row %ld] %@\n", @"error text when reading of csv file gave errors"),
+ (long)(rowsImported+1),[mySQLConnection getLastErrorMessage]]];
+ }
+
+ if ( insertRemainingRowsAfterUpdate && ![mySQLConnection affectedRows]) {
+ query = [[NSMutableString alloc] initWithString:insertRemainingBaseString];
+ [query appendString:[self mappedValueStringForRowArray:[parsedRows objectAtIndex:i]]];
+
+ // Perform the query
+ if(csvImportMethodHasTail)
+ [mySQLConnection queryString:[NSString stringWithFormat:@"%@ %@", query, csvImportTailString]];
+ else
+ [mySQLConnection queryString:query];
+ [query release];
+
+ if ([mySQLConnection queryErrored]) {
+ [errors appendString:[NSString stringWithFormat:
+ NSLocalizedString(@"[ERROR in row %ld] %@\n", @"error text when reading of csv file gave errors"),
+ (long)(rowsImported+1),[mySQLConnection getLastErrorMessage]]];
+ }
+ }
+
+ rowsImported++;
+ csvRowsThisQuery++;
+ [singleProgressBar setDoubleValue:[[parsePositions objectAtIndex:i] doubleValue]];
+ [singleProgressText setStringValue:[NSString stringWithFormat:NSLocalizedString(@"Imported %@ of %@", @"SQL import progress text"),
+ [NSString stringForByteSize:[[parsePositions objectAtIndex:i] longValue]], [NSString stringForByteSize:fileTotalLength]]];
+ }
+ }
+ // If an error occurred, run the queries individually to get exact line errors
+ if (!importMethodIsUpdate && [mySQLConnection queryErrored]) {
+ [tableDocumentInstance showConsole:nil];
+ for (i = 0; i < csvRowsThisQuery; i++) {
+ if (progressCancelled) break;
+ query = [[NSMutableString alloc] initWithString:insertBaseString];
+ [query appendString:[self mappedValueStringForRowArray:[parsedRows objectAtIndex:i]]];
+
+ // Perform the query
+ if(csvImportMethodHasTail)
+ [mySQLConnection queryString:[NSString stringWithFormat:@"%@ %@", query, csvImportTailString]];
+ else
+ [mySQLConnection queryString:query];
+ [query release];
+
+ if ([mySQLConnection queryErrored]) {
+ [errors appendString:[NSString stringWithFormat:
+ NSLocalizedString(@"[ERROR in row %ld] %@\n", @"error text when reading of csv file gave errors"),
+ (long)(rowsImported+1),[mySQLConnection getLastErrorMessage]]];
+ }
+ rowsImported++;
+ [singleProgressBar setDoubleValue:[[parsePositions objectAtIndex:i] doubleValue]];
+ [singleProgressText setStringValue:[NSString stringWithFormat:NSLocalizedString(@"Imported %@ of %@", @"SQL import progress text"),
+ [NSString stringForByteSize:[[parsePositions objectAtIndex:i] longValue]], [NSString stringForByteSize:fileTotalLength]]];
+ }
+ } else {
+ rowsImported += csvRowsThisQuery;
+ [singleProgressBar setDoubleValue:[[parsePositions objectAtIndex:csvRowsThisQuery-1] doubleValue]];
+ [singleProgressText setStringValue:[NSString stringWithFormat:NSLocalizedString(@"Imported %@ of %@", @"SQL import progress text"),
+ [NSString stringForByteSize:[[parsePositions objectAtIndex:csvRowsThisQuery-1] longValue]], [NSString stringForByteSize:fileTotalLength]]];
+ }
+
+ // Update the arrays
+ [parsedRows removeObjectsInRange:NSMakeRange(0, csvRowsThisQuery)];
+ [parsePositions removeObjectsInRange:NSMakeRange(0, csvRowsThisQuery)];
+ }
+ }
+
+ // 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];
+ }
+
+ // Clean up
+ [csvParser release];
+ [csvDataBuffer release];
+ [parsedRows release];
+ [parsePositions release];
+ if(csvImportTailString) [csvImportTailString release], csvImportTailString = nil;
+ if(csvImportHeaderString) [csvImportHeaderString release], csvImportHeaderString = nil;
+ if(fieldMappingArray) [fieldMappingArray release], fieldMappingArray = nil;
+ if(fieldMappingGlobalValueArray) [fieldMappingGlobalValueArray release], fieldMappingGlobalValueArray = nil;
+ if(fieldMappingTableColumnNames) [fieldMappingTableColumnNames release], fieldMappingTableColumnNames = nil;
+ if(fieldMappingTableDefaultValues) [fieldMappingTableDefaultValues release], fieldMappingTableDefaultValues = nil;
+ if(fieldMapperOperator) [fieldMapperOperator release], fieldMapperOperator = nil;
+ [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];
+ }
+
+ // 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"];
+
+ // If the table selected for import is also selected in the content view,
+ // update the content view - on the main thread to avoid crashes.
+ if ([tablesListInstance tableName] && [selectedTableTarget isEqualToString:[tablesListInstance tableName]]) {
+ if ([[tableDocumentInstance selectedToolbarItemIdentifier] isEqualToString:SPMainToolbarTableContent]) {
+ [tableContentInstance performSelectorOnMainThread:@selector(reloadTable:) withObject:nil waitUntilDone:YES];
+ } else {
+ [tablesListInstance setContentRequiresReload:YES];
+ }
+ }
+}
+
+/**
+ *
+ */
+- (void)openPanelDidEnd:(id)sheet returnCode:(NSInteger)returnCode contextInfo:(NSString *)contextInfo
+{
+
+ // if contextInfo == nil NSOpenPanel else importFromClipboardPanel
+
+ // save values to preferences
+ if(contextInfo == nil)
+ [prefs setObject:[(NSOpenPanel*)sheet directory] forKey:@"openPath"];
+ else
+ [importFromClipboardTextView setString:@""];
+
+ [prefs setObject:[[importFormatPopup selectedItem] title] forKey:@"importFormatPopupValue"];
+
+ // close NSOpenPanel sheet
+ if(contextInfo == nil)
+ [sheet orderOut:self];
+
+ // check if user canceled
+ if (returnCode != NSOKButton)
+ return;
+
+ // Reset progress cancelled from any previous runs
+ progressCancelled = NO;
+
+ NSString *importFileName;
+
+ // File path from NSOpenPanel
+ if(contextInfo == nil)
+ {
+ if(lastFilename) [lastFilename release]; lastFilename = nil;
+ lastFilename = [[NSString stringWithString:[(NSOpenPanel*)sheet filename]] retain];
+ importFileName = [NSString stringWithString:lastFilename];
+ if(lastFilename == nil || ![lastFilename length]) {
+ NSBeep();
+ return;
+ }
+ }
+
+ // Import from Clipboard
+ else
+ {
+ 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 = [MCPConnection encodingForMySQLEncoding:[[tableDocumentInstance connectionEncoding] UTF8String]];
+
+ 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
+ [NSThread detachNewThreadSelector:@selector(importBackgroundProcess:) toTarget:self withObject:importFileName];
+}
+
+/**
+ *
+ */
+- (void)startSQLImportProcessWithFile:(NSString *)filename
+{
+ [importFormatPopup selectItemWithTitle:@"SQL"];
+ [NSThread detachNewThreadSelector:@selector(importBackgroundProcess:) toTarget:self withObject:filename];
+}
+
+/**
+ * Sets up the field mapping array, and asks the user to provide a field mapping to an
+ * appropriate table; on success, constructs the field mapping array into the global variable,
+ * and returns true. On failure, displays error messages itself, and returns false.
+ * Takes an array of data to show when selecting the field mapping, and an indicator of whether
+ * that dataset is complete or a preview of the full data set.
+ */
+- (BOOL) buildFieldMappingArrayWithData:(NSArray *)importData isPreview:(BOOL)dataIsPreviewData ofSoureFile:(NSString*)filename
+{
+
+ // Ensure data was provided, or alert than an import error occurred and return false.
+ if (![importData count]) {
+ [self closeAndStopProgressSheet];
+ SPBeginAlertSheet(NSLocalizedString(@"Error", @"error"),
+ NSLocalizedString(@"OK", @"OK button"),
+ nil, nil,
+ [tableDocumentInstance parentWindow], self,
+ nil, nil,
+ NSLocalizedString(@"Could not parse file as CSV", @"Error when we can't parse/split file as CSV")
+ );
+ return FALSE;
+ }
+
+ // Sanity check the first row of the CSV to prevent hang loops caused by wrong line ending entry
+ if ([[importData objectAtIndex:0] count] > 512) {
+ [self closeAndStopProgressSheet];
+ SPBeginAlertSheet(NSLocalizedString(@"Error", @"error"),
+ NSLocalizedString(@"OK", @"OK button"),
+ nil, nil,
+ [tableDocumentInstance parentWindow], self,
+ nil, nil,
+ NSLocalizedString(@"The CSV was read as containing more than 512 columns, more than the maximum columns permitted for speed reasons by Sequel Pro.\n\nThis usually happens due to errors reading the CSV; please double-check the CSV to be imported and the line endings and escape characters at the bottom of the CSV selection dialog.", @"Error when CSV appears to have too many columns to import, probably due to line ending mismatch")
+ );
+ return FALSE;
+ }
+ fieldMappingImportArrayIsPreview = dataIsPreviewData;
+
+ // If there's no tables to select, error
+ if (![[tablesListInstance allTableNames] count]) {
+ [self closeAndStopProgressSheet];
+ SPBeginAlertSheet(NSLocalizedString(@"Error", @"error"),
+ NSLocalizedString(@"OK", @"OK button"),
+ nil, nil,
+ [tableDocumentInstance parentWindow], self,
+ nil, nil,
+ NSLocalizedString(@"Can't import CSV data into a database without any tables!", @"error text when trying to import csv data, but we have no tables in the db")
+ );
+ return FALSE;
+ }
+
+ // Set the import array
+ if (fieldMappingImportArray) [fieldMappingImportArray release];
+ fieldMappingImportArray = [[NSArray alloc] initWithArray:importData];
+ numberOfImportDataColumns = [[importData objectAtIndex:0] count];
+
+ fieldMapperSheetStatus = 1;
+ fieldMappingArrayHasGlobalVariables = NO;
+
+ // Init the field mapper controller
+ fieldMapperController = [[SPFieldMapperController alloc] initWithDelegate:self];
+ [fieldMapperController setConnection:mySQLConnection];
+ [fieldMapperController setSourcePath:filename];
+ [fieldMapperController setImportDataArray:fieldMappingImportArray hasHeader:[importFieldNamesSwitch state] isPreview:fieldMappingImportArrayIsPreview];
+
+ // Show field mapper sheet and set the focus to it
+ [[NSApp onMainThread] beginSheet:[fieldMapperController window]
+ modalForWindow:[tableDocumentInstance parentWindow]
+ modalDelegate:self
+ didEndSelector:@selector(fieldMapperDidEndSheet:returnCode:contextInfo:)
+ contextInfo:nil];
+
+ [[[fieldMapperController window] onMainThread] makeKeyWindow];
+
+ // Wait for field mapper sheet
+ while (fieldMapperSheetStatus == 1)
+ usleep(100000);
+
+ // Get mapping settings and preset some global variables
+ fieldMapperOperator = [[NSArray arrayWithArray:[fieldMapperController fieldMapperOperator]] retain];
+ fieldMappingArray = [[NSArray arrayWithArray:[fieldMapperController fieldMappingArray]] retain];
+ selectedTableTarget = [NSString stringWithString:[fieldMapperController selectedTableTarget]];
+ selectedImportMethod = [NSString stringWithString:[fieldMapperController selectedImportMethod]];
+ fieldMappingTableColumnNames = [[NSArray arrayWithArray:[fieldMapperController fieldMappingTableColumnNames]] retain];
+ fieldMappingGlobalValueArray = [[NSArray arrayWithArray:[fieldMapperController fieldMappingGlobalValueArray]] retain];
+ fieldMappingTableDefaultValues = [[NSArray arrayWithArray:[fieldMapperController fieldMappingTableDefaultValues]] retain];
+ csvImportHeaderString = [[NSString stringWithString:[fieldMapperController importHeaderString]] retain];
+ csvImportTailString = [[NSString stringWithString:[fieldMapperController onupdateString]] retain];
+ fieldMappingArrayHasGlobalVariables = [fieldMapperController globalValuesInUsage];
+ csvImportMethodHasTail = ([csvImportTailString length] == 0) ? NO : YES;
+ insertRemainingRowsAfterUpdate = [fieldMapperController insertRemainingRowsAfterUpdate];
+ importMethodIsUpdate = ([selectedImportMethod isEqualToString:@"UPDATE"]) ? YES : NO;
+
+ // Error checking
+ if( ![fieldMapperOperator count]
+ || ![fieldMappingArray count]
+ || ![selectedImportMethod length]
+ || ![selectedTableTarget length]
+ || ![csvImportHeaderString length])
+ {
+ if(fieldMapperController) [fieldMapperController release];
+ NSBeep();
+ return FALSE;
+ }
+
+ [importFieldNamesSwitch setState:[fieldMapperController importFieldNamesHeader]];
+ [prefs setBool:[importFieldNamesSwitch state] forKey:SPCSVImportFirstLineIsHeader];
+
+ if(fieldMapperController) [fieldMapperController release];
+
+ if(fieldMapperSheetStatus == 2)
+ return YES;
+ else
+ return NO;
+}
+
+/**
+ *
+ */
+- (void)fieldMapperDidEndSheet:(NSWindow *)sheet returnCode:(NSInteger)returnCode contextInfo:(void *)contextInfo
+{
+ [sheet orderOut:self];
+ fieldMapperSheetStatus = (returnCode) ? 2 : 3;
+}
+
+/**
+ * Construct the SET and WHERE clause for a CSV row, based on the field mapping array
+ * for the import method "UPDATE".
+ */
+- (NSString *)mappedUpdateSetStatementStringForRowArray:(NSArray *)csvRowArray
+{
+
+ NSMutableString *setString = [NSMutableString stringWithString:@""];
+ NSMutableString *whereString = [NSMutableString stringWithString:@"WHERE "];
+
+ NSInteger i;
+ NSInteger mapColumn;
+ id cellData;
+ NSInteger mappingArrayCount = [fieldMappingArray count];
+
+ for (i = 0; i < mappingArrayCount; i++) {
+
+ // Skip unmapped columns
+ if ([NSArrayObjectAtIndex(fieldMapperOperator, i) integerValue] == 1 ) continue;
+
+ mapColumn = [NSArrayObjectAtIndex(fieldMappingArray, i) integerValue];
+
+ // SET clause
+ if ([NSArrayObjectAtIndex(fieldMapperOperator, i) integerValue] == 0 ) {
+ if ([setString length] > 1) [setString appendString:@","];
+ [setString appendString:[NSArrayObjectAtIndex(fieldMappingTableColumnNames, i) backtickQuotedString]];
+ [setString appendString:@"="];
+ // Append the data
+ // - check for global values
+ if(fieldMappingArrayHasGlobalVariables && mapColumn >= numberOfImportDataColumns) {
+ // Global variables are coming wrapped in ' ' if there're not marked as SQL
+ [setString appendString:NSArrayObjectAtIndex(fieldMappingGlobalValueArray, mapColumn)];
+ } else {
+ cellData = NSArrayObjectAtIndex(csvRowArray, mapColumn);
+
+ // If import column isn't specified import the table column default value
+ if ([cellData isSPNotLoaded])
+ cellData = NSArrayObjectAtIndex(fieldMappingTableDefaultValues, i);
+
+ if (cellData == [NSNull null]) {
+ [setString appendString:@"NULL"];
+ } else {
+ [setString appendString:@"'"];
+ [setString appendString:[mySQLConnection prepareString:cellData]];
+ [setString appendString:@"'"];
+ }
+ }
+ }
+ // WHERE clause
+ else if ([NSArrayObjectAtIndex(fieldMapperOperator, i) integerValue] == 2 )
+ {
+ if ([whereString length] > 7) [whereString appendString:@" AND "];
+ [whereString appendString:[NSArrayObjectAtIndex(fieldMappingTableColumnNames, i) backtickQuotedString]];
+ // Append the data
+ // - check for global values
+ if(fieldMappingArrayHasGlobalVariables && mapColumn >= numberOfImportDataColumns) {
+ // Global variables are coming wrapped in ' ' if there're not marked as SQL
+ [whereString appendString:@"="];
+ [whereString appendString:NSArrayObjectAtIndex(fieldMappingGlobalValueArray, mapColumn)];
+ } else {
+ cellData = NSArrayObjectAtIndex(csvRowArray, mapColumn);
+
+ // If import column isn't specified import the table column default value
+ if ([cellData isSPNotLoaded])
+ cellData = NSArrayObjectAtIndex(fieldMappingTableDefaultValues, i);
+
+ if (cellData == [NSNull null]) {
+ [whereString appendString:@" IS NULL"];
+ } else {
+ [whereString appendString:@"="];
+ [whereString appendString:@"'"];
+ [whereString appendString:[mySQLConnection prepareString:cellData]];
+ [whereString appendString:@"'"];
+ }
+ }
+ }
+ }
+
+ return [NSString stringWithFormat:@"%@ %@", setString, whereString];
+}
+
+/**
+ * Construct the VALUES string for a CSV row, based on the field mapping array - including
+ * surrounding brackets but not including the VALUES keyword.
+ */
+- (NSString *)mappedValueStringForRowArray:(NSArray *)csvRowArray
+{
+ NSMutableString *valueString = [NSMutableString stringWithString:@"("];
+ NSInteger i;
+ NSInteger mapColumn;
+ id cellData;
+ NSInteger mappingArrayCount = [fieldMappingArray count];
+
+ for (i = 0; i < mappingArrayCount; i++) {
+
+ // Skip unmapped columns
+ if ([NSArrayObjectAtIndex(fieldMapperOperator, i) integerValue] > 0) continue;
+
+ mapColumn = [NSArrayObjectAtIndex(fieldMappingArray, i) integerValue];
+
+ if ([valueString length] > 1) [valueString appendString:@","];
+
+ // Append the data
+ // - check for global values
+ if(fieldMappingArrayHasGlobalVariables && mapColumn >= numberOfImportDataColumns) {
+ // Global variables are coming wrapped in ' ' if there're not marked as SQL
+ [valueString appendString:NSArrayObjectAtIndex(fieldMappingGlobalValueArray, mapColumn)];
+ } else {
+ cellData = NSArrayObjectAtIndex(csvRowArray, mapColumn);
+
+ // If import column isn't specified import the table column default value
+ if ([cellData isSPNotLoaded])
+ cellData = NSArrayObjectAtIndex(fieldMappingTableDefaultValues, i);
+
+ if (cellData == [NSNull null]) {
+ [valueString appendString:@"NULL"];
+ } else {
+ [valueString appendString:@"'"];
+ [valueString appendString:[mySQLConnection prepareString:cellData]];
+ [valueString appendString:@"'"];
+ }
+ }
+ }
+
+ [valueString appendString:@")"];
+
+ return valueString;
+}
+
+#pragma mark -
+#pragma mark Import delegate notifications
+
+/**
+ * Called when the selection within an open/save panel changes.
+ */
+- (void)panelSelectionDidChange:(id)sender
+{
+ NSArray *selectedFilenames = [sender filenames];
+ NSString *pathExtension;
+
+ // If a single file is selected and the extension is recognised, change the format dropdown automatically
+ if ( [selectedFilenames count] != 1 ) return;
+ pathExtension = [[[selectedFilenames objectAtIndex:0] pathExtension] uppercaseString];
+
+ // If a file has extension ".gz", indicating gzip, fetch the next extension
+ if ([pathExtension isEqualToString:@"GZ"]) {
+ NSMutableString *pathString = [NSMutableString stringWithString:[selectedFilenames objectAtIndex:0]];
+ [pathString deleteCharactersInRange:NSMakeRange([pathString length]-3, 3)];
+ pathExtension = [[pathString pathExtension] uppercaseString];
+ }
+
+ if ([pathExtension isEqualToString:@"SQL"]) {
+ [importFormatPopup selectItemWithTitle:@"SQL"];
+ [self changeFormat:self];
+ } else if ([pathExtension isEqualToString:@"CSV"]) {
+ [importFormatPopup selectItemWithTitle:@"CSV"];
+ [self changeFormat:self];
+
+ // Try to detect the line endings using "file"
+ NSTask *fileTask = [[NSTask alloc] init];
+ NSPipe *filePipe = [[NSPipe alloc] init];
+
+ [fileTask setLaunchPath:@"/usr/bin/file"];
+ [fileTask setArguments:[NSArray arrayWithObjects:@"-L", @"-b", [selectedFilenames objectAtIndex:0], nil]];
+ [fileTask setStandardOutput:filePipe];
+ NSFileHandle *fileHandle = [filePipe fileHandleForReading];
+
+ [fileTask launch];
+
+ NSString *fileCheckOutput = [[NSString alloc] initWithData:[fileHandle readDataToEndOfFile] encoding:NSASCIIStringEncoding];
+ if (fileCheckOutput && [fileCheckOutput length]) {
+ NSString *lineEndingString = [fileCheckOutput stringByMatching:@"with ([A-Z]{2,4}) line terminators" capture:1L];
+ if (!lineEndingString && [fileCheckOutput isMatchedByRegex:@"text"]) lineEndingString = @"LF";
+ if (lineEndingString) {
+ if ([lineEndingString isEqualToString:@"LF"]) [importLinesTerminatedField setStringValue:@"\\n"];
+ else if ([lineEndingString isEqualToString:@"CR"]) [importLinesTerminatedField setStringValue:@"\\r"];
+ else if ([lineEndingString isEqualToString:@"CRLF"]) [importLinesTerminatedField setStringValue:@"\\r\\n"];
+ }
+ }
+ if (fileCheckOutput) [fileCheckOutput release];
+
+ [fileTask release];
+ [filePipe release];
+ }
+}
+
+#pragma mark -
+#pragma mark Other
+
+/**
+ * Sets the connection (received from SPDatabaseDocument) and makes things that have to be done only once.
+ */
+- (void)setConnection:(MCPConnection *)theConnection
+{
+ NSButtonCell *switchButton = [[NSButtonCell alloc] init];
+
+ prefs = [[NSUserDefaults standardUserDefaults] retain];
+
+ mySQLConnection = theConnection;
+
+ // Set up the interface
+ [switchButton setButtonType:NSSwitchButton];
+ [switchButton setControlSize:NSSmallControlSize];
+ [switchButton release];
+
+ if ([prefs boolForKey:SPUseMonospacedFonts]) {
+ [errorsView setFont:[NSFont fontWithName:SPDefaultMonospacedFontName size:[NSFont smallSystemFontSize]]];
+ } else {
+ [errorsView setFont:[NSFont systemFontOfSize:[NSFont smallSystemFontSize]]];
+ }
+}
+
+/**
+ *
+ */
+- (NSArray *)toolbarSelectableItemIdentifiers:(NSToolbar *)toolbar
+{
+ NSArray *array = [toolbar items];
+ NSMutableArray *items = [NSMutableArray arrayWithCapacity:6];
+
+ for (NSToolbarItem *item in array)
+ {
+ [items addObject:[item itemIdentifier]];
+ }
+
+ return items;
+}
+
+/**
+ *
+ */
+- (void)showErrorSheetWithMessage:(NSString*)message
+{
+ if (![NSThread isMainThread]) {
+ [self performSelectorOnMainThread:@selector(showErrorSheetWithMessage:) withObject:message waitUntilDone:YES];
+ return;
+ }
+
+ [errorsView setString:message];
+ [NSApp beginSheet:errorsSheet
+ modalForWindow:[tableDocumentInstance parentWindow]
+ modalDelegate:self
+ didEndSelector:@selector(sheetDidEnd:returnCode:contextInfo:)
+ contextInfo:nil];
+ [errorsSheet makeKeyWindow];
+}
+
+/**
+ *
+ */
+- (void)sheetDidEnd:(NSWindow *)sheet returnCode:(NSInteger)returnCode contextInfo:(void *)contextInfo
+{
+ [sheet orderOut:self];
+}
+
+#pragma mark -
+
+/**
+ * Dealloc.
+ */
+- (void)dealloc
+{
+ if (fieldMappingImportArray) [fieldMappingImportArray release];
+ if (lastFilename) [lastFilename release];
+ if (prefs) [prefs release];
+
+ for (id retainedObject in nibObjectsToRelease) [retainedObject release];
+
+ [nibObjectsToRelease release];
+
+ [super dealloc];
+}
+
+@end
37' href='#n2737'>2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883