aboutsummaryrefslogtreecommitdiffstats
path: root/Source/TableDump.m
diff options
context:
space:
mode:
authorrowanbeentje <rowan@beent.je>2009-09-14 00:14:25 +0000
committerrowanbeentje <rowan@beent.je>2009-09-14 00:14:25 +0000
commitf85e71af7997af33ca10ee581c20c7c2264c6287 (patch)
treeb0d1e2d4bf329c96c149ada7fd926a186f7cafe6 /Source/TableDump.m
parent1e2b95b113242895a988d0db02e7a7fe1708a63d (diff)
downloadsequelpro-f85e71af7997af33ca10ee581c20c7c2264c6287.tar.gz
sequelpro-f85e71af7997af33ca10ee581c20c7c2264c6287.tar.bz2
sequelpro-f85e71af7997af33ca10ee581c20c7c2264c6287.zip
Significantly improve export:
- Rework CSV export to stream data, significantly reducing memory consumption and so increasing speed and stability when exporting large tables. By default safe/fast streaming is used, but a checkbox is available to select "low memory mode" full streaming, allowing export of any size table in theory. This addresses Issue #224. - Rework XML export to stream data in the same way, also significantly reducing memory usage and providing the option of using low memory mode. - Make SQL, CSV and XML export progress bars update more smoothly - When exporting the current browse view or custom query result, show an indeterminate progress bar when copying large resultsets to avoid the app appearing to hang
Diffstat (limited to 'Source/TableDump.m')
-rw-r--r--Source/TableDump.m496
1 files changed, 314 insertions, 182 deletions
diff --git a/Source/TableDump.m b/Source/TableDump.m
index eaa86510..55f81e1a 100644
--- a/Source/TableDump.m
+++ b/Source/TableDump.m
@@ -148,6 +148,7 @@
case 6:
file = [NSString stringWithFormat:@"%@.csv", [tableDocumentInstance table]];
[savePanel setAccessoryView:exportCSVView];
+ [csvFullStreamingSwitch setEnabled:YES];
contextInfo = @"exportTableContentAsCSV";
break;
@@ -161,6 +162,7 @@
case 8:
file = [NSString stringWithFormat:@"%@ view.csv", [tableDocumentInstance table]];
[savePanel setAccessoryView:exportCSVView];
+ [csvFullStreamingSwitch setEnabled:NO];
contextInfo = @"exportBrowseViewAsCSV";
break;
@@ -174,6 +176,7 @@
case 10:
file = @"customresult.csv";
[savePanel setAccessoryView:exportCSVView];
+ [csvFullStreamingSwitch setEnabled:NO];
contextInfo = @"exportCustomResultAsCSV";
break;
@@ -277,46 +280,86 @@
} else if ( [contextInfo isEqualToString:@"exportTableContentAsXML"] ) {
success = [self exportTables:[NSArray arrayWithObject:[tableDocumentInstance table]] toFileHandle:fileHandle usingFormat:@"xml" usingMulti:NO];
- // Export the current "browse" view to a file in CSV format
- } else if ( [contextInfo isEqualToString:@"exportBrowseViewAsCSV"] ) {
- success = [self writeCsvForArray:[tableContentInstance currentResult] orQueryResult:nil
- toFileHandle:fileHandle
- outputFieldNames:[exportFieldNamesSwitch state]
- terminatedBy:[exportFieldsTerminatedField stringValue]
- enclosedBy:[exportFieldsEnclosedField stringValue]
- escapedBy:[exportFieldsEscapedField stringValue]
- lineEnds:[exportLinesTerminatedField stringValue]
- withNumericColumns:nil
- silently:NO];
-
- // Export the current "browse" view to a file in XML format
- } else if ( [contextInfo isEqualToString:@"exportBrowseViewAsXML"] ) {
- success = [self writeXmlForArray:[tableContentInstance currentResult] orQueryResult:nil
- toFileHandle:fileHandle
- tableName:(NSString *)[tableDocumentInstance table]
- withHeader:YES
- silently:NO];
-
- // Export the current custom query result set to a file in CSV format
- } else if ( [contextInfo isEqualToString:@"exportCustomResultAsCSV"] ) {
- success = [self writeCsvForArray:[customQueryInstance currentResult] orQueryResult:nil
- toFileHandle:fileHandle
- outputFieldNames:[exportFieldNamesSwitch state]
- terminatedBy:[exportFieldsTerminatedField stringValue]
- enclosedBy:[exportFieldsEnclosedField stringValue]
- escapedBy:[exportFieldsEscapedField stringValue]
- lineEnds:[exportLinesTerminatedField stringValue]
- withNumericColumns:nil
- silently:NO];
-
- // Export the current custom query result set to a file in XML format
- } else if ( [contextInfo isEqualToString:@"exportCustomResultAsXML"] ) {
- success = [self writeXmlForArray:[customQueryInstance currentResult] orQueryResult:nil
- toFileHandle:fileHandle
- tableName:@"custom"
- withHeader:YES
- silently:NO];
+ // Export the current "browse" view to a file in CSV or XML format
+ } else if ( [contextInfo isEqualToString:@"exportBrowseViewAsCSV"]
+ || [contextInfo isEqualToString:@"exportBrowseViewAsXML"] )
+ {
+
+ // Start an indeterminate progress sheet, as getting the current result set can take a significant period of time
+ [singleProgressTitle setStringValue:[NSString stringWithFormat:NSLocalizedString(@"Exporting content view to CSV", @"title showing that application is saving content view as CSV")]];
+ [singleProgressText setStringValue:NSLocalizedString(@"Exporting data...", @"text showing that app is preparing data")];
+ [singleProgressBar setUsesThreadedAnimation:YES];
+ [singleProgressBar setIndeterminate:YES];
+ [NSApp beginSheet:singleProgressSheet modalForWindow:tableWindow modalDelegate:self didEndSelector:nil contextInfo:nil];
+
+ [singleProgressBar startAnimation:self];
+ NSArray *contentViewArray = [tableContentInstance currentResult];
+
+ if ( [contextInfo isEqualToString:@"exportBrowseViewAsCSV"] ) {
+ success = [self writeCsvForArray:contentViewArray orStreamingResult:nil
+ toFileHandle:fileHandle
+ outputFieldNames:[exportFieldNamesSwitch state]
+ terminatedBy:[exportFieldsTerminatedField stringValue]
+ enclosedBy:[exportFieldsEnclosedField stringValue]
+ escapedBy:[exportFieldsEscapedField stringValue]
+ lineEnds:[exportLinesTerminatedField stringValue]
+ withNumericColumns:nil
+ totalRows:[contentViewArray count]
+ silently:YES];
+ } else {
+ success = [self writeXmlForArray:contentViewArray orStreamingResult:nil
+ toFileHandle:fileHandle
+ tableName:(NSString *)[tableDocumentInstance table]
+ withHeader:YES
+ totalRows:[contentViewArray count]
+ silently:YES];
+ }
+
+ // Close the progress sheet
+ [singleProgressBar stopAnimation:self];
+ [NSApp endSheet:singleProgressSheet];
+ [singleProgressSheet orderOut:nil];
+ // Export the current custom query result set to a file in CSV or XML format
+ } else if ( [contextInfo isEqualToString:@"exportCustomResultAsCSV"]
+ || [contextInfo isEqualToString:@"exportCustomResultAsXML"] )
+ {
+
+ // Start an indeterminate progress sheet, as getting the current result set can take a significant period of time
+ [singleProgressTitle setStringValue:[NSString stringWithFormat:NSLocalizedString(@"Exporting custom query view to CSV", @"title showing that application is saving custom query view as CSV")]];
+ [singleProgressText setStringValue:NSLocalizedString(@"Exporting data...", @"text showing that app is preparing data")];
+ [singleProgressBar setUsesThreadedAnimation:YES];
+ [singleProgressBar setIndeterminate:YES];
+ [NSApp beginSheet:singleProgressSheet modalForWindow:tableWindow modalDelegate:self didEndSelector:nil contextInfo:nil];
+
+ [singleProgressBar startAnimation:self];
+ NSArray *customQueryViewArray = [customQueryInstance currentResult];
+
+ if ( [contextInfo isEqualToString:@"exportCustomResultAsCSV"] ) {
+ success = [self writeCsvForArray:customQueryViewArray orStreamingResult:nil
+ toFileHandle:fileHandle
+ outputFieldNames:[exportFieldNamesSwitch state]
+ terminatedBy:[exportFieldsTerminatedField stringValue]
+ enclosedBy:[exportFieldsEnclosedField stringValue]
+ escapedBy:[exportFieldsEscapedField stringValue]
+ lineEnds:[exportLinesTerminatedField stringValue]
+ withNumericColumns:nil
+ totalRows:[customQueryViewArray count]
+ silently:YES];
+ } else {
+ success = [self writeXmlForArray:customQueryViewArray orStreamingResult:nil
+ toFileHandle:fileHandle
+ tableName:@"custom"
+ withHeader:YES
+ totalRows:[customQueryViewArray count]
+ silently:YES];
+ }
+
+ // Close the progress sheet
+ [singleProgressBar stopAnimation:self];
+ [NSApp endSheet:singleProgressSheet];
+ [singleProgressSheet orderOut:nil];
+
// Export multiple tables to a file in CSV format
} else if ( [contextInfo isEqualToString:@"exportMultipleTablesAsCSV"] ) {
success = [self exportSelectedTablesToFileHandle:fileHandle usingFormat:@"csv"];
@@ -977,7 +1020,7 @@
- (BOOL)dumpSelectedTablesAsSqlToFileHandle:(NSFileHandle *)fileHandle
{
int i,j,t,rowCount, colCount, lastProgressValue, queryLength;
- // int progressBarWidth;
+ int progressBarWidth;
int tableType = SP_TABLETYPE_TABLE; //real tableType will be setup later
MCPResult *queryResult;
MCPStreamingResult *streamingResult;
@@ -1007,6 +1050,8 @@
[singleProgressText displayIfNeeded];
[singleProgressBar setDoubleValue:0];
[singleProgressBar displayIfNeeded];
+ progressBarWidth = (int)[singleProgressBar bounds].size.width;
+ [singleProgressBar setMaxValue:progressBarWidth];
// Open the progress sheet
[NSApp beginSheet:singleProgressSheet
@@ -1128,7 +1173,7 @@
}
// Retrieve the number of rows in the table for progress bar drawing
- rowCount = [[[[mySQLConnection queryString:[NSString stringWithFormat:@"SELECT COUNT(1) FROM %@", [tableName backtickQuotedString]]] fetchRowAsArray] objectAtIndex:0] intValue];
+ rowCount = [[[[mySQLConnection queryString:[NSString stringWithFormat:@"SELECT COUNT(1) FROM %@", [tableName backtickQuotedString]]] fetchRowAsArray] objectAtIndex:0] integerValue];
// Set up a result set in streaming mode
streamingResult = [mySQLConnection streamingQueryString:[NSString stringWithFormat:@"SELECT * FROM %@", [tableName backtickQuotedString]] useLowMemoryBlockingStreaming:([sqlFullStreamingSwitch state] == NSOnState)];
@@ -1163,7 +1208,7 @@
[sqlString setString:@""];
// Update the progress bar
- [singleProgressBar setDoubleValue:(j*100/rowCount)];
+ [singleProgressBar setDoubleValue:(j*progressBarWidth/rowCount)];
if ((int)[singleProgressBar doubleValue] > lastProgressValue) {
lastProgressValue = (int)[singleProgressBar doubleValue];
[singleProgressBar displayIfNeeded];
@@ -1295,7 +1340,10 @@
// Close the progress sheet
[NSApp endSheet:singleProgressSheet];
[singleProgressSheet orderOut:nil];
-
+
+ // Restore the default maximum of the progress bar
+ [singleProgressBar setMaxValue:100];
+
// Show errors sheet if there have been errors
if ( [errors length] ) {
[errorsView setString:errors];
@@ -1461,31 +1509,42 @@
/*
- Takes an array and writes it in CSV format to the supplied NSFileHandle
+ * Takes an array, or a streaming result set, and writes the appropriate data
+ * in CSV format to the supplied NSFileHandle.
+ * The field terminators, quotes and escape characters should all be supplied
+ * together with the line terminators; if an array of numeric column types is
+ * supplied, processing of rows is significantly sped up as each field does not
+ * need to be parsed.
+ * Also takes a totalRows parameter, which is used for drawing progress bars -
+ * for arrays, this must be accurate, but for streaming result sets it is only
+ * used for drawing the progress bar.
*/
-- (BOOL)writeCsvForArray:(NSArray *)array orQueryResult:(MCPResult *)queryResult toFileHandle:(NSFileHandle *)fileHandle
+- (BOOL)writeCsvForArray:(NSArray *)array orStreamingResult:(MCPStreamingResult *)streamingResult toFileHandle:(NSFileHandle *)fileHandle
outputFieldNames:(BOOL)outputFieldNames
terminatedBy:(NSString *)fieldSeparatorString
enclosedBy:(NSString *)enclosingString
escapedBy:(NSString *)escapeString
lineEnds:(NSString *)lineEndString
withNumericColumns:(NSArray *)tableColumnNumericStatus
+ totalRows:(NSInteger)totalRows
silently:(BOOL)silently;
{
+ NSAutoreleasePool *csvExportPool;
NSStringEncoding tableEncoding = [MCPConnection encodingForMySQLEncoding:[[tableDocumentInstance connectionEncoding] UTF8String]];
- NSMutableString *csvCell = [NSMutableString string];
- NSMutableArray *csvRow = [NSMutableArray array];
+ NSMutableString *csvCellString = [NSMutableString string];
+ NSArray *csvRow;
+ id csvCell;
NSMutableString *csvString = [NSMutableString string];
NSString *nullString = [NSString stringWithString:[prefs objectForKey:@"NullValue"]];
NSString *escapedEscapeString, *escapedFieldSeparatorString, *escapedEnclosingString, *escapedLineEndString;
NSString *dataConversionString;
+ NSInteger currentRowIndex;
NSScanner *csvNumericTester;
BOOL quoteFieldSeparators = [enclosingString isEqualToString:@""];
BOOL csvCellIsNumeric;
- int i, j, startingRow, totalRows, progressBarWidth, lastProgressValue;
-
- if (queryResult != nil && [queryResult numOfRows]) [queryResult dataSeek:0];
-
+ int i, progressBarWidth, lastProgressValue, currentPoolDataLength;
+ int csvCellCount = 0;
+
// Detect and restore special characters being used as terminating or line end strings
NSMutableString *tempSeparatorString = [NSMutableString stringWithString:fieldSeparatorString];
[tempSeparatorString replaceOccurrencesOfString:@"\\t" withString:@"\t"
@@ -1513,7 +1572,9 @@
// Updating the progress bar can take >20% of processing time - store details to only update when required
progressBarWidth = (int)[singleProgressBar bounds].size.width;
lastProgressValue = 0;
+ [singleProgressBar setMaxValue:progressBarWidth];
[singleProgressBar setDoubleValue:0];
+ [singleProgressBar setIndeterminate:NO];
[singleProgressBar setUsesThreadedAnimation:YES];
[singleProgressBar displayIfNeeded];
@@ -1521,9 +1582,7 @@
// Set the progress text
[singleProgressTitle setStringValue:NSLocalizedString(@"Exporting CSV", @"text showing that the application is exporting a CSV")];
- [singleProgressText setStringValue:NSLocalizedString(@"Exporting...", @"text showing that app is exporting to text file")];
- // [singleProgressText displayIfNeeded];
-
+ [singleProgressText setStringValue:NSLocalizedString(@"Writing...", @"text showing that app is writing text file")];
// Open progress sheet
[NSApp beginSheet:singleProgressSheet
@@ -1537,134 +1596,156 @@
escapedEnclosingString = [NSString stringWithFormat:@"%@%@", escapeString, enclosingString];
escapedLineEndString = [NSString stringWithFormat:@"%@%@", escapeString, lineEndString];
- // Determine the total number of rows and starting row depending on supplied data format
- if (array == nil) {
- startingRow = outputFieldNames ? -1 : 0;
- totalRows = [queryResult numOfRows];
- } else {
- startingRow = outputFieldNames ? 0 : 1;
- totalRows = [array count];
+ // Set up the starting row; for supplied arrays, which include the column
+ // headers as the first row, decide whether to skip the first row.
+ currentRowIndex = 0;
+ if (array && !outputFieldNames) {
+ currentRowIndex++;
}
-
- // Walk through the supplied data constructing the CSV string
- for ( i = startingRow ; i < totalRows ; i++ ) {
-
- // Update the progress bar
- if (totalRows) [singleProgressBar setDoubleValue:((i+1)*100/totalRows)];
- if ((int)[singleProgressBar doubleValue] > lastProgressValue) {
- lastProgressValue = (int)[singleProgressBar doubleValue];
- [singleProgressBar displayIfNeeded];
- }
-
- // Retrieve the row from the supplied data
- if (array == nil) {
+
+ // Drop into the processing loop
+ csvExportPool = [[NSAutoreleasePool alloc] init];
+ currentPoolDataLength = 0;
+ while (1) {
+
+ // Retrieve the next row from the supplied data, either directly from the array...
+ if (array) {
+ csvRow = NSArrayObjectAtIndex(array, currentRowIndex);
+
+ // Or by reading an appropriate row from the streaming result
+ } else {
- // Header row
- if (i == -1) {
- [csvRow setArray:[queryResult fetchFieldNames]];
+ // If still requested to read the field names, get the field names
+ if (outputFieldNames) {
+ csvRow = [streamingResult fetchFieldNames];
+ outputFieldNames = NO;
} else {
- [csvRow setArray:[queryResult fetchRowAsArray]];
+ csvRow = [streamingResult fetchNextRowAsArray];
+ if (!csvRow) break;
}
- } else {
- [csvRow setArray:NSArrayObjectAtIndex(array, i)];
}
+ // Get the cell count if we don't already have it stored
+ if (!csvCellCount) csvCellCount = [csvRow count];
+
[csvString setString:@""];
- for ( j = 0 ; j < [csvRow count] ; j++ ) {
-
+ for ( i = 0 ; i < csvCellCount ; i++ ) {
+ csvCell = NSArrayObjectAtIndex(csvRow, i);
+
// For NULL objects supplied from a queryResult, add an unenclosed null string as per prefs
- if ([[csvRow objectAtIndex:j] isKindOfClass:[NSNull class]]) {
+ if ([csvCell isKindOfClass:[NSNull class]]) {
[csvString appendString:nullString];
- if (j < [csvRow count] - 1) [csvString appendString:fieldSeparatorString];
+ if (i < csvCellCount - 1) [csvString appendString:fieldSeparatorString];
continue;
}
// Retrieve the contents of this cell
- if ([NSArrayObjectAtIndex(csvRow, j) isKindOfClass:[NSData class]]) {
- dataConversionString = [[NSString alloc] initWithData:NSArrayObjectAtIndex(csvRow, j) encoding:tableEncoding];
+ if ([csvCell isKindOfClass:[NSData class]]) {
+ dataConversionString = [[NSString alloc] initWithData:csvCell encoding:tableEncoding];
if (dataConversionString == nil)
- dataConversionString = [[NSString alloc] initWithData:NSArrayObjectAtIndex(csvRow, j) encoding:NSASCIIStringEncoding];
- [csvCell setString:[NSString stringWithString:dataConversionString]];
+ dataConversionString = [[NSString alloc] initWithData:csvCell encoding:NSASCIIStringEncoding];
+ [csvCellString setString:[NSString stringWithString:dataConversionString]];
[dataConversionString release];
} else {
- [csvCell setString:[NSArrayObjectAtIndex(csvRow, j) description]];
+ [csvCellString setString:[csvCell description]];
}
// For NULL values supplied via an array add the unenclosed null string as set in preferences
- if ( [csvCell isEqualToString:nullString] ) {
+ if ( [csvCellString isEqualToString:nullString] ) {
[csvString appendString:nullString];
// Add empty strings as a pair of enclosing characters.
- } else if ( [csvCell length] == 0 ) {
+ } else if ( [csvCellString length] == 0 ) {
[csvString appendString:enclosingString];
[csvString appendString:enclosingString];
} else {
- // Test whether this cell contains a number
- if ([NSArrayObjectAtIndex(csvRow, j) isKindOfClass:[NSData class]]) {
- csvCellIsNumeric = FALSE;
-
// If an array of bools supplying information as to whether the column is numeric has been supplied, use it.
- } else if (tableColumnNumericStatus != nil) {
- csvCellIsNumeric = [NSArrayObjectAtIndex(tableColumnNumericStatus, j) boolValue];
+ if (tableColumnNumericStatus != nil) {
+ csvCellIsNumeric = [NSArrayObjectAtIndex(tableColumnNumericStatus, i) boolValue];
+
+ // Otherwise, first test whether this cell contains data
+ } else if ([NSArrayObjectAtIndex(csvRow, i) isKindOfClass:[NSData class]]) {
+ csvCellIsNumeric = FALSE;
// Or fall back to testing numeric content via an NSScanner.
} else {
- csvNumericTester = [NSScanner scannerWithString:csvCell];
+ csvNumericTester = [NSScanner scannerWithString:csvCellString];
csvCellIsNumeric = [csvNumericTester scanFloat:nil] && [csvNumericTester isAtEnd]
- && ([csvCell characterAtIndex:0] != '0'
- || [csvCell length] == 1
- || ([csvCell length] > 1 && [csvCell characterAtIndex:1] == '.'));
+ && ([csvCellString characterAtIndex:0] != '0'
+ || [csvCellString length] == 1
+ || ([csvCellString length] > 1 && [csvCellString characterAtIndex:1] == '.'));
}
// Escape any occurrences of the escaping character
- [csvCell replaceOccurrencesOfString:escapeString
- withString:escapedEscapeString
- options:NSLiteralSearch
- range:NSMakeRange(0,[csvCell length])];
+ [csvCellString replaceOccurrencesOfString:escapeString
+ withString:escapedEscapeString
+ options:NSLiteralSearch
+ range:NSMakeRange(0, [csvCellString length])];
// Escape any occurrences of the enclosure string
if ( ![escapeString isEqualToString:enclosingString] ) {
- [csvCell replaceOccurrencesOfString:enclosingString
- withString:escapedEnclosingString
- options:NSLiteralSearch
- range:NSMakeRange(0,[csvCell length])];
+ [csvCellString replaceOccurrencesOfString:enclosingString
+ withString:escapedEnclosingString
+ options:NSLiteralSearch
+ range:NSMakeRange(0, [csvCellString length])];
}
// Escape occurrences of the line end character
- [csvCell replaceOccurrencesOfString:lineEndString
- withString:escapedLineEndString
- options:NSLiteralSearch
- range:NSMakeRange(0,[csvCell length])];
+ [csvCellString replaceOccurrencesOfString:lineEndString
+ withString:escapedLineEndString
+ options:NSLiteralSearch
+ range:NSMakeRange(0, [csvCellString length])];
// If the string isn't quoted or otherwise enclosed, escape occurrences of the
// field separators
if ( quoteFieldSeparators || csvCellIsNumeric ) {
- [csvCell replaceOccurrencesOfString:fieldSeparatorString
- withString:escapedFieldSeparatorString
- options:NSLiteralSearch
- range:NSMakeRange(0,[csvCell length])];
+ [csvCellString replaceOccurrencesOfString:fieldSeparatorString
+ withString:escapedFieldSeparatorString
+ options:NSLiteralSearch
+ range:NSMakeRange(0, [csvCellString length])];
}
// Write out the cell data by appending strings - this is significantly faster than stringWithFormat.
if (csvCellIsNumeric) {
- [csvString appendString:csvCell];
+ [csvString appendString:csvCellString];
} else {
[csvString appendString:enclosingString];
- [csvString appendString:csvCell];
+ [csvString appendString:csvCellString];
[csvString appendString:enclosingString];
}
}
- if (j < [csvRow count] - 1) [csvString appendString:fieldSeparatorString];
+ if (i < csvCellCount - 1) [csvString appendString:fieldSeparatorString];
}
- // Append the line ending to the string for this row
+ // Append the line ending to the string for this row, and record the length processed for pool flushing
[csvString appendString:lineEndString];
+ currentPoolDataLength += [csvString length];
// Write it to the fileHandle
[fileHandle writeData:[csvString dataUsingEncoding:tableEncoding]];
+
+ // Update the progress counter and progress bar
+ currentRowIndex++;
+ if (totalRows)
+ [singleProgressBar setDoubleValue:(currentRowIndex*progressBarWidth/totalRows)];
+ if ((int)[singleProgressBar doubleValue] > lastProgressValue) {
+ lastProgressValue = (int)[singleProgressBar doubleValue];
+ [singleProgressBar displayIfNeeded];
+ }
+
+ // If an array was supplied and we've processed all rows, break
+ if (array && totalRows == currentRowIndex) break;
+
+ // Drain the autorelease pool as required to keep memory usage low
+ if (currentPoolDataLength > 250000) {
+ [csvExportPool drain];
+ csvExportPool = [[NSAutoreleasePool alloc] init];
+ }
}
+
+ [csvExportPool drain];
// Close the progress sheet if it's present
if ( !silently ) {
@@ -1672,6 +1753,9 @@
[singleProgressSheet orderOut:nil];
}
+ // Restore the progress bar to a normal maximum
+ [singleProgressBar setMaxValue:100];
+
return TRUE;
}
@@ -1905,48 +1989,52 @@
/*
- Takes an array and writes it in XML format to the supplied NSFileHandle
+ * Takes an array, or streaming result reference, and writes it in XML
+ * format to the supplied NSFileHandle. For output, also takes a table
+ * name for tag construction, and a toggle to control whether the header
+ * is output.
+ * Also takes a totalRows parameter, which is used for drawing progress bars -
+ * for arrays, this must be accurate, but for streaming result sets it is only
+ * used for drawing the progress bar.
*/
-- (BOOL)writeXmlForArray:(NSArray *)array orQueryResult:(MCPResult *)queryResult toFileHandle:(NSFileHandle *)fileHandle tableName:(NSString *)table withHeader:(BOOL)header silently:(BOOL)silently
+- (BOOL)writeXmlForArray:(NSArray *)array orStreamingResult:(MCPStreamingResult *)streamingResult toFileHandle:(NSFileHandle *)fileHandle tableName:(NSString *)table withHeader:(BOOL)header totalRows:(NSInteger)totalRows silently:(BOOL)silently
{
+ NSAutoreleasePool *xmlExportPool;
NSStringEncoding tableEncoding = [MCPConnection encodingForMySQLEncoding:[[tableDocumentInstance connectionEncoding] UTF8String]];
NSMutableArray *xmlTags = [NSMutableArray array];
- NSMutableArray *xmlRow = [NSMutableArray array];
+ NSArray *xmlRow;
NSMutableString *xmlString = [NSMutableString string];
NSMutableString *xmlItem = [NSMutableString string];
NSString *dataConversionString;
- int i,j, startingRow, totalRows, lastProgressValue;
- // int progressBarWidth;
-
- if (queryResult != nil && [queryResult numOfRows]) [queryResult dataSeek:0];
+ int i, currentRowIndex, lastProgressValue, progressBarWidth, currentPoolDataLength;
+ int xmlRowCount = 0;
// Updating the progress bar can take >20% of processing time - store details to only update when required
- //progressBarWidth = (int)[singleProgressBar bounds].size.width;
+ progressBarWidth = (int)[singleProgressBar bounds].size.width;
lastProgressValue = 0;
+ [singleProgressBar setMaxValue:progressBarWidth];
[singleProgressBar setDoubleValue:0];
[singleProgressBar displayIfNeeded];
// Set up an array of encoded field names as opening and closing tags
- if (array == nil) {
- [xmlRow setArray:[queryResult fetchFieldNames]];
+ if (array) {
+ xmlRow = [array objectAtIndex:0];
} else {
- [xmlRow setArray:[array objectAtIndex:0]];
+ xmlRow = [streamingResult fetchFieldNames];
}
- for ( j = 0; j < [xmlRow count]; j++ ) {
+ for ( i = 0; i < [xmlRow count]; i++ ) {
[xmlTags addObject:[NSMutableArray array]];
- [[xmlTags objectAtIndex:j] addObject:[NSString stringWithFormat:@"\t\t<%@>",
- [self htmlEscapeString:[[xmlRow objectAtIndex:j] description]]]];
- [[xmlTags objectAtIndex:j] addObject:[NSString stringWithFormat:@"</%@>\n",
- [self htmlEscapeString:[[xmlRow objectAtIndex:j] description]]]];
+ [[xmlTags objectAtIndex:i] addObject:[NSString stringWithFormat:@"\t\t<%@>",
+ [self htmlEscapeString:[[xmlRow objectAtIndex:i] description]]]];
+ [[xmlTags objectAtIndex:i] addObject:[NSString stringWithFormat:@"</%@>\n",
+ [self htmlEscapeString:[[xmlRow objectAtIndex:i] description]]]];
}
if ( !silently ) {
// Set the progress text
[singleProgressTitle setStringValue:NSLocalizedString(@"Exporting XML", @"text showing that the application is exporting XML")];
- [singleProgressTitle displayIfNeeded];
[singleProgressText setStringValue:NSLocalizedString(@"Writing...", @"text showing that app is writing text file")];
- [singleProgressText displayIfNeeded];
// Open progress sheet
[NSApp beginSheet:singleProgressSheet
@@ -1975,58 +2063,74 @@
[self htmlEscapeString:table]]
dataUsingEncoding:tableEncoding]];
- // Determine the total number of rows and starting row depending on supplied data format
- if (array == nil) {
- startingRow = 0;
- totalRows = [queryResult numOfRows];
- } else {
- startingRow = 1;
- totalRows = [array count];
- }
-
- // Walk through the array, contructing the XML string.
- // Note: the XML array starts at index 1 thus we have to iterate
- // to i < totalRows + 1 in order to output the very last row.
- for ( i = 1 ; i < totalRows + 1 ; i++ ) {
-
- // Update the progress bar
- if (totalRows) [singleProgressBar setDoubleValue:((i+1)*100/totalRows)];
- if ((int)[singleProgressBar doubleValue] > lastProgressValue) {
- lastProgressValue = (int)[singleProgressBar doubleValue];
- [singleProgressBar displayIfNeeded];
- }
-
- // Retrieve the row from the supplied data
- if (array == nil) {
- [xmlRow setArray:[queryResult fetchRowAsArray]];
+ // Set up the starting row, which is 0 for streaming result sets and
+ // 1 for supplied arrays which include the column headers as the first row.
+ currentRowIndex = 0;
+ if (array) currentRowIndex++;
+
+ // Drop into the processing loop
+ xmlExportPool = [[NSAutoreleasePool alloc] init];
+ currentPoolDataLength = 0;
+ while (1) {
+
+ // Retrieve the next row from the supplied data, either directly from the array...
+ if (array) {
+ xmlRow = NSArrayObjectAtIndex(array, currentRowIndex);
+
+ // Or by reading an appropriate row from the streaming result
} else {
- [xmlRow setArray:[array objectAtIndex:i]];
+ xmlRow = [streamingResult fetchNextRowAsArray];
+ if (!xmlRow) break;
}
+
+ // Get the cell count if we don't already have it stored
+ if (!xmlRowCount) xmlRowCount = [xmlRow count];
// Construct the row
[xmlString setString:@"\t<row>\n"];
- for ( j = 0 ; j < [xmlRow count] ; j++ ) {
+ for ( i = 0 ; i < xmlRowCount ; i++ ) {
// Retrieve the contents of this tag
- if ([[xmlRow objectAtIndex:j] isKindOfClass:[NSData class]]) {
- dataConversionString = [[NSString alloc] initWithData:[xmlRow objectAtIndex:j] encoding:tableEncoding];
+ if ([NSArrayObjectAtIndex(xmlRow, i) isKindOfClass:[NSData class]]) {
+ dataConversionString = [[NSString alloc] initWithData:NSArrayObjectAtIndex(xmlRow, i) encoding:tableEncoding];
if (dataConversionString == nil)
- dataConversionString = [[NSString alloc] initWithData:[xmlRow objectAtIndex:j] encoding:NSASCIIStringEncoding];
+ dataConversionString = [[NSString alloc] initWithData:NSArrayObjectAtIndex(xmlRow, i) encoding:NSASCIIStringEncoding];
[xmlItem setString:[NSString stringWithString:dataConversionString]];
[dataConversionString release];
} else {
- [xmlItem setString:[[xmlRow objectAtIndex:j] description]];
+ [xmlItem setString:[NSArrayObjectAtIndex(xmlRow, i) description]];
}
// Add the opening and closing tag and the contents to the XML string
- [xmlString appendString:[[xmlTags objectAtIndex:j] objectAtIndex:0]];
+ [xmlString appendString:NSArrayObjectAtIndex(NSArrayObjectAtIndex(xmlTags, i), 0)];
[xmlString appendString:[self htmlEscapeString:xmlItem]];
- [xmlString appendString:[[xmlTags objectAtIndex:j] objectAtIndex:1]];
+ [xmlString appendString:NSArrayObjectAtIndex(NSArrayObjectAtIndex(xmlTags, i), 1)];
}
[xmlString appendString:@"\t</row>\n"];
+ // Record the total length for use with pool flushing
+ currentPoolDataLength += [xmlString length];
+
// Write the row to the filehandle
[fileHandle writeData:[xmlString dataUsingEncoding:tableEncoding]];
+
+ // Update the progress counter and progress bar
+ currentRowIndex++;
+ if (totalRows)
+ [singleProgressBar setDoubleValue:(currentRowIndex*progressBarWidth/totalRows)];
+ if ((int)[singleProgressBar doubleValue] > lastProgressValue) {
+ lastProgressValue = (int)[singleProgressBar doubleValue];
+ [singleProgressBar displayIfNeeded];
+ }
+
+ // If an array was supplied and we've processed all rows, break
+ if (array && totalRows == currentRowIndex) break;
+
+ // Drain the autorelease pool as required to keep memory usage low
+ if (currentPoolDataLength > 250000) {
+ [xmlExportPool drain];
+ xmlExportPool = [[NSAutoreleasePool alloc] init];
+ }
}
// Write the closing tag for the table
@@ -2034,12 +2138,17 @@
[self htmlEscapeString:table]]
dataUsingEncoding:tableEncoding]];
+ [xmlExportPool drain];
+
// Close the progress sheet if appropriate
if ( !silently ) {
[NSApp endSheet:singleProgressSheet];
[singleProgressSheet orderOut:nil];
}
-
+
+ // Restore the progress bar to a normal maximum
+ [singleProgressBar setMaxValue:100];
+
return TRUE;
}
@@ -2070,6 +2179,8 @@
{
int i, j;
MCPResult *queryResult;
+ MCPStreamingResult *streamingResult;
+ NSInteger streamingResultCount;
NSString *tableName, *tableColumnTypeGrouping;
NSMutableString *infoString = [NSMutableString string];
NSMutableString *errors = [NSMutableString string];
@@ -2167,16 +2278,27 @@
}
}
- // Retrieve all the content within this table
- queryResult = [mySQLConnection queryString:[NSString stringWithFormat:@"SELECT * FROM %@", [tableName backtickQuotedString]]];
-
- // Note any errors during retrieval
+ BOOL useLowMemoryBlockingStreaming;
+ if ([type isEqualToString:@"csv"]) {
+ if (multi)
+ useLowMemoryBlockingStreaming = ([multiCSVFullStreamingSwitch state] == NSOnState);
+ else
+ useLowMemoryBlockingStreaming = ([csvFullStreamingSwitch state] == NSOnState);
+ } else {
+ useLowMemoryBlockingStreaming = ([multiXMLFullStreamingSwitch state] == NSOnState);
+ }
+
+ // Perform a COUNT for progress purposes and make a streaming request for the data
+ streamingResultCount = [[[[mySQLConnection queryString:[NSString stringWithFormat:@"SELECT COUNT(1) FROM %@", [tableName backtickQuotedString]]] fetchRowAsArray] objectAtIndex:0] integerValue];
+ streamingResult = [mySQLConnection streamingQueryString:[NSString stringWithFormat:@"SELECT * FROM %@", [tableName backtickQuotedString]] useLowMemoryBlockingStreaming:useLowMemoryBlockingStreaming];
+
+ // Note any errors during initial query
if ( ![[mySQLConnection getLastErrorMessage] isEqualToString:@""] ) {
[errors appendString:[NSString stringWithFormat:@"%@\n", [mySQLConnection getLastErrorMessage]]];
}
-
+
// Update the progress text and set the progress bar back to determinate
- [singleProgressText setStringValue:[NSString stringWithFormat:NSLocalizedString(@"Table %i of %i (%@): Writing...", @"text showing that app is writing data for table export"), (i+1), [selectedTables count], tableName]];
+ [singleProgressText setStringValue:[NSString stringWithFormat:NSLocalizedString(@"Table %i of %i (%@): Writing data...", @"text showing that app is writing data for table export"), (i+1), [selectedTables count], tableName]];
[singleProgressText displayIfNeeded];
[singleProgressBar stopAnimation:self];
[singleProgressBar setUsesThreadedAnimation:NO];
@@ -2187,7 +2309,7 @@
// Use the appropriate export method to write the data to file
if ( [type isEqualToString:@"csv"] ) {
if (multi) {
- [self writeCsvForArray:nil orQueryResult:queryResult
+ [self writeCsvForArray:nil orStreamingResult:streamingResult
toFileHandle:fileHandle
outputFieldNames:[exportMultipleFieldNamesSwitch state]
terminatedBy:[exportMultipleFieldsTerminatedField stringValue]
@@ -2195,9 +2317,10 @@
escapedBy:[exportMultipleFieldsEscapedField stringValue]
lineEnds:[exportMultipleLinesTerminatedField stringValue]
withNumericColumns:tableColumnNumericStatus
+ totalRows:streamingResultCount
silently:YES];
} else {
- [self writeCsvForArray:nil orQueryResult:queryResult
+ [self writeCsvForArray:nil orStreamingResult:streamingResult
toFileHandle:fileHandle
outputFieldNames:[exportFieldNamesSwitch state]
terminatedBy:[exportFieldsTerminatedField stringValue]
@@ -2205,22 +2328,31 @@
escapedBy:[exportFieldsEscapedField stringValue]
lineEnds:[exportLinesTerminatedField stringValue]
withNumericColumns:tableColumnNumericStatus
+ totalRows:streamingResultCount
silently:YES];
}
// Add a spacer to the file
[fileHandle writeData:[[NSString stringWithFormat:@"%@%@%@", csvLineEnd, csvLineEnd, csvLineEnd] dataUsingEncoding:connectionEncoding]];
} else if ( [type isEqualToString:@"xml"] ) {
- [self writeXmlForArray:nil orQueryResult:queryResult
+ [self writeXmlForArray:nil orStreamingResult:streamingResult
toFileHandle:fileHandle
tableName:tableName
withHeader:NO
+ totalRows:streamingResultCount
silently:YES];
// Add a spacer to the file
[fileHandle writeData:[[NSString stringWithString:@"\n\n\n"] dataUsingEncoding:connectionEncoding]];
}
-
+
+ // Release the result set
+ [streamingResult release];
+
+ // Note any errors during data retrieval
+ if ( ![[mySQLConnection getLastErrorMessage] isEqualToString:@""] ) {
+ [errors appendString:[NSString stringWithFormat:@"%@\n", [mySQLConnection getLastErrorMessage]]];
+ }
}
// For XML output, close the database tag
' href='#n1687'>1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607