aboutsummaryrefslogtreecommitdiffstats
path: root/Source
diff options
context:
space:
mode:
authorrowanbeentje <rowan@beent.je>2009-03-19 23:44:06 +0000
committerrowanbeentje <rowan@beent.je>2009-03-19 23:44:06 +0000
commitddf7d62d20614111acdd420075ef762d6deaa8d7 (patch)
treecf5ce70dde9c25d1b21da1cded5cee9f3e562704 /Source
parent4a8d0f731bbb03b9ace041d421800e5c6470326a (diff)
downloadsequelpro-ddf7d62d20614111acdd420075ef762d6deaa8d7.tar.gz
sequelpro-ddf7d62d20614111acdd420075ef762d6deaa8d7.tar.bz2
sequelpro-ddf7d62d20614111acdd420075ef762d6deaa8d7.zip
SPSQLParser changes:
- Use method caches for oft-called functions, and support caching of chunks of the underlying string for string walking, resulting in an overall 1.3x-1.4x parsing speedup. - Improve handling of multi-character comment starts (eg / or -) at the very end of strings - When running splitString... methods return even empty strings for consistency. - Update TableDump and TableData to match new usage SPStringAddition changes: - Add a formatter for time intervals. CMMCPConnection changes: - Add support for timing queries CustomQuery and nib changes: - Change the "Run Queries" button to "Run All". - Add a "Run Current" button, which runs the query the text caret is currently positioned inside; if text is actually selected, this changes to "Run Selection". This addresses Issue #43. - Amend the "rows affected" string to better reflect the actual number of rows altered by several queries, show the query count if > 1, and display the overall execution time of the queries. This addresses Issue #142. - No longer execute blank strings as part of the custom query, preventing errors.
Diffstat (limited to 'Source')
-rw-r--r--Source/CMMCPConnection.h2
-rw-r--r--Source/CMMCPConnection.m22
-rw-r--r--Source/CustomQuery.h9
-rw-r--r--Source/CustomQuery.m505
-rw-r--r--Source/SPSQLParser.h18
-rw-r--r--Source/SPSQLParser.m116
-rw-r--r--Source/SPStringAdditions.h1
-rw-r--r--Source/SPStringAdditions.m45
-rw-r--r--Source/SPTableData.m52
-rw-r--r--Source/TableDump.m5
10 files changed, 574 insertions, 201 deletions
diff --git a/Source/CMMCPConnection.h b/Source/CMMCPConnection.h
index e6479eb1..b26319ee 100644
--- a/Source/CMMCPConnection.h
+++ b/Source/CMMCPConnection.h
@@ -49,6 +49,7 @@
NSString *connectionHost;
int connectionPort;
NSString *connectionSocket;
+ float lastQueryExecutionTime;
NSTimer *keepAliveTimer;
NSDate *lastKeepAliveSuccess;
@@ -66,6 +67,7 @@
- (void) setParentWindow:(NSWindow *)theWindow;
- (BOOL) selectDB:(NSString *) dbName;
- (CMMCPResult *) queryString:(NSString *) query;
+- (float) lastQueryExecutionTime;
- (MCPResult *) listDBsLike:(NSString *) dbsName;
- (BOOL) checkConnection;
- (void) setDelegate:(id)object;
diff --git a/Source/CMMCPConnection.m b/Source/CMMCPConnection.m
index 109ab280..64315ff6 100644
--- a/Source/CMMCPConnection.m
+++ b/Source/CMMCPConnection.m
@@ -68,6 +68,7 @@ static void forcePingTimeout(int signalNumber);
connectionSocket = nil;
keepAliveTimer = nil;
lastKeepAliveSuccess = nil;
+ lastQueryExecutionTime = 0;
if (![NSBundle loadNibNamed:@"ConnectionErrorDialog" owner:self]) {
NSLog(@"Connection error dialog could not be loaded; connection failure handling will not function correctly.");
}
@@ -345,6 +346,7 @@ static void forcePingTimeout(int signalNumber);
CMMCPResult *theResult;
const char *theCQuery = [self cStringFromString:query];
int theQueryCode;
+ NSDate *queryStartDate;
// If no connection is present, return nil.
if (!mConnected) return nil;
@@ -360,10 +362,16 @@ static void forcePingTimeout(int signalNumber);
[delegate willQueryString:query];
}
- if (0 == (theQueryCode = mysql_query(mConnection, theCQuery))) {
+ // Run the query, storing run time (note this will include some network and overhead)
+ queryStartDate = [NSDate date];
+ theQueryCode = mysql_query(mConnection, theCQuery);
+ lastQueryExecutionTime = [[NSDate date] timeIntervalSinceDate:queryStartDate];
+
+ // Retrieve the result or error appropriately.
+ if (0 == theQueryCode) {
if (mysql_field_count(mConnection) != 0) {
- // Use CMMCPResult instad of MCPResult
+ // Use CMMCPResult instead of MCPResult
theResult = [[CMMCPResult alloc] initWithMySQLPtr:mConnection encoding:mEncoding timeZone:mTimeZone];
} else {
return nil;
@@ -385,6 +393,16 @@ static void forcePingTimeout(int signalNumber);
/*
+ * Return the time taken to execute the last query. This should be close to the time it took
+ * the server to run the query, but will include network lag and some client library overhead.
+ */
+- (float) lastQueryExecutionTime
+{
+ return lastQueryExecutionTime;
+}
+
+
+/*
* Modified version of selectDB to be used in Sequel Pro.
* Checks the connection exists, and handles keepalive, otherwise calling the parent implementation.
*/
diff --git a/Source/CustomQuery.h b/Source/CustomQuery.h
index 8e81c7e5..c3a61b56 100644
--- a/Source/CustomQuery.h
+++ b/Source/CustomQuery.h
@@ -43,6 +43,8 @@
IBOutlet id queryFavoritesView;
IBOutlet id removeQueryFavoriteButton;
IBOutlet id copyQueryFavoriteButton;
+ IBOutlet id runSelectionButton;
+ IBOutlet id runAllButton;
NSArray *queryResult;
NSUserDefaults *prefs;
@@ -52,7 +54,8 @@
}
// IBAction methods
-- (IBAction)performQuery:(id)sender;
+- (IBAction)runAllQueries:(id)sender;
+- (IBAction)runSelectedQueries:(id)sender;
- (IBAction)chooseQueryFavorite:(id)sender;
- (IBAction)chooseQueryHistory:(id)sender;
- (IBAction)closeSheet:(id)sender;
@@ -63,6 +66,10 @@
- (IBAction)copyQueryFavorite:(id)sender;
- (IBAction)closeQueryFavoritesSheet:(id)sender;
+// Query actions
+- (void)performQueries:(NSArray *)queries;
+- (NSString *)queryAtPosition:(long)position;
+
// Accessors
- (NSArray *)currentResult;
diff --git a/Source/CustomQuery.m b/Source/CustomQuery.m
index e917e984..94ec6cba 100644
--- a/Source/CustomQuery.m
+++ b/Source/CustomQuery.m
@@ -25,177 +25,77 @@
#import "CustomQuery.h"
#import "SPSQLParser.h"
#import "SPGrowlController.h"
+#import "SPStringAdditions.h"
+
@implementation CustomQuery
-//IBAction methods
-- (IBAction)performQuery:(id)sender;
+
+
+#pragma mark IBAction methods
+
+
/*
-performs the mysql-query given by the user
-sets the tableView columns corresponding to the mysql-result
-*/
-{
+ * Split all the queries in the text view, split them into individual queries,
+ * and run sequentially.
+ */
+- (IBAction)runAllQueries:(id)sender
+{
+ SPSQLParser *queryParser;
+ NSArray *queries;
+
// Fixes bug in key equivalents.
- if ([[NSApp currentEvent] type] == NSKeyUp)
- {
+ if ([[NSApp currentEvent] type] == NSKeyUp) {
return;
}
-
- NSArray *theColumns;
- NSTableColumn *theCol;
- CMMCPResult *theResult = nil;
- NSArray *queries;
- NSMutableArray *menuItems = [NSMutableArray array];
- NSMutableArray *tempResult = [NSMutableArray array];
- NSMutableString *errors = [NSMutableString string];
- SPSQLParser *queryParser;
- int i;
-
- // Notify listeners that a query has started
- [[NSNotificationCenter defaultCenter] postNotificationName:@"SMySQLQueryWillBePerformed" object:self];
// Retrieve the custom query string and split it into separate SQL queries
queryParser = [[SPSQLParser alloc] initWithString:[textView string]];
queries = [queryParser splitStringByCharacter:';'];
[queryParser release];
- // Perform the queries in series
- for ( i = 0 ; i < [queries count] ; i++ ) {
- theResult = [mySQLConnection queryString:[queries objectAtIndex:i]];
- if ( ![[mySQLConnection getLastErrorMessage] isEqualToString:@""] ) {
-
- // If the query errored, append error to the error log for display at the end
- if ( [queries count] > 1 ) {
- [errors appendString:[NSString stringWithFormat:NSLocalizedString(@"[ERROR in query %d] %@\n", @"error text when multiple custom query failed"),
- i+1,
- [mySQLConnection getLastErrorMessage]]];
- } else {
- [errors setString:[mySQLConnection getLastErrorMessage]];
- }
- }
- }
-
- //perform empty query if no query is given
- if ( [queries count] == 0 ) {
- theResult = [mySQLConnection queryString:@""];
- [errors setString:[mySQLConnection getLastErrorMessage]];
- }
-
-//put result in array
- [queryResult release];
- queryResult = nil;
- if ( nil != theResult )
- {
- int r = [theResult numOfRows];
- if (r) [theResult dataSeek:0];
- for ( i = 0 ; i < r ; i++ ) {
- [tempResult addObject:[theResult fetchRowAsArray]];
- }
- queryResult = [[NSArray arrayWithArray:tempResult] retain];
- }
-
-//add query to history
- [queryHistoryButton insertItemWithTitle:[textView string] atIndex:1];
- while ( [queryHistoryButton numberOfItems] > 21 ) {
- [queryHistoryButton removeItemAtIndex:[queryHistoryButton numberOfItems]-1];
- }
- for ( i = 1 ; i < [queryHistoryButton numberOfItems] ; i++ )
- {
- [menuItems addObject:[queryHistoryButton itemTitleAtIndex:i]];
- }
- [prefs setObject:menuItems forKey:@"queryHistory"];
+ [self performQueries:queries];
-//select the text of the query textView and set standard font
+ // Select the text of the query textView for re-editing and set standard font
[textView selectAll:self];
- if ( [errors length] ) {
- [errorText setStringValue:errors];
- } else {
- [errorText setStringValue:NSLocalizedString(@"There were no errors.", @"text shown when query was successfull")];
- }
- if ( [mySQLConnection affectedRows] != -1 ) {
- [affectedRowsText setStringValue:[NSString stringWithFormat:NSLocalizedString(@"%@ row(s) affected", @"text showing how many rows have been affected"),
- [[NSNumber numberWithLongLong:[mySQLConnection affectedRows]] stringValue]]];
- } else {
- [affectedRowsText setStringValue:@""];
- }
if ( [prefs boolForKey:@"useMonospacedFonts"] ) {
[textView setFont:[NSFont fontWithName:@"Monaco" size:[NSFont smallSystemFontSize]]];
} else {
[textView setFont:[NSFont systemFontOfSize:[NSFont smallSystemFontSize]]];
}
+}
- if ( !theResult || ![theResult numOfRows] ) {
-//no rows in result
- //free tableView
- theColumns = [customQueryView tableColumns];
- while ([theColumns count]) {
- [customQueryView removeTableColumn:[theColumns objectAtIndex:0]];
- }
-// theCol = [[NSTableColumn alloc] initWithIdentifier:@""];
-// [[theCol headerCell] setStringValue:@""];
-// [customQueryView addTableColumn:theCol];
-// [customQueryView sizeLastColumnToFit];
- [customQueryView reloadData];
-// [theCol release];
-
- //query finished
- [[NSNotificationCenter defaultCenter] postNotificationName:@"SMySQLQueryHasBeenPerformed" object:self];
-
- // Query finished Growl notification
- [[SPGrowlController sharedGrowlController] notifyWithTitle:@"Query Finished"
- description:[NSString stringWithFormat:NSLocalizedString(@"%@",@"description for query finished growl notification"), [errorText stringValue]]
- notificationName:@"Query Finished"];
-
- return;
- }
-
-//set columns
-//remove all columns
- theColumns = [customQueryView tableColumns];
-// i=0;
- while ([theColumns count]) {
- [customQueryView removeTableColumn:[theColumns objectAtIndex:0]];
-// i++;
- }
+/*
+ * Depending on selection, run either the query containing the selection caret (if the caret is
+ * at a single point within the text view), or run the selected text (if a text range is selected).
+ */
+- (IBAction)runSelectedQueries:(id)sender
+{
+ NSArray *queries;
+ NSString *query;
+ NSRange selectedRange = [textView selectedRange];
+ SPSQLParser *queryParser;
-//add columns, corresponding to the query result
- theColumns = [theResult fetchFieldNames];
- for ( i = 0 ; i < [theResult numOfFields] ; i++) {
- theCol = [[NSTableColumn alloc] initWithIdentifier:[NSNumber numberWithInt:i]];
- [theCol setResizingMask:NSTableColumnUserResizingMask];
- NSTextFieldCell *dataCell = [[[NSTextFieldCell alloc] initTextCell:@""] autorelease];
- [dataCell setEditable:NO];
- if ( [prefs boolForKey:@"useMonospacedFonts"] ) {
- [dataCell setFont:[NSFont fontWithName:@"Monaco" size:10]];
- } else {
- [dataCell setFont:[NSFont systemFontOfSize:[NSFont smallSystemFontSize]]];
+ // If the current selection is a single caret position, run the current query.
+ if (selectedRange.length == 0) {
+ query = [self queryAtPosition:selectedRange.location];
+ if (!query) {
+ NSBeep();
+ return;
}
- [dataCell setLineBreakMode:NSLineBreakByTruncatingTail];
- [theCol setDataCell:dataCell];
- [[theCol headerCell] setStringValue:[theColumns objectAtIndex:i]];
+ queries = [NSArray arrayWithObject:query];
- [customQueryView addTableColumn:theCol];
- [theCol release];
+ // Otherwise, run the selected text.
+ } else {
+ queryParser = [[SPSQLParser alloc] initWithString:[[textView string] substringWithRange:selectedRange]];
+ queries = [queryParser splitStringByCharacter:';'];
+ [queryParser release];
}
- [customQueryView sizeLastColumnToFit];
- //tries to fix problem with last row (otherwise to small)
- //sets last column to width of the first if smaller than 30
- //problem not fixed for resizing window
- if ( [[customQueryView tableColumnWithIdentifier:[NSNumber numberWithInt:[theColumns count]-1]] width] < 30 )
- [[customQueryView tableColumnWithIdentifier:[NSNumber numberWithInt:[theColumns count]-1]]
- setWidth:[[customQueryView tableColumnWithIdentifier:[NSNumber numberWithInt:0]] width]];
- [customQueryView reloadData];
-
- //query finished
- [[NSNotificationCenter defaultCenter] postNotificationName:@"SMySQLQueryHasBeenPerformed" object:self];
-
- // Query finished Growl notification
- [[SPGrowlController sharedGrowlController] notifyWithTitle:@"Query Finished"
- description:[NSString stringWithFormat:NSLocalizedString(@"%@",@"description for query finished growl notification"), [errorText stringValue]]
- notificationName:@"Query Finished"];
+ [self performQueries:queries];
}
+
- (IBAction)chooseQueryFavorite:(id)sender
/*
insert the choosen favorite query in the query textView or save query to favorites or opens window to edit favorites
@@ -255,7 +155,10 @@ closes the sheet
}
-//queryFavoritesSheet methods
+#pragma mark -
+#pragma mark queryFavoritesSheet methods
+
+
- (IBAction)addQueryFavorite:(id)sender
/*
adds a query favorite
@@ -352,7 +255,229 @@ closes queryFavoritesSheet and saves favorites to preferences
}
-//getter methods
+#pragma mark -
+#pragma mark Query actions
+
+
+- (void)performQueries:(NSArray *)queries;
+/*
+performs the mysql-query given by the user
+sets the tableView columns corresponding to the mysql-result
+*/
+{
+
+ NSArray *theColumns;
+ NSTableColumn *theCol;
+ CMMCPResult *theResult = nil;
+ NSMutableArray *menuItems = [NSMutableArray array];
+ NSMutableArray *tempResult = [NSMutableArray array];
+ NSMutableString *errors = [NSMutableString string];
+ int i, totalQueriesRun = 0, totalAffectedRows = 0;
+ float executionTime = 0;
+
+ // Notify listeners that a query has started
+ [[NSNotificationCenter defaultCenter] postNotificationName:@"SMySQLQueryWillBePerformed" object:self];
+
+ // Perform the supplied queries in series
+ for ( i = 0 ; i < [queries count] ; i++ ) {
+
+ // Don't run blank queries, or queries which only contain whitespace.
+ if ([[[queries objectAtIndex:i] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length] == 0)
+ continue;
+
+ // Run the query, timing execution (note this also includes network and overhead)
+ theResult = [mySQLConnection queryString:[queries objectAtIndex:i]];
+ executionTime += [mySQLConnection lastQueryExecutionTime];
+ totalQueriesRun++;
+
+ // Record any affected rows
+ if ( [mySQLConnection affectedRows] != -1 )
+ totalAffectedRows += [mySQLConnection affectedRows];
+
+ // Store any error messages
+ if ( ![[mySQLConnection getLastErrorMessage] isEqualToString:@""] ) {
+
+ // If the query errored, append error to the error log for display at the end
+ if ( [queries count] > 1 ) {
+ [errors appendString:[NSString stringWithFormat:NSLocalizedString(@"[ERROR in query %d] %@\n", @"error text when multiple custom query failed"),
+ i+1,
+ [mySQLConnection getLastErrorMessage]]];
+ } else {
+ [errors setString:[mySQLConnection getLastErrorMessage]];
+ }
+ }
+ }
+
+ //perform empty query if no query is given
+ if ( [queries count] == 0 ) {
+ theResult = [mySQLConnection queryString:@""];
+ [errors setString:[mySQLConnection getLastErrorMessage]];
+ }
+
+//put result in array
+ [queryResult release];
+ queryResult = nil;
+ if ( nil != theResult )
+ {
+ int r = [theResult numOfRows];
+ if (r) [theResult dataSeek:0];
+ for ( i = 0 ; i < r ; i++ ) {
+ [tempResult addObject:[theResult fetchRowAsArray]];
+ }
+ queryResult = [[NSArray arrayWithArray:tempResult] retain];
+ }
+
+//add query to history
+ [queryHistoryButton insertItemWithTitle:[queries componentsJoinedByString:@"; "] atIndex:1];
+ while ( [queryHistoryButton numberOfItems] > 21 ) {
+ [queryHistoryButton removeItemAtIndex:[queryHistoryButton numberOfItems]-1];
+ }
+ for ( i = 1 ; i < [queryHistoryButton numberOfItems] ; i++ )
+ {
+ [menuItems addObject:[queryHistoryButton itemTitleAtIndex:i]];
+ }
+ [prefs setObject:menuItems forKey:@"queryHistory"];
+
+ if ( [errors length] ) {
+ [errorText setStringValue:errors];
+ } else {
+ [errorText setStringValue:NSLocalizedString(@"There were no errors.", @"text shown when query was successfull")];
+ }
+
+ // Set up the status string
+ if ( totalQueriesRun > 1 ) {
+ [affectedRowsText setStringValue:[NSString stringWithFormat:NSLocalizedString(@"%i total row(s) affected, by %i queries taking %@", @"text showing how many rows have been affected by multiple queries"),
+ totalAffectedRows,
+ totalQueriesRun,
+ [NSString stringForTimeInterval:executionTime]
+ ]];
+ } else {
+ [affectedRowsText setStringValue:[NSString stringWithFormat:NSLocalizedString(@"%i row(s) affected, taking %@", @"text showing how many rows have been affected by a single query"),
+ totalAffectedRows,
+ [NSString stringForTimeInterval:executionTime]
+ ]];
+ }
+
+ if ( !theResult || ![theResult numOfRows] ) {
+//no rows in result
+ //free tableView
+ theColumns = [customQueryView tableColumns];
+ while ([theColumns count]) {
+ [customQueryView removeTableColumn:[theColumns objectAtIndex:0]];
+ }
+// theCol = [[NSTableColumn alloc] initWithIdentifier:@""];
+// [[theCol headerCell] setStringValue:@""];
+// [customQueryView addTableColumn:theCol];
+// [customQueryView sizeLastColumnToFit];
+ [customQueryView reloadData];
+// [theCol release];
+
+ //query finished
+ [[NSNotificationCenter defaultCenter] postNotificationName:@"SMySQLQueryHasBeenPerformed" object:self];
+
+ // Query finished Growl notification
+ [[SPGrowlController sharedGrowlController] notifyWithTitle:@"Query Finished"
+ description:[NSString stringWithFormat:NSLocalizedString(@"%@",@"description for query finished growl notification"), [errorText stringValue]]
+ notificationName:@"Query Finished"];
+
+ return;
+ }
+
+//set columns
+//remove all columns
+ theColumns = [customQueryView tableColumns];
+// i=0;
+ while ([theColumns count]) {
+ [customQueryView removeTableColumn:[theColumns objectAtIndex:0]];
+// i++;
+ }
+
+//add columns, corresponding to the query result
+ theColumns = [theResult fetchFieldNames];
+ for ( i = 0 ; i < [theResult numOfFields] ; i++) {
+ theCol = [[NSTableColumn alloc] initWithIdentifier:[NSNumber numberWithInt:i]];
+ [theCol setResizingMask:NSTableColumnUserResizingMask];
+ NSTextFieldCell *dataCell = [[[NSTextFieldCell alloc] initTextCell:@""] autorelease];
+ [dataCell setEditable:NO];
+ if ( [prefs boolForKey:@"useMonospacedFonts"] ) {
+ [dataCell setFont:[NSFont fontWithName:@"Monaco" size:10]];
+ } else {
+ [dataCell setFont:[NSFont systemFontOfSize:[NSFont smallSystemFontSize]]];
+ }
+ [dataCell setLineBreakMode:NSLineBreakByTruncatingTail];
+ [theCol setDataCell:dataCell];
+ [[theCol headerCell] setStringValue:[theColumns objectAtIndex:i]];
+
+ [customQueryView addTableColumn:theCol];
+ [theCol release];
+ }
+
+ [customQueryView sizeLastColumnToFit];
+ //tries to fix problem with last row (otherwise to small)
+ //sets last column to width of the first if smaller than 30
+ //problem not fixed for resizing window
+ if ( [[customQueryView tableColumnWithIdentifier:[NSNumber numberWithInt:[theColumns count]-1]] width] < 30 )
+ [[customQueryView tableColumnWithIdentifier:[NSNumber numberWithInt:[theColumns count]-1]]
+ setWidth:[[customQueryView tableColumnWithIdentifier:[NSNumber numberWithInt:0]] width]];
+ [customQueryView reloadData];
+
+ //query finished
+ [[NSNotificationCenter defaultCenter] postNotificationName:@"SMySQLQueryHasBeenPerformed" object:self];
+
+ // Query finished Growl notification
+ [[SPGrowlController sharedGrowlController] notifyWithTitle:@"Query Finished"
+ description:[NSString stringWithFormat:NSLocalizedString(@"%@",@"description for query finished growl notification"), [errorText stringValue]]
+ notificationName:@"Query Finished"];
+}
+
+/*
+ * Retrieve the query at a position specified within the custom query
+ * text view. This will return nil if the position specified is beyond
+ * the available string or if an empty query would be returned.
+ */
+- (NSString *)queryAtPosition:(long)position
+{
+ SPSQLParser *customQueryParser;
+ NSArray *queries;
+ NSString *query = nil;
+ int i, queryPosition = 0;
+
+ // If the supplied position is negative or beyond the end of the string, return nil.
+ if (position < 0 || position > [[textView string] length])
+ return nil;
+
+ // Split the current text into queries
+ customQueryParser = [[SPSQLParser alloc] initWithString:[textView string]];
+ queries = [[NSArray alloc] initWithArray:[customQueryParser splitStringByCharacter:';']];
+ [customQueryParser release];
+
+ // Walk along the array of queries to identify the current query - taking into account
+ // the extra semicolon at the end of each query
+ for (i = 0; i < [queries count]; i++ ) {
+ queryPosition += [[queries objectAtIndex:i] length];
+ if (queryPosition >= position) {
+ query = [NSString stringWithString:[queries objectAtIndex:i]];
+ break;
+ }
+ queryPosition++;
+ }
+
+ [queries release];
+
+ // Ensure the string isn't empty.
+ // (We could also strip comments for this check, but that prevents use of conditional comments)
+ if ([[query stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length] == 0)
+ return nil;
+
+ // Return the located string.
+ return query;
+}
+
+
+#pragma mark -
+#pragma mark Accessors
+
+
- (NSArray *)currentResult
/*
returns the current result (as shown in custom result view) as array, the first object containing the field names as array, the following objects containing the rows as array
@@ -384,7 +509,10 @@ returns the current result (as shown in custom result view) as array, the first
}
-//additional methods
+#pragma mark -
+#pragma mark Additional methods
+
+
- (void)setConnection:(CMMCPConnection *)theConnection
/*
sets the connection (received from TableDocument) and makes things that have to be done only once
@@ -447,11 +575,14 @@ inserts the query in the textView and performs query
*/
{
[textView setString:query];
- [self performQuery:self];
+ [self runAllQueries:self];
}
-//tableView datasource methods
+#pragma mark -
+#pragma mark TableView datasource methods
+
+
- (int)numberOfRowsInTableView:(NSTableView *)aTableView
{
if ( aTableView == customQueryView ) {
@@ -668,7 +799,10 @@ opens sheet with value when double clicking on a field
}
-//splitView delegate methods
+#pragma mark -
+#pragma mark SplitView delegate methods
+
+
- (BOOL)splitView:(NSSplitView *)sender canCollapseSubview:(NSView *)subview
/*
tells the splitView that it can collapse views
@@ -702,7 +836,10 @@ defines min position of splitView
}
-//textView delegate methods
+#pragma mark -
+#pragma mark TextView delegate methods
+
+
- (BOOL)textView:(NSTextView *)aTextView doCommandBySelector:(SEL)aSelector
/*
traps enter key and
@@ -714,7 +851,7 @@ traps enter key and
if ( [aTextView methodForSelector:aSelector] == [aTextView methodForSelector:@selector(insertNewline:)] &&
[[[NSApp currentEvent] characters] isEqualToString:@"\003"] )
{
- [self performQuery:self];
+ [self runAllQueries:self];
return YES;
} else {
return NO;
@@ -732,6 +869,68 @@ traps enter key and
}
/*
+ * A notification posted when the selection changes within the text view;
+ * used to control the run-currentrun-selection button state and action.
+ */
+- (void)textViewDidChangeSelection:(NSNotification *)aNotification
+{
+
+ // Ensure that the notification is from the custom query text view
+ if ( [aNotification object] != textView ) return;
+
+ // If no text is selected, disable the button.
+ if ( [textView selectedRange].location == NSNotFound ) {
+ [runSelectionButton setEnabled:NO];
+ return;
+ }
+
+ // If the current selection is a single caret position, update the button based on
+ // whether the caret is inside a valid query.
+ if ([textView selectedRange].length == 0) {
+ int selectionPosition = [textView selectedRange].location;
+ int movedRangeStart, movedRangeLength;
+ NSRange oldSelection;
+
+ // Retrieve the old selection position
+ [[[aNotification userInfo] objectForKey:@"NSOldSelectedCharacterRange"] getValue:&oldSelection];
+
+ // Only process the query text if the selection previously had length, or moved more than 100 characters,
+ // or the intervening space contained a semicolon, or typing has been performed with no current query.
+ // This adds more checks to every keypress, but ensures the majority of the actions don't incur a
+ // parsing overhead - which is cheap on small text strings but heavy of large queries.
+ movedRangeStart = (selectionPosition < oldSelection.location)?selectionPosition:oldSelection.location;
+ movedRangeLength = abs(selectionPosition - oldSelection.location);
+ if (oldSelection.length > 0
+ || movedRangeLength > 100
+ || oldSelection.location > [[textView string] length]
+ || [[textView string] rangeOfString:@";" options:0 range:NSMakeRange(movedRangeStart, movedRangeLength)].location != NSNotFound
+ || (![runSelectionButton isEnabled] && selectionPosition > oldSelection.location
+ && [[[[textView string] substringWithRange:NSMakeRange(movedRangeStart, movedRangeLength)] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length])
+ ) {
+
+ [runSelectionButton setTitle:NSLocalizedString(@"Run Current", @"Title of button to run current query in custom query view")];
+
+ // If a valid query is present at the cursor position, enable the button
+ if ([self queryAtPosition:selectionPosition]) {
+ [runSelectionButton setEnabled:YES];
+ } else {
+ [runSelectionButton setEnabled:NO];
+ }
+ }
+
+ // For selection ranges, enable the button.
+ } else {
+ [runSelectionButton setTitle:NSLocalizedString(@"Run Selection", @"Title of button to run selected text in custom query view")];
+ [runSelectionButton setEnabled:YES];
+ }
+}
+
+
+#pragma mark -
+#pragma mark TableView notifications
+
+
+/*
* Updates various interface elements based on the current table view selection.
*/
- (void)tableViewSelectionDidChange:(NSNotification *)notification
@@ -744,6 +943,10 @@ traps enter key and
}
}
+
+#pragma mark -
+
+
// Last but not least
- (id)init;
{
diff --git a/Source/SPSQLParser.h b/Source/SPSQLParser.h
index 14ac6f9d..3e68501c 100644
--- a/Source/SPSQLParser.h
+++ b/Source/SPSQLParser.h
@@ -23,6 +23,12 @@
#import <Cocoa/Cocoa.h>
+/*
+ * Define the length of the character cache to use when parsing instead of accessing
+ * via characterAtIndex:. There is a balance here between updating the cache very
+ * often and access penalties; 1500 appears a reasonable compromise.
+ */
+#define CHARACTER_CACHE_LENGTH 1500
/*
* This class provides a string class intended for SQL parsing. It extends NSMutableString,
@@ -53,6 +59,9 @@
@interface SPSQLParser : NSMutableString
{
id string;
+ unichar *stringCharCache;
+ long charCacheStart;
+ long charCacheEnd;
}
@@ -210,6 +219,15 @@ typedef enum _SPCommentTypes {
- (long) endIndexOfStringQuotedByCharacter:(unichar)quoteCharacter startingAtIndex:(long)index;
- (long) endIndexOfCommentOfType:(SPCommentType)commentType startingAtIndex:(long)index;
+/*
+ * Cacheing methods to enable a faster alternative to characterAtIndex: when walking strings, and overrides to update.
+ */
+- (unichar) charAtIndex:(long)index;
+- (void) clearCharCache;
+- (void) deleteCharactersInRange:(NSRange)aRange;
+- (void) insertString:(NSString *)aString atIndex:(NSUInteger)anIndex;
+
+
/* Required and primitive methods to allow subclassing class cluster */
#pragma mark -
diff --git a/Source/SPSQLParser.m b/Source/SPSQLParser.m
index 9828f529..e5c490da 100644
--- a/Source/SPSQLParser.m
+++ b/Source/SPSQLParser.m
@@ -60,11 +60,11 @@
case '-':
if (stringLength < currentStringIndex + 2) break;
if ([string characterAtIndex:currentStringIndex+1] != '-') break;
- if (![[NSCharacterSet whitespaceAndNewlineCharacterSet] characterIsMember:[string characterAtIndex:currentStringIndex+2]]) break;
+ if (![[NSCharacterSet whitespaceCharacterSet] characterIsMember:[string characterAtIndex:currentStringIndex+2]]) break;
commentEndIndex = [self endIndexOfCommentOfType:SPDoubleDashComment startingAtIndex:currentStringIndex];
// Remove the comment
- [string deleteCharactersInRange:NSMakeRange(currentStringIndex, commentEndIndex - currentStringIndex + 1)];
+ [self deleteCharactersInRange:NSMakeRange(currentStringIndex, commentEndIndex - currentStringIndex + 1)];
stringLength -= commentEndIndex - currentStringIndex + 1;
currentStringIndex--;
break;
@@ -73,7 +73,7 @@
commentEndIndex = [self endIndexOfCommentOfType:SPHashComment startingAtIndex:currentStringIndex];
// Remove the comment
- [string deleteCharactersInRange:NSMakeRange(currentStringIndex, commentEndIndex - currentStringIndex + 1)];
+ [self deleteCharactersInRange:NSMakeRange(currentStringIndex, commentEndIndex - currentStringIndex + 1)];
stringLength -= commentEndIndex - currentStringIndex + 1;
currentStringIndex--;
break;
@@ -85,7 +85,7 @@
commentEndIndex = [self endIndexOfCommentOfType:SPCStyleComment startingAtIndex:currentStringIndex];
// Remove the comment
- [string deleteCharactersInRange:NSMakeRange(currentStringIndex, commentEndIndex - currentStringIndex + 1)];
+ [self deleteCharactersInRange:NSMakeRange(currentStringIndex, commentEndIndex - currentStringIndex + 1)];
stringLength -= commentEndIndex - currentStringIndex + 1;
currentStringIndex--;
break;
@@ -158,7 +158,7 @@
if (stringIndex == NSNotFound) return NO;
// If it has been found, trim the string appropriately and return YES
- [string deleteCharactersInRange:NSMakeRange(0, stringIndex + (inclusive?1:0))];
+ [self deleteCharactersInRange:NSMakeRange(0, stringIndex + (inclusive?1:0))];
return YES;
}
@@ -213,7 +213,7 @@
// Select the appropriate string range, truncate the current string, and return the selected string
resultString = [NSString stringWithString:[string substringWithRange:NSMakeRange(0, stringIndex + (inclusiveReturn?1:0))]];
- [string deleteCharactersInRange:NSMakeRange(0, stringIndex + (inclusiveTrim?1:0))];
+ [self deleteCharactersInRange:NSMakeRange(0, stringIndex + (inclusiveTrim?1:0))];
return resultString;
}
@@ -255,7 +255,7 @@
- (NSString *) stringFromCharacter:(unichar)fromCharacter toCharacter:(unichar)toCharacter inclusively:(BOOL)inclusive skippingBrackets:(BOOL)skipBrackets ignoringQuotedStrings:(BOOL)ignoreQuotedStrings
{
long fromCharacterIndex, toCharacterIndex;
-
+
// Look for the first occurrence of the from: character
fromCharacterIndex = [self firstOccurrenceOfCharacter:fromCharacter afterIndex:-1 skippingBrackets:skipBrackets ignoringQuotedStrings:ignoreQuotedStrings];
if (fromCharacterIndex == NSNotFound) return nil;
@@ -318,7 +318,7 @@
// Select the correct part of the string, truncate the current string, and return the selected string.
resultString = [string substringWithRange:NSMakeRange(fromCharacterIndex + (inclusiveReturn?0:1), toCharacterIndex + (inclusiveReturn?1:-1) - fromCharacterIndex)];
- [string deleteCharactersInRange:NSMakeRange(fromCharacterIndex + (inclusiveTrim?0:1), toCharacterIndex + (inclusiveTrim?1:-1) - fromCharacterIndex)];
+ [self deleteCharactersInRange:NSMakeRange(fromCharacterIndex + (inclusiveTrim?0:1), toCharacterIndex + (inclusiveTrim?1:-1) - fromCharacterIndex)];
return resultString;
}
@@ -358,16 +358,14 @@
NSMutableArray *resultsArray = [NSMutableArray array];
long stringIndex = -1, nextIndex = 0;
- // Walk through the string finding the character to split by, and add non-zero length strings.
+ // Walk through the string finding the character to split by, and add all strings to the array.
while (1) {
nextIndex = [self firstOccurrenceOfCharacter:character afterIndex:stringIndex skippingBrackets:skipBrackets ignoringQuotedStrings:ignoreQuotedStrings];
if (nextIndex == NSNotFound) {
break;
}
- if (nextIndex - stringIndex - 1 > 0) {
- [resultsArray addObject:[string substringWithRange:NSMakeRange(stringIndex+1, nextIndex - stringIndex - 1)]];
- }
+ [resultsArray addObject:[string substringWithRange:NSMakeRange(stringIndex+1, nextIndex - stringIndex - 1)]];
stringIndex = nextIndex;
}
@@ -408,12 +406,16 @@
long stringLength = [string length];
int bracketingLevel = 0;
+ // Cache frequently used selectors, avoiding dynamic binding overhead
+ IMP charAtIndex = [self methodForSelector:@selector(charAtIndex:)];
+ IMP endIndex = [self methodForSelector:@selector(endIndexOfStringQuotedByCharacter:startingAtIndex:)];
+
// Sanity check inputs
if (startIndex < -1) startIndex = -1;
// Walk along the string, processing characters
for (currentStringIndex = startIndex + 1; currentStringIndex < stringLength; currentStringIndex++) {
- currentCharacter = [string characterAtIndex:currentStringIndex];
+ currentCharacter = (unichar)(long)(*charAtIndex)(self, @selector(charAtIndex:), currentStringIndex);
// Check for the ending character, and if it has been found and quoting/brackets is valid, return.
if (currentCharacter == character) {
@@ -430,7 +432,7 @@
case '"':
case '`':
if (!ignoreQuotedStrings) break;
- quotedStringEndIndex = [self endIndexOfStringQuotedByCharacter:currentCharacter startingAtIndex:currentStringIndex+1];
+ quotedStringEndIndex = (long)(*endIndex)(self, @selector(endIndexOfStringQuotedByCharacter:startingAtIndex:), currentCharacter, currentStringIndex+1);
if (quotedStringEndIndex == NSNotFound) {
return NSNotFound;
}
@@ -449,8 +451,8 @@
// For comments starting "--[\s]", ensure the start syntax is valid before proceeding.
case '-':
if (stringLength < currentStringIndex + 2) break;
- if ([string characterAtIndex:currentStringIndex+1] != '-') break;
- if (![[NSCharacterSet whitespaceAndNewlineCharacterSet] characterIsMember:[string characterAtIndex:currentStringIndex+2]]) break;
+ if ((unichar)(long)(*charAtIndex)(self, @selector(charAtIndex:), currentStringIndex+1) != '-') break;
+ if (![[NSCharacterSet whitespaceCharacterSet] characterIsMember:(unichar)(long)(*charAtIndex)(self, @selector(charAtIndex:), currentStringIndex+2)]) break;
currentStringIndex = [self endIndexOfCommentOfType:SPDoubleDashComment startingAtIndex:currentStringIndex];
break;
@@ -461,7 +463,7 @@
// For comments starting "/*", ensure the start syntax is valid before proceeding.
case '/':
if (stringLength < currentStringIndex + 1) break;
- if ([string characterAtIndex:currentStringIndex+1] != '*') break;
+ if ((unichar)(long)(*charAtIndex)(self, @selector(charAtIndex:), currentStringIndex+1) != '*') break;
currentStringIndex = [self endIndexOfCommentOfType:SPCStyleComment startingAtIndex:currentStringIndex];
break;
}
@@ -480,17 +482,20 @@
BOOL characterIsEscaped;
unichar currentCharacter;
+ // Cache the charAtIndex selector, avoiding dynamic binding overhead
+ IMP charAtIndex = [self methodForSelector:@selector(charAtIndex:)];
+
stringLength = [string length];
// Walk the string looking for the string end
for ( currentStringIndex = index; currentStringIndex < stringLength; currentStringIndex++) {
- currentCharacter = [string characterAtIndex:currentStringIndex];
+ currentCharacter = (unichar)(long)(*charAtIndex)(self, @selector(charAtIndex:), currentStringIndex);
// If the string end is a backtick and one has been encountered, treat it as end of string
if (quoteCharacter == '`' && currentCharacter == '`') {
// ...as long as the next character isn't also a backtick, in which case it's being quoted. Skip both.
- if ((currentStringIndex + 1) < stringLength && [string characterAtIndex:currentStringIndex+1] == '`') {
+ if ((currentStringIndex + 1) < stringLength && (unichar)(long)(*charAtIndex)(self, @selector(charAtIndex:), currentStringIndex+1) == '`') {
currentStringIndex++;
continue;
}
@@ -504,7 +509,7 @@
characterIsEscaped = NO;
i = 1;
quotedStringLength = currentStringIndex - 1;
- while ((quotedStringLength - i) > 0 && [string characterAtIndex:currentStringIndex - i] == '\\') {
+ while ((quotedStringLength - i) > 0 && (unichar)(long)(*charAtIndex)(self, @selector(charAtIndex:), currentStringIndex - i) == '\\') {
characterIsEscaped = !characterIsEscaped;
i++;
}
@@ -512,7 +517,7 @@
// If an even number have been found, it may be the end of the string - as long as the subsequent character
// isn't also the same character, in which case it's another form of escaping.
if (!characterIsEscaped) {
- if ((currentStringIndex + 1) < stringLength && [string characterAtIndex:currentStringIndex+1] == quoteCharacter) {
+ if ((currentStringIndex + 1) < stringLength && (unichar)(long)(*charAtIndex)(self, @selector(charAtIndex:), currentStringIndex+1) == quoteCharacter) {
currentStringIndex++;
continue;
}
@@ -534,6 +539,9 @@
long stringLength = [string length];
unichar currentCharacter;
+ // Cache the charAtIndex selector, avoiding dynamic binding overhead
+ IMP charAtIndex = [self methodForSelector:@selector(charAtIndex:)];
+
switch (commentType) {
// For comments of type "--[\s]", start the comment processing two characters in to match the start syntax,
@@ -545,7 +553,7 @@
case SPHashComment:
index++;
for ( ; index < stringLength; index++ ) {
- currentCharacter = [string characterAtIndex:index];
+ currentCharacter = (unichar)(long)(*charAtIndex)(self, @selector(charAtIndex:), index);
if (currentCharacter == '\r' || currentCharacter == '\n') {
return index-1;
}
@@ -557,8 +565,8 @@
case SPCStyleComment:
index = index+2;
for ( ; index < stringLength; index++ ) {
- if ([string characterAtIndex:index] == '*') {
- if ((stringLength > index + 1) && [string characterAtIndex:index+1] == '/') {
+ if ((unichar)(long)(*charAtIndex)(self, @selector(charAtIndex:), index) == '*') {
+ if ((stringLength > index + 1) && (unichar)(long)(*charAtIndex)(self, @selector(charAtIndex:), index+1) == '/') {
return (index+1);
}
}
@@ -569,6 +577,52 @@
return (stringLength-1);
}
+/*
+ * Provide a method to retrieve a character from the local cache.
+ * Does no bounds checking on the underlying string, and so is kept
+ * separate for characterAtIndex:.
+ */
+- (unichar) charAtIndex:(long)index
+{
+
+ // If the current cache doesn't include the current character, update it.
+ if (index > charCacheEnd || index < charCacheStart) {
+ if (charCacheEnd > -1) {
+ free(stringCharCache);
+ }
+ unsigned int remainingStringLength = [string length] - index;
+ unsigned int newcachelength = (CHARACTER_CACHE_LENGTH < remainingStringLength)?CHARACTER_CACHE_LENGTH:remainingStringLength;
+ stringCharCache = (unichar *)calloc(newcachelength, sizeof(unichar));
+ [string getCharacters:stringCharCache range:NSMakeRange(index, newcachelength)];
+ charCacheEnd = index + newcachelength - 1;
+ charCacheStart = index;
+ }
+ return stringCharCache[index - charCacheStart];
+}
+
+/*
+ * Provide a method to cleat the cache, and use it when updating the string.
+ */
+- (void) clearCharCache
+{
+ if (charCacheEnd > -1) {
+ free(stringCharCache);
+ }
+ charCacheEnd = -1;
+ charCacheStart = 0;
+}
+- (void) deleteCharactersInRange:(NSRange)aRange
+{
+ [super deleteCharactersInRange:aRange];
+ [self clearCharCache];
+}
+- (void) insertString:(NSString *)aString atIndex:(NSUInteger)anIndex
+{
+ [super insertString:aString atIndex:anIndex];
+ [self clearCharCache];
+}
+
+
/* Required and primitive methods to allow subclassing class cluster */
#pragma mark -
@@ -576,45 +630,53 @@
if (self = [super init]) {
string = [[NSMutableString string] retain];
}
+ charCacheEnd = -1;
return self;
}
- (id) initWithBytes:(const void *)bytes length:(unsigned int)length encoding:(NSStringEncoding)encoding {
if (self = [super init]) {
string = [[NSMutableString alloc] initWithBytes:bytes length:length encoding:encoding];
}
+ charCacheEnd = -1;
return self;
}
- (id) initWithBytesNoCopy:(void *)bytes length:(unsigned int)length encoding:(NSStringEncoding)encoding freeWhenDone:(BOOL)flag {
if (self = [super init]) {
string = [[NSMutableString alloc] initWithBytesNoCopy:bytes length:length encoding:encoding freeWhenDone:flag];
}
+ charCacheEnd = -1;
return self;
}
- (id) initWithCapacity:(unsigned int)capacity {
if (self = [super init]) {
string = [[NSMutableString stringWithCapacity:capacity] retain];
}
+ charCacheEnd = -1;
return self;
}
- (id) initWithCharactersNoCopy:(unichar *)characters length:(unsigned int)length freeWhenDone:(BOOL)flag {
if (self = [super init]) {
string = [[NSMutableString alloc] initWithCharactersNoCopy:characters length:length freeWhenDone:flag];
}
+ charCacheEnd = -1;
return self;
}
- (id) initWithContentsOfFile:(id)path {
+ charCacheEnd = -1;
return [self initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:NULL];
}
- (id) initWithContentsOfFile:(NSString *)path encoding:(NSStringEncoding)encoding error:(NSError **)error {
if (self = [super init]) {
string = [[NSMutableString alloc] initWithContentsOfFile:path encoding:encoding error:error];
}
+ charCacheEnd = -1;
return self;
}
- (id) initWithCString:(const char *)nullTerminatedCString encoding:(NSStringEncoding)encoding {
if (self = [super init]) {
string = [[NSMutableString alloc] initWithCString:nullTerminatedCString encoding:encoding];
}
+ charCacheEnd = -1;
return self;
}
- (id) initWithFormat:(NSString *)format, ... {
@@ -622,12 +684,14 @@
va_start(argList, format);
id str = [self initWithFormat:format arguments:argList];
va_end(argList);
+ charCacheEnd = -1;
return str;
}
- (id) initWithFormat:(NSString *)format arguments:(va_list)argList {
if (self = [super init]) {
string = [[NSMutableString alloc] initWithFormat:format arguments:argList];
}
+ charCacheEnd = -1;
return self;
}
- (unsigned int) length {
@@ -641,15 +705,19 @@
}
- (unsigned int) replaceOccurrencesOfString:(NSString *)target withString:(NSString *)replacement options:(unsigned)options range:(NSRange)searchRange {
return [string replaceOccurrencesOfString:target withString:replacement options:options range:searchRange];
+ [self clearCharCache];
}
- (void) setString:(NSString *)aString {
[string setString:aString];
+ [self clearCharCache];
}
- (void) replaceCharactersInRange:(NSRange)range withString:(NSString *)aString {
[string replaceCharactersInRange:range withString:aString];
+ [self clearCharCache];
}
- (void) dealloc {
[string release];
+ if (charCacheEnd != -1) free(stringCharCache);
[super dealloc];
}
@end \ No newline at end of file
diff --git a/Source/SPStringAdditions.h b/Source/SPStringAdditions.h
index 4acd748c..0a323cf3 100644
--- a/Source/SPStringAdditions.h
+++ b/Source/SPStringAdditions.h
@@ -25,6 +25,7 @@
@interface NSString (SPStringAdditions)
+ (NSString *)stringForByteSize:(int)byteSize;
++ (NSString *)stringForTimeInterval:(float)timeInterval;
#if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
- (NSArray *)componentsSeparatedByCharactersInSet:(NSCharacterSet *)set;
diff --git a/Source/SPStringAdditions.m b/Source/SPStringAdditions.m
index 2916611d..ad6972ce 100644
--- a/Source/SPStringAdditions.m
+++ b/Source/SPStringAdditions.m
@@ -66,6 +66,51 @@
return [numberFormatter stringFromNumber:[NSNumber numberWithFloat:size]];
}
+
+// -------------------------------------------------------------------------------
+// stringForTimeInterval:
+//
+// Returns a human readable version string of the supplied time interval.
+// -------------------------------------------------------------------------------
++ (NSString *)stringForTimeInterval:(float)timeInterval
+{
+ NSNumberFormatter *numberFormatter = [[[NSNumberFormatter alloc] init] autorelease];
+
+ [numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
+
+ if (timeInterval < 1) {
+ timeInterval = (timeInterval * 1000);
+ [numberFormatter setFormat:@"#,##0 ms"];
+
+ return [numberFormatter stringFromNumber:[NSNumber numberWithFloat:timeInterval]];
+ }
+
+ if (timeInterval < 100) {
+ [numberFormatter setFormat:@"#,##0.0 s"];
+
+ return [numberFormatter stringFromNumber:[NSNumber numberWithFloat:timeInterval]];
+ }
+
+ if (timeInterval < 300) {
+ [numberFormatter setFormat:@"#,##0 s"];
+
+ return [numberFormatter stringFromNumber:[NSNumber numberWithFloat:timeInterval]];
+ }
+
+ if (timeInterval < 3600) {
+ timeInterval = (timeInterval / 60);
+ [numberFormatter setFormat:@"#,##0 min"];
+
+ return [numberFormatter stringFromNumber:[NSNumber numberWithFloat:timeInterval]];
+ }
+
+ timeInterval = (timeInterval / 3600);
+ [numberFormatter setFormat:@"#,##0 hours"];
+
+ return [numberFormatter stringFromNumber:[NSNumber numberWithFloat:timeInterval]];
+}
+
+
#if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
// -------------------------------------------------------------------------------
// componentsSeparatedByCharactersInSet:
diff --git a/Source/SPTableData.m b/Source/SPTableData.m
index 905a8ec5..1391e355 100644
--- a/Source/SPTableData.m
+++ b/Source/SPTableData.m
@@ -508,12 +508,18 @@
NSMutableDictionary *fieldDetails = [[NSMutableDictionary alloc] init];
NSMutableArray *detailParts;
NSString *detailString;
- int i, partsArrayLength;
+ int i, definitionPartsIndex = 0, partsArrayLength;
if (![definitionParts count]) return [NSDictionary dictionary];
+ // Skip blank items within the definition parts
+ while (definitionPartsIndex < [definitionParts count]
+ && ![[[definitionParts objectAtIndex:definitionPartsIndex] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length])
+ definitionPartsIndex++;
+
// The first item is always the data type.
- [fieldParser setString:[definitionParts objectAtIndex:0]];
+ [fieldParser setString:[definitionParts objectAtIndex:definitionPartsIndex]];
+ definitionPartsIndex++;
// If no field length definition is present, store only the type
if ([fieldParser firstOccurrenceOfCharacter:'(' ignoringQuotedStrings:YES] == NSNotFound) {
@@ -595,8 +601,8 @@
// Walk through the remaining column definition parts storing recognised details
partsArrayLength = [definitionParts count];
- for (i = 1; i < partsArrayLength; i++) {
- detailString = [[NSString alloc] initWithString:[[definitionParts objectAtIndex:i] uppercaseString]];
+ for ( ; definitionPartsIndex < partsArrayLength; definitionPartsIndex++) {
+ detailString = [[NSString alloc] initWithString:[[definitionParts objectAtIndex:definitionPartsIndex] uppercaseString]];
// Whether numeric fields are unsigned
if ([detailString isEqualToString:@"UNSIGNED"]) {
@@ -611,30 +617,30 @@
[fieldDetails setValue:[NSNumber numberWithBool:YES] forKey:@"binary"];
// Whether text types have a different encoding to the table
- } else if ([detailString isEqualToString:@"CHARSET"] && (i + 1 < partsArrayLength)) {
- if (![[[definitionParts objectAtIndex:i+1] uppercaseString] isEqualToString:@"DEFAULT"]) {
- [fieldDetails setValue:[definitionParts objectAtIndex:i+1] forKey:@"encoding"];
+ } else if ([detailString isEqualToString:@"CHARSET"] && (definitionPartsIndex + 1 < partsArrayLength)) {
+ if (![[[definitionParts objectAtIndex:definitionPartsIndex+1] uppercaseString] isEqualToString:@"DEFAULT"]) {
+ [fieldDetails setValue:[definitionParts objectAtIndex:definitionPartsIndex+1] forKey:@"encoding"];
}
- i++;
- } else if ([detailString isEqualToString:@"CHARACTER"] && (i + 2 < partsArrayLength)
- && [[[definitionParts objectAtIndex:i+1] uppercaseString] isEqualToString:@"SET"]) {
- if (![[[definitionParts objectAtIndex:i+2] uppercaseString] isEqualToString:@"DEFAULT"]) {;
- [fieldDetails setValue:[definitionParts objectAtIndex:i+2] forKey:@"encoding"];
+ definitionPartsIndex++;
+ } else if ([detailString isEqualToString:@"CHARACTER"] && (definitionPartsIndex + 2 < partsArrayLength)
+ && [[[definitionParts objectAtIndex:definitionPartsIndex+1] uppercaseString] isEqualToString:@"SET"]) {
+ if (![[[definitionParts objectAtIndex:definitionPartsIndex+2] uppercaseString] isEqualToString:@"DEFAULT"]) {;
+ [fieldDetails setValue:[definitionParts objectAtIndex:definitionPartsIndex+2] forKey:@"encoding"];
}
- i = i + 2;
+ definitionPartsIndex += 2;
// Whether text types have a different collation to the table
- } else if ([detailString isEqualToString:@"COLLATE"] && (i + 1 < partsArrayLength)) {
- if (![[[definitionParts objectAtIndex:i+1] uppercaseString] isEqualToString:@"DEFAULT"]) {
- [fieldDetails setValue:[definitionParts objectAtIndex:i+1] forKey:@"collation"];
+ } else if ([detailString isEqualToString:@"COLLATE"] && (definitionPartsIndex + 1 < partsArrayLength)) {
+ if (![[[definitionParts objectAtIndex:definitionPartsIndex+1] uppercaseString] isEqualToString:@"DEFAULT"]) {
+ [fieldDetails setValue:[definitionParts objectAtIndex:definitionPartsIndex+1] forKey:@"collation"];
}
- i++;
+ definitionPartsIndex++;
// Whether fields are NOT NULL
- } else if ([detailString isEqualToString:@"NOT"] && (i + 1 < partsArrayLength)
- && [[[definitionParts objectAtIndex:i+1] uppercaseString] isEqualToString:@"NULL"]) {
+ } else if ([detailString isEqualToString:@"NOT"] && (definitionPartsIndex + 1 < partsArrayLength)
+ && [[[definitionParts objectAtIndex:definitionPartsIndex+1] uppercaseString] isEqualToString:@"NULL"]) {
[fieldDetails setValue:[NSNumber numberWithBool:NO] forKey:@"null"];
- i++;
+ definitionPartsIndex++;
// Whether fields are NULL
} else if ([detailString isEqualToString:@"NULL"]) {
@@ -645,11 +651,11 @@
[fieldDetails setValue:[NSNumber numberWithBool:YES] forKey:@"autoincrement"];
// Field defaults
- } else if ([detailString isEqualToString:@"DEFAULT"] && (i + 1 < partsArrayLength)) {
- detailParser = [[SPSQLParser alloc] initWithString:[definitionParts objectAtIndex:i+1]];
+ } else if ([detailString isEqualToString:@"DEFAULT"] && (definitionPartsIndex + 1 < partsArrayLength)) {
+ detailParser = [[SPSQLParser alloc] initWithString:[definitionParts objectAtIndex:definitionPartsIndex+1]];
[fieldDetails setValue:[detailParser unquotedString] forKey:@"default"];
[detailParser release];
- i++;
+ definitionPartsIndex++;
}
// TODO: Currently unhandled: [UNIQUE | PRIMARY] KEY | COMMENT 'foo' | COLUMN_FORMAT bar | STORAGE q | REFERENCES...
diff --git a/Source/TableDump.m b/Source/TableDump.m
index fb0504a8..a59aad73 100644
--- a/Source/TableDump.m
+++ b/Source/TableDump.m
@@ -428,6 +428,11 @@
for ( i = 0 ; i < [queries count] ; i++ ) {
[singleProgressBar setDoubleValue:((i+1)*100/[queries count])];
[singleProgressBar displayIfNeeded];
+
+ // Skip blank or whitespace-only queries to avoid errors
+ if ([[[queries objectAtIndex:i] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length] == 0)
+ continue;
+
[mySQLConnection queryString:[queries objectAtIndex:i]];
if (![[mySQLConnection getLastErrorMessage] isEqualToString:@""] && ![[mySQLConnection getLastErrorMessage] isEqualToString:@"Query was empty"]) {
555'>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 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 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