aboutsummaryrefslogtreecommitdiffstats
path: root/Source
diff options
context:
space:
mode:
Diffstat (limited to 'Source')
-rw-r--r--Source/CMImageView.m2
-rw-r--r--Source/CMTextView.m27
-rw-r--r--Source/SPAlertSheets.h2
-rw-r--r--Source/SPAppController.m1
-rw-r--r--Source/SPConnectionController.m4
-rw-r--r--Source/SPConnectionDelegate.m31
-rw-r--r--Source/SPConstants.h7
-rw-r--r--Source/SPConstants.m7
-rw-r--r--Source/SPDBActionCommons.h48
-rw-r--r--Source/SPDBActionCommons.m35
-rw-r--r--Source/SPDatabaseCopy.h66
-rw-r--r--Source/SPDatabaseCopy.m105
-rw-r--r--Source/SPDatabaseData.h4
-rw-r--r--Source/SPDatabaseData.m42
-rw-r--r--Source/SPDatabaseInfo.h56
-rw-r--r--Source/SPDatabaseInfo.m73
-rw-r--r--Source/SPDatabaseRename.h74
-rw-r--r--Source/SPDatabaseRename.m127
-rw-r--r--Source/SPExtendedTableInfo.m8
-rw-r--r--Source/SPFieldMapperController.m13
-rw-r--r--Source/SPFileHandle.h102
-rw-r--r--Source/SPFileHandle.m343
-rw-r--r--Source/SPHistoryController.m48
-rw-r--r--Source/SPLogger.h44
-rw-r--r--Source/SPLogger.m183
-rw-r--r--Source/SPNarrowDownCompletion.m95
-rw-r--r--Source/SPNotLoaded.h2
-rw-r--r--Source/SPPreferenceController.m100
-rw-r--r--Source/SPProcessListController.h12
-rw-r--r--Source/SPProcessListController.m298
-rw-r--r--Source/SPQueryController.m6
-rw-r--r--Source/SPSQLParser.m2
-rw-r--r--Source/SPTableCopy.h61
-rw-r--r--Source/SPTableCopy.m139
-rw-r--r--Source/SPTableData.h1
-rw-r--r--Source/SPTableData.m81
-rw-r--r--Source/SPTableRelations.m6
-rw-r--r--Source/SPTableTriggers.h2
-rw-r--r--Source/SPTableTriggers.m99
-rw-r--r--Source/SPUserManager.h2
-rw-r--r--Source/SPUserManager.m43
-rw-r--r--Source/TableContent.m173
-rw-r--r--Source/TableDocument.h16
-rw-r--r--Source/TableDocument.m171
-rw-r--r--Source/TableDump.h25
-rw-r--r--Source/TableDump.m415
-rw-r--r--Source/TableSource.m102
-rw-r--r--Source/TablesList.h5
-rw-r--r--Source/TablesList.m118
49 files changed, 723 insertions, 2703 deletions
diff --git a/Source/CMImageView.m b/Source/CMImageView.m
index 32d60d13..31eb9c60 100644
--- a/Source/CMImageView.m
+++ b/Source/CMImageView.m
@@ -123,4 +123,4 @@
[delegateForUse processPasteImageData];
}
-@end
+@end \ No newline at end of file
diff --git a/Source/CMTextView.m b/Source/CMTextView.m
index e936e801..efe18042 100644
--- a/Source/CMTextView.m
+++ b/Source/CMTextView.m
@@ -34,7 +34,6 @@
#import "SPTooltip.h"
#import "TablesList.h"
#import "SPNavigatorController.h"
-#import "SPAlertSheets.h"
#pragma mark -
#pragma mark lex init
@@ -536,23 +535,23 @@ NSInteger alphabeticSort(id string1, id string2, void *reverse)
if(r.location) {
NSCharacterSet *ignoreCharacterSet = [NSCharacterSet characterSetWithCharactersInString:@"\"'`;,()[]{}=+/<> \t\n\r"];
- // Check the previous character and don't autocomplete if the character is whitespace or certain types of punctuation
- if ([ignoreCharacterSet characterIsMember:[[self string] characterAtIndex:r.location - 1]]) return;
+ // Check the previous character and don't autocomplete if the character is whitespace or certain types of punctuation
+ if ([ignoreCharacterSet characterIsMember:[[self string] characterAtIndex:r.location - 1]]) return;
- // Suppress auto-completion if the window isn't active anymore
- if ([[NSApp keyWindow] firstResponder] != self) return;
+ // Suppress auto-completion if the window isn't active anymore
+ if ([[NSApp keyWindow] firstResponder] != self) return;
- // Trigger the completion
- [self doCompletionByUsingSpellChecker:NO fuzzyMode:NO autoCompleteMode:YES];
+ // Trigger the completion
+ [self doCompletionByUsingSpellChecker:NO fuzzyMode:NO autoCompleteMode:YES];
}
}
- (void) refreshCompletion
{
- if(completionWasRefreshed) return;
- completionWasRefreshed = YES;
- [self doCompletionByUsingSpellChecker:NO fuzzyMode:completionFuzzyMode autoCompleteMode:NO];
+ if(completionWasRefreshed) return;
+ completionWasRefreshed = YES;
+ [self doCompletionByUsingSpellChecker:NO fuzzyMode:completionFuzzyMode autoCompleteMode:NO];
}
- (void) doCompletionByUsingSpellChecker:(BOOL)isDictMode fuzzyMode:(BOOL)fuzzySearch autoCompleteMode:(BOOL)autoCompleteMode
@@ -569,7 +568,7 @@ NSInteger alphabeticSort(id string1, id string2, void *reverse)
}
[self breakUndoCoalescing];
-
+
// Remember state for refreshCompletion
completionFuzzyMode = fuzzySearch;
@@ -1307,6 +1306,7 @@ NSInteger alphabeticSort(id string1, id string2, void *reverse)
if (completionIsOpen) [completionPopup close], completionPopup = nil;
completionIsOpen = YES;
+
completionPopup = [[SPNarrowDownCompletion alloc] initWithItems:possibleCompletions
alreadyTyped:@""
staticPrefix:@""
@@ -1463,6 +1463,7 @@ NSInteger alphabeticSort(id string1, id string2, void *reverse)
if (completionIsOpen) [completionPopup close], completionPopup = nil;
completionIsOpen = YES;
+
completionPopup = [[SPNarrowDownCompletion alloc] initWithItems:possibleCompletions
alreadyTyped:@""
staticPrefix:@""
@@ -2677,11 +2678,11 @@ NSInteger alphabeticSort(id string1, id string2, void *reverse)
}
[self setTypingAttributes:textAttributes];
[self setDefaultParagraphStyle:paragraphStyle];
+ [paragraphStyle release];
[self setFont:tvFont];
[self setEditable:oldEditableStatus];
- [paragraphStyle release];
}
- (void)drawRect:(NSRect)rect {
@@ -3316,4 +3317,4 @@ NSInteger alphabeticSort(id string1, id string2, void *reverse)
[super dealloc];
}
-@end
+@end \ No newline at end of file
diff --git a/Source/SPAlertSheets.h b/Source/SPAlertSheets.h
index bdcfdd64..2610ee41 100644
--- a/Source/SPAlertSheets.h
+++ b/Source/SPAlertSheets.h
@@ -33,4 +33,4 @@ void SPBeginAlertSheet(
SEL didDismissSelector,
void *contextInfo,
NSString *msg
-);
+); \ No newline at end of file
diff --git a/Source/SPAppController.m b/Source/SPAppController.m
index f793b93c..f0d4c9bf 100644
--- a/Source/SPAppController.m
+++ b/Source/SPAppController.m
@@ -441,7 +441,6 @@
@"queryHistory",
@"tableColumnWidths",
@"savePath",
- @"NSRecentDocumentRecords",
nil]];
return preferences;
diff --git a/Source/SPConnectionController.m b/Source/SPConnectionController.m
index f2d5fcdd..1f19ba1e 100644
--- a/Source/SPConnectionController.m
+++ b/Source/SPConnectionController.m
@@ -523,8 +523,8 @@
[prefsController showWindow:self];
[prefsController displayFavoritePreferences:self];
-
- if ([favoritesTable numberOfSelectedRows]) [prefsController selectFavorites:[NSArray arrayWithObject:[self valueForKeyPath:@"selectedFavorite"]]];
+
+ if ([favoritesTable numberOfSelectedRows]) [prefsController selectFavorites:[NSArray arrayWithObject:[self valueForKeyPath:@"selectedFavorite"]]];
}
/**
diff --git a/Source/SPConnectionDelegate.m b/Source/SPConnectionDelegate.m
index ae67697c..c69c3150 100644
--- a/Source/SPConnectionDelegate.m
+++ b/Source/SPConnectionDelegate.m
@@ -111,22 +111,23 @@
- (MCPConnectionCheck)connectionLost:(id)connection
{
NSInteger connectionErrorCode = MCPConnectionCheckDisconnect;
-
- // Only display the reconnect dialog if the window is visible
- if ([tableWindow isVisible]) {
-
- // Display the connection error dialog and wait for the return code
- [NSApp beginSheet:connectionErrorDialog modalForWindow:tableWindow modalDelegate:self didEndSelector:nil contextInfo:nil];
- connectionErrorCode = [NSApp runModalForWindow:connectionErrorDialog];
-
- [NSApp endSheet:connectionErrorDialog];
- [connectionErrorDialog orderOut:nil];
-
- // If 'disconnect' was selected, trigger a window close.
- if (connectionErrorCode == MCPConnectionCheckDisconnect) {
- [self performSelectorOnMainThread:@selector(closeDocumentWindowAndDisconnect) withObject:nil waitUntilDone:YES];
+
+ // Only display the reconnect dialog if the window is visible
+ if ([tableWindow isVisible]) {
+
+ // Display the connection error dialog and wait for the return code
+ [NSApp beginSheet:connectionErrorDialog modalForWindow:tableWindow modalDelegate:self didEndSelector:nil contextInfo:nil];
+ connectionErrorCode = [NSApp runModalForWindow:connectionErrorDialog];
+
+ [NSApp endSheet:connectionErrorDialog];
+ [connectionErrorDialog orderOut:nil];
+
+ // If 'disconnect' was selected, trigger a window close.
+ if (connectionErrorCode == MCPConnectionCheckDisconnect) {
+ [self performSelectorOnMainThread:@selector(closeDocumentWindowAndDisconnect) withObject:nil waitUntilDone:YES];
+ }
}
- }
+
return connectionErrorCode;
}
diff --git a/Source/SPConstants.h b/Source/SPConstants.h
index ca84e103..ed25b61e 100644
--- a/Source/SPConstants.h
+++ b/Source/SPConstants.h
@@ -215,8 +215,7 @@ extern NSString *SPEditInSheetEnabled;
extern NSString *SPTableInformationPanelCollapsed;
extern NSString *SPTableColumnWidths;
extern NSString *SPProcessListShowProcessID;
-extern NSString *SPProcessListEnableAutoRefresh;
-extern NSString *SPProcessListAutoRrefreshInterval;
+extern NSString *SPProcessListShowFullProcessList;
extern NSString *SPFavoritesSortedBy;
extern NSString *SPFavoritesSortedInReverse;
@@ -224,15 +223,13 @@ extern NSString *SPFavoritesSortedInReverse;
extern NSString *SPPrintWarningRowLimit;
extern NSString *SPDisplayServerVersionInWindowTitle;
-// Import and export
+// Import
extern NSString *SPCSVImportFieldTerminator;
extern NSString *SPCSVImportLineTerminator;
extern NSString *SPCSVImportFieldEnclosedBy;
extern NSString *SPCSVImportFieldEscapeCharacter;
extern NSString *SPCSVImportFirstLineIsHeader;
extern NSString *SPCSVFieldImportMappingAlignment;
-extern NSString *SPImportClipboardTempFileNamePrefix;
-extern NSString *SPSQLExportUseCompression;
// Misc
extern NSString *SPContentFilters;
diff --git a/Source/SPConstants.m b/Source/SPConstants.m
index 3f5bf15a..ba4156e2 100644
--- a/Source/SPConstants.m
+++ b/Source/SPConstants.m
@@ -129,8 +129,7 @@ NSString *SPEditInSheetEnabled = @"EditInSheetEnabled";
NSString *SPTableInformationPanelCollapsed = @"TableInformationPanelCollapsed";
NSString *SPTableColumnWidths = @"tableColumnWidths";
NSString *SPProcessListShowProcessID = @"ProcessListShowProcessID";
-NSString *SPProcessListEnableAutoRefresh = @"ProcessListEnableAutoRefresh";
-NSString *SPProcessListAutoRrefreshInterval = @"ProcessListAutoRrefreshInterval";
+NSString *SPProcessListShowFullProcessList = @"ProcessListShowFullProcessList";
NSString *SPFavoritesSortedBy = @"FavoritesSortedBy";
NSString *SPFavoritesSortedInReverse = @"FavoritesSortedInReverse";
@@ -138,15 +137,13 @@ NSString *SPFavoritesSortedInReverse = @"FavoritesSortedInReverse";
NSString *SPPrintWarningRowLimit = @"PrintWarningRowLimit";
NSString *SPDisplayServerVersionInWindowTitle = @"DisplayServerVersionInWindowTitle";
-// Import and export
+// Import
NSString *SPCSVImportFieldEnclosedBy = @"CSVImportFieldEnclosedBy";
NSString *SPCSVImportFieldEscapeCharacter = @"CSVImportFieldEscapeCharacter";
NSString *SPCSVImportFieldTerminator = @"CSVImportFieldTerminator";
NSString *SPCSVImportFirstLineIsHeader = @"CSVImportFirstLineIsHeader";
NSString *SPCSVImportLineTerminator = @"CSVImportLineTerminator";
NSString *SPCSVFieldImportMappingAlignment = @"CSVFieldImportMappingAlignment";
-NSString *SPImportClipboardTempFileNamePrefix = @"/tmp/_SP_ClipBoard_Import_File_";
-NSString *SPSQLExportUseCompression = @"SQLExportUseCompression";
// Misc
NSString *SPContentFilters = @"ContentFilters";
diff --git a/Source/SPDBActionCommons.h b/Source/SPDBActionCommons.h
deleted file mode 100644
index 334b0c78..00000000
--- a/Source/SPDBActionCommons.h
+++ /dev/null
@@ -1,48 +0,0 @@
-//
-// $Id$
-//
-// SPDBActionCommons.h
-// sequel-pro
-//
-// Created by David Rekowski on Apr 29, 2010
-//
-// This program is free software; you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation; either version 2 of the License, or
-// (at your option) any later version.
-//
-// This program is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU General Public License
-// along with this program; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//
-// More info at <http://code.google.com/p/sequel-pro/>
-
-#import <Foundation/Foundation.h>
-#import <Cocoa/Cocoa.h>
-#import <MCPKit/MCPConnection.h>
-#import <MCPKit/MCPResult.h>
-#import "SPAlertSheets.h"
-#import "SPStringAdditions.h"
-#import "Sequel-Pro.pch"
-
-@interface SPDBActionCommons : NSObject {
- MCPConnection *connection;
- NSWindow *messageWindow;
-}
-
-/**
- * @property MCPConnection references the MCPKit connection to MySQL; it has to be set.
- */
-@property (retain) MCPConnection *connection;
-
-/**
- * @property the NSWindow instance to send message sheets to
- */
-@property (assign) NSWindow *messageWindow;
-
-@end
diff --git a/Source/SPDBActionCommons.m b/Source/SPDBActionCommons.m
deleted file mode 100644
index 977b3b5d..00000000
--- a/Source/SPDBActionCommons.m
+++ /dev/null
@@ -1,35 +0,0 @@
-//
-// $Id$
-//
-// SPDBActionCommons.m
-// sequel-pro
-//
-// Created by David Rekowski on Apr 29, 2010
-//
-// This program is free software; you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation; either version 2 of the License, or
-// (at your option) any later version.
-//
-// This program is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU General Public License
-// along with this program; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//
-// More info at <http://code.google.com/p/sequel-pro/>
-
-#import "SPDBActionCommons.h"
-#import "SPAlertSheets.h"
-#import "SPStringAdditions.h"
-#import "Sequel-Pro.pch"
-
-@implementation SPDBActionCommons
-
-@synthesize connection;
-@synthesize messageWindow;
-
-@end
diff --git a/Source/SPDatabaseCopy.h b/Source/SPDatabaseCopy.h
deleted file mode 100644
index 3776d5a1..00000000
--- a/Source/SPDatabaseCopy.h
+++ /dev/null
@@ -1,66 +0,0 @@
-//
-// $Id$
-//
-// SPDatabaseCopy.h
-// sequel-pro
-//
-// Created by David Rekowski on Apr 13, 2010
-//
-// This program is free software; you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation; either version 2 of the License, or
-// (at your option) any later version.
-//
-// This program is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU General Public License
-// along with this program; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//
-// More info at <http://code.google.com/p/sequel-pro/>
-
-
-#import "SPDBActionCommons.h"
-#import "SPDatabaseInfo.h"
-
-/**
- * The SPDatabaseCopy class povides functionality to create a copy of a database.
- */
-@interface SPDatabaseCopy : SPDBActionCommons {
- SPDatabaseInfo *dbInfo;
-}
-
-/**
- * @property SPDatabaseInfo an instance of the database info class
- */
-@property (retain) SPDatabaseInfo *dbInfo;
-
-/**
- * This method retrieves the dbInfo object if it exists; otherwise it is generated and the
- * connection is passed to it.
- *
- * @result SPDatabaseInfo dbInfo object
- */
-- (SPDatabaseInfo *)getDBInfoObject;
-
-/**
- * This method clones an existing database.
- *
- * @param NSString sourceDatabaseName the name of the source database
- * @param NSString targetDatabaseName the name of the target database
- * @result BOOL success
- */
-- (BOOL)copyDatabaseFrom: (NSString *)sourceDatabaseName to: (NSString *)targetDatabaseName withContent: (BOOL)copyWithContent;
-
-/**
- * This method creates a new database.
- *
- * @param NSString newDatabaseName name of the new database to be created
- * @return BOOL YES on success, otherwise NO
- */
-- (BOOL) createDatabase: (NSString *)newDatabaseName;
-
-@end
diff --git a/Source/SPDatabaseCopy.m b/Source/SPDatabaseCopy.m
deleted file mode 100644
index 2d5f92c3..00000000
--- a/Source/SPDatabaseCopy.m
+++ /dev/null
@@ -1,105 +0,0 @@
-//
-// $Id$
-//
-// SPDatabaseCopy.m
-// sequel-pro
-//
-// Created by David Rekowski on Apr 13, 2010
-//
-// This program is free software; you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation; either version 2 of the License, or
-// (at your option) any later version.
-//
-// This program is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU General Public License
-// along with this program; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//
-// More info at <http://code.google.com/p/sequel-pro/>
-
-#import "SPDBActionCommons.h"
-#import "SPDatabaseCopy.h"
-#import "SPTableCopy.h"
-
-@implementation SPDatabaseCopy
-
-@synthesize dbInfo;
-
-- (SPDatabaseInfo *)getDBInfoObject {
- if (dbInfo != nil) {
- return dbInfo;
- } else {
- dbInfo = [[SPDatabaseInfo alloc] init];
- [dbInfo setConnection:[self connection]];
- [dbInfo setMessageWindow:messageWindow];
- }
- return dbInfo;
-}
-
-- (BOOL)copyDatabaseFrom: (NSString *)sourceDatabaseName to: (NSString *)targetDatabaseName withContent:(BOOL)copyWithContent {
-
- SPDatabaseInfo *databaseInfo = [self getDBInfoObject];
- // check, whether the source database exists and the target database doesn't.
- NSArray *tables = [NSArray array];
- BOOL sourceExists = [databaseInfo databaseExists:sourceDatabaseName];
- BOOL targetExists = [databaseInfo databaseExists:targetDatabaseName];
- if (sourceExists && !targetExists) {
- // retrieve the list of tables/views/funcs/triggers from the source database
-
- tables = [connection listTablesFromDB:sourceDatabaseName];
- } else {
- SPBeginAlertSheet(NSLocalizedString(@"Cannot create existing database", @"create database exists error message"),
- NSLocalizedString(@"OK", @"OK button"), nil, nil, messageWindow, self, nil, nil, nil,
- [NSString stringWithFormat:NSLocalizedString(@"An error occured while trying to create the target database.\n\nDatabase %@ already exists.",
- @"create database error informative message"),
- targetDatabaseName]);
-
- return NO;
- }
- DLog(@"list of found tables of source db: %@", tables);
-
- BOOL success = [self createDatabase:targetDatabaseName];
- SPTableCopy *dbActionTableCopy = [[SPTableCopy alloc] init];
- [dbActionTableCopy setConnection:connection];
-
- for (NSString *currentTable in tables) {
- if ([dbActionTableCopy copyTable:currentTable
- from:sourceDatabaseName
- to:targetDatabaseName
- withContent:copyWithContent]) {
- } else {
- success = NO;
- }
- }
- return success;
-}
-
-- (BOOL) createDatabase: (NSString *)newDatabaseName {
- NSString *createStatement = [NSString stringWithFormat:@"CREATE DATABASE %@",
- [newDatabaseName backtickQuotedString]];
- [connection queryString:createStatement];
-
- if ([connection queryErrored]) {
- SPBeginAlertSheet(NSLocalizedString(@"Failed to create database", @"create database error message"),
- NSLocalizedString(@"OK", @"OK button"), nil, nil, messageWindow, self, nil, nil, nil,
- [NSString stringWithFormat:NSLocalizedString(@"An error occured while trying to create the target database.\n\nMySQL said: %@",
- @"create database error informative message"),
- [connection getLastErrorMessage]]);
- return NO;
- }
- return YES;
-
-
-}
-
-- (void)dealloc {
- [dbInfo dealloc];
-}
-
-
-@end \ No newline at end of file
diff --git a/Source/SPDatabaseData.h b/Source/SPDatabaseData.h
index 29c80aeb..acfbd37c 100644
--- a/Source/SPDatabaseData.h
+++ b/Source/SPDatabaseData.h
@@ -38,10 +38,6 @@ typedef struct
{
NSString *characterSetEncoding;
- NSInteger serverMajorVersion;
- NSInteger serverMinorVersion;
- NSInteger serverReleaseVersion;
-
NSMutableArray *collations;
NSMutableArray *characterSetCollations;
NSMutableArray *storageEngines;
diff --git a/Source/SPDatabaseData.m b/Source/SPDatabaseData.m
index becd1d6e..8c4935d9 100644
--- a/Source/SPDatabaseData.m
+++ b/Source/SPDatabaseData.m
@@ -212,18 +212,6 @@ const SPDatabaseCharSets charsets[] =
}
/**
- * Set the current connection the supplied connection instance.
- */
-- (void)setConnection:(MCPConnection *)dbConnection
-{
- connection = dbConnection;
-
- serverMajorVersion = [connection serverMajorVersion];
- serverMinorVersion = [connection serverMinorVersion];
- serverReleaseVersion = [connection serverReleaseVersion];
-}
-
-/**
* Reset all the cached values.
*/
- (void)resetAllData
@@ -246,7 +234,7 @@ const SPDatabaseCharSets charsets[] =
if ([collations count] == 0) {
// Try to retrieve the available collations from the database
- if (serverMajorVersion >= 5)
+ if ([connection serverMajorVersion] >= 5)
[collations addObjectsFromArray:[self _getDatabaseDataForQuery:@"SELECT * FROM `information_schema.collations` ORDER BY `collation_name` ASC"]];
// If that failed, get the list of collations from the hard-coded list
@@ -279,7 +267,7 @@ const SPDatabaseCharSets charsets[] =
characterSetEncoding = [[NSString alloc] initWithString:encoding];
// Try to retrieve the available collations for the supplied encoding from the database
- if (serverMajorVersion >= 5)
+ if ([connection serverMajorVersion] >= 5)
[characterSetCollations addObjectsFromArray:[self _getDatabaseDataForQuery:[NSString stringWithFormat:@"SELECT * FROM `information_schema`.`collations` WHERE character_set_name = '%@' ORDER BY `collation_name` ASC", characterSetEncoding]]];
// If that failed, get the list of collations matching the supplied encoding from the hard-coded list
@@ -308,7 +296,7 @@ const SPDatabaseCharSets charsets[] =
- (NSArray *)getDatabaseStorageEngines
{
if ([storageEngines count] == 0) {
- if (serverMajorVersion < 5) {
+ if ([connection serverMajorVersion] < 5) {
[storageEngines addObject:[NSDictionary dictionaryWithObject:@"MyISAM" forKey:@"Engine"]];
// Check if InnoDB support is enabled
@@ -322,7 +310,7 @@ const SPDatabaseCharSets charsets[] =
}
// Before MySQL 4.1 the MEMORY engine was known as HEAP and the ISAM engine was included
- if ((serverMajorVersion <= 4) && (serverMinorVersion < 100)) {
+ if (([connection serverMajorVersion] <= 4) && ([connection serverMinorVersion] < 100)) {
[storageEngines addObject:[NSDictionary dictionaryWithObject:@"HEAP" forKey:@"Engine"]];
[storageEngines addObject:[NSDictionary dictionaryWithObject:@"ISAM" forKey:@"Engine"]];
}
@@ -331,28 +319,28 @@ const SPDatabaseCharSets charsets[] =
}
// BLACKHOLE storage engine was added in MySQL 4.1.11
- if ((serverMajorVersion >= 4) &&
- (serverMinorVersion >= 1) &&
- (serverReleaseVersion >= 11))
+ if (([connection serverMajorVersion] >= 4) &&
+ ([connection serverMinorVersion] >= 1) &&
+ ([connection serverReleaseVersion] >= 11))
{
[storageEngines addObject:[NSDictionary dictionaryWithObject:@"BLACKHOLE" forKey:@"Engine"]];
// ARCHIVE storage engine was added in MySQL 4.1.3
- if (serverReleaseVersion >= 3) {
+ if ([connection serverReleaseVersion] >= 3) {
[storageEngines addObject:[NSDictionary dictionaryWithObject:@"ARCHIVE" forKey:@"Engine"]];
}
// CSV storage engine was added in MySQL 4.1.4
- if (serverReleaseVersion >= 4) {
+ if ([connection serverReleaseVersion] >= 4) {
[storageEngines addObject:[NSDictionary dictionaryWithObject:@"CSV" forKey:@"Engine"]];
}
}
}
// The table information_schema.engines didn't exist until MySQL 5.1.5
else {
- if ((serverMajorVersion >= 5) &&
- (serverMinorVersion >= 1) &&
- (serverReleaseVersion >= 5))
+ if (([connection serverMajorVersion] >= 5) &&
+ ([connection serverMinorVersion] >= 1) &&
+ ([connection serverReleaseVersion] >= 5))
{
// Check the information_schema.engines table is accessible
MCPResult *result = [connection queryString:@"SHOW TABLES IN information_schema LIKE 'ENGINES'"];
@@ -392,7 +380,7 @@ const SPDatabaseCharSets charsets[] =
// Try to retrieve the available character set encodings from the database
// Check the information_schema.character_sets table is accessible
- if (serverMajorVersion >= 5)
+ if ([connection serverMajorVersion] >= 5)
[characterSetEncodings addObjectsFromArray:[self _getDatabaseDataForQuery:@"SELECT * FROM `information_schema`.`character_sets` ORDER BY `character_set_name` ASC"]];
// If that failed, get the list of character set encodings from the hard-coded list
@@ -431,6 +419,10 @@ const SPDatabaseCharSets charsets[] =
[super dealloc];
}
+@end
+
+@implementation SPDatabaseData (PrivateAPI)
+
/**
* Executes the supplied query against the current connection and returns the result as an array of
* NSDictionarys, one for each row.
diff --git a/Source/SPDatabaseInfo.h b/Source/SPDatabaseInfo.h
deleted file mode 100644
index 3f68b773..00000000
--- a/Source/SPDatabaseInfo.h
+++ /dev/null
@@ -1,56 +0,0 @@
-//
-// $Id$
-//
-// SPDatabaseInfo.h
-// sequel-pro
-//
-// Created by David Rekowski on Apr 13, 2010
-//
-// This program is free software; you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation; either version 2 of the License, or
-// (at your option) any later version.
-//
-// This program is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU General Public License
-// along with this program; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//
-// More info at <http://code.google.com/p/sequel-pro/>
-
-#import "SPDBActionCommons.h"
-
-/*
- * The SPDatabaseInfo class provides means of retrieving a list of database names
- */
-@interface SPDatabaseInfo : SPDBActionCommons {
-}
-
-/**
- * This method checks, whether a database exists.
- *
- * @param databaseName the name of the database to check
- * @result TRUE if it exists, otherwise FALSE
- */
--(BOOL)databaseExists:(NSString *)databaseName;
-
-/**
- * This method retrieves a list of all databases.
- *
- * @result NSArray databaseNames
- */
-- (NSArray *)listDBs;
-
-/**
- * This method retrieves a list of databases like the given string
- *
- * @param NSString dbsName name of the database substring to match
- * @result NSArray databaseNames
- */
-- (NSArray *)listDBsLike:(NSString *)dbsName;
-
-@end
diff --git a/Source/SPDatabaseInfo.m b/Source/SPDatabaseInfo.m
deleted file mode 100644
index 883ebef2..00000000
--- a/Source/SPDatabaseInfo.m
+++ /dev/null
@@ -1,73 +0,0 @@
-//
-// $Id$
-//
-// SPDatbaseInfo.h
-// sequel-pro
-//
-// Created by David Rekowski on Apr 13, 2010
-//
-// This program is free software; you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation; either version 2 of the License, or
-// (at your option) any later version.
-//
-// This program is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU General Public License
-// along with this program; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//
-// More info at <http://code.google.com/p/sequel-pro/>
-
-#import "SPDBActionCommons.h"
-#import "SPDatabaseInfo.h"
-
-@implementation SPDatabaseInfo
-
--(BOOL)databaseExists:(NSString *)databaseName {
- NSArray *names = [self listDBs];
- return [names containsObject:databaseName];
-}
-
-- (NSArray *)listDBs {
- return [self listDBsLike:nil];
-}
-
-- (NSArray *)listDBsLike:(NSString *)dbsName
-{
- NSString *listDBStatement = nil;
- if ((dbsName == nil) || ([dbsName isEqualToString:@""])) {
- listDBStatement = [NSString stringWithFormat:@"SHOW DATABASES"];
- }
- else {
- listDBStatement = [NSString stringWithFormat:@"SHOW DATABASES LIKE %@", [dbsName backtickQuotedString]];
- }
- DLog(@"running query : %@", listDBStatement);
- MCPResult *theResult = [connection queryString:listDBStatement];
-
- if ([connection queryErrored]) {
- SPBeginAlertSheet(NSLocalizedString(@"Failed to retrieve databases list", @"database list error message"),
- NSLocalizedString(@"OK", @"OK button"), nil, nil, messageWindow, self, nil, nil, nil,
- [NSString stringWithFormat:NSLocalizedString(@"An error occured while trying to retrieve a list of databases.\n\nMySQL said: %@",
- @"database list error informative message"),
- [connection getLastErrorMessage]]);
- return NO;
- }
-
- NSMutableArray *names = [NSMutableArray array];
- NSMutableString *name;
- if ([theResult numOfRows] > 1) {
- int i;
- for ( i = 0 ; i < [theResult numOfRows] ; i++ ) {
- name = [[theResult fetchRowAsArray] objectAtIndex:0];
- [names addObject:name];
- }
- }
-
- return names;
-}
-
-@end
diff --git a/Source/SPDatabaseRename.h b/Source/SPDatabaseRename.h
deleted file mode 100644
index bd52a86f..00000000
--- a/Source/SPDatabaseRename.h
+++ /dev/null
@@ -1,74 +0,0 @@
-//
-// $Id$
-//
-// SPDatabaseRename.h
-// sequel-pro
-//
-// Created by David Rekowski on Apr 13, 2010
-//
-// This program is free software; you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation; either version 2 of the License, or
-// (at your option) any later version.
-//
-// This program is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU General Public License
-// along with this program; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//
-// More info at <http://code.google.com/p/sequel-pro/>
-
-
-#import "SPDBActionCommons.h"
-#import "SPDatabaseInfo.h"
-
-/**
- * The SPDatabaseRename class povides functionality to rename a database.
- */
-@interface SPDatabaseRename : SPDBActionCommons {
- SPDatabaseInfo *dbInfo;
-}
-
-/**
- * @property SPDatabaseInfo an instance of the database info class
- */
-@property (retain) SPDatabaseInfo *dbInfo;
-
-/**
- * This method retrieves the dbInfo object if it exists; otherwise it is generated and the
- * connection is passed to it.
- *
- * @result SPDatabaseInfo dbInfo object
- */
-- (SPDatabaseInfo *)getDBInfoObject;
-
-/**
- * This method renames an existing database.
- *
- * @param NSString sourceDatabaseName the name of the source database
- * @param NSString targetDatabaseName the name of the target database
- * @result BOOL success
- */
-- (BOOL)renameDatabaseFrom: (NSString *)sourceDatabaseName to: (NSString *)targetDatabaseName;
-
-/**
- * This method creates a new database.
- *
- * @param NSString newDatabaseName name of the new database to be created
- * @return BOOL YES on success, otherwise NO
- */
-- (BOOL) createDatabase: (NSString *)newDatabaseName;
-
-/**
- * This method drops a database.
- *
- * @param NSString databaseName name of the database to drop
- * @return BOOL YES on success, otherwise NO
- */
-- (BOOL) dropDatabase: (NSString *)databaseName;
-
-@end
diff --git a/Source/SPDatabaseRename.m b/Source/SPDatabaseRename.m
deleted file mode 100644
index 26a983e5..00000000
--- a/Source/SPDatabaseRename.m
+++ /dev/null
@@ -1,127 +0,0 @@
-//
-// $Id$
-//
-// SPDatabaseRename.m
-// sequel-pro
-//
-// Created by David Rekowski on Apr 13, 2010
-//
-// This program is free software; you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation; either version 2 of the License, or
-// (at your option) any later version.
-//
-// This program is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU General Public License
-// along with this program; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//
-// More info at <http://code.google.com/p/sequel-pro/>
-
-
-#import "SPDBActionCommons.h"
-#import "SPDatabaseRename.h"
-#import "SPTableCopy.h"
-
-@implementation SPDatabaseRename
-
-@synthesize dbInfo;
-
-- (SPDatabaseInfo *)getDBInfoObject {
- if (dbInfo != nil) {
- return dbInfo;
- } else {
- dbInfo = [[SPDatabaseInfo alloc] init];
- [dbInfo setConnection:[self connection]];
- [dbInfo setMessageWindow:messageWindow];
- }
- return dbInfo;
-}
-
-- (BOOL)renameDatabaseFrom: (NSString *)sourceDatabaseName to: (NSString *)targetDatabaseName {
- SPDatabaseInfo *databaseInfo = [self getDBInfoObject];
-
- // check, whether the source database exists and the target database doesn't.
- NSArray *tables = [NSArray array];
- BOOL sourceExists = [databaseInfo databaseExists:sourceDatabaseName];
- BOOL targetExists = [databaseInfo databaseExists:targetDatabaseName];
- if (sourceExists && !targetExists) {
- // retrieve the list of tables/views/funcs/triggers from the source database
-
- tables = [connection listTablesFromDB:sourceDatabaseName];
- } else {
- SPBeginAlertSheet(NSLocalizedString(@"Cannot create existing database", @"create database exists error message"),
- NSLocalizedString(@"OK", @"OK button"), nil, nil, messageWindow, self, nil, nil, nil,
- [NSString stringWithFormat:NSLocalizedString(@"An error occured while trying to create the target database.\n\nDatabase %@ already exists.",
- @"create database error informative message"),
- targetDatabaseName]);
- return NO;
- }
- DLog(@"list of found tables of source db: %@", tables);
-
- BOOL success = [self createDatabase:targetDatabaseName];
- SPTableCopy *dbActionTableCopy = [[SPTableCopy alloc] init];
- [dbActionTableCopy setConnection:connection];
-
- for (NSString *currentTable in tables) {
- if ([dbActionTableCopy moveTable:currentTable
- from:sourceDatabaseName
- to:targetDatabaseName]) {
- } else {
- success = FALSE;
- }
- }
- tables = [connection listTablesFromDB:sourceDatabaseName];
- if ([tables count] == 0) {
- [self dropDatabase:sourceDatabaseName];
- } else {
- SPBeginAlertSheet(NSLocalizedString(@"Failed to delete database", @"delete database error message"),
- NSLocalizedString(@"OK", @"OK button"), nil, nil, messageWindow, self, nil, nil, nil,
- [NSString stringWithFormat:NSLocalizedString(@"Database %@ not empty, skipping drop database.",
- @"delete database not empty error informative message"),
- sourceDatabaseName]);
- }
- return success;
-}
-
-- (BOOL) createDatabase: (NSString *)newDatabaseName {
- NSString *createStatement = [NSString stringWithFormat:@"CREATE DATABASE %@",
- [newDatabaseName backtickQuotedString]];
- [connection queryString:createStatement];
- if ([connection queryErrored]) {
- SPBeginAlertSheet(NSLocalizedString(@"Failed to create database", @"create database error message"),
- NSLocalizedString(@"OK", @"OK button"), nil, nil, messageWindow, self, nil, nil, nil,
- [NSString stringWithFormat:NSLocalizedString(@"An error occured while trying to create a database.\n\nMySQL said: %@",
- @"create database error informative message"),
- [connection getLastErrorMessage]]);
- return NO;
- }
- return YES;
-
-}
-
-- (BOOL) dropDatabase: (NSString *)databaseName {
- NSString *dropStatement = [NSString stringWithFormat:@"DROP DATABASE %@",
- [databaseName backtickQuotedString]];
- [connection queryString:dropStatement];
- if ([connection queryErrored]) {
- SPBeginAlertSheet(NSLocalizedString(@"Failed to drop database", @"drop database error message"),
- NSLocalizedString(@"OK", @"OK button"), nil, nil, messageWindow, self, nil, nil, nil,
- [NSString stringWithFormat:NSLocalizedString(@"An error occured while trying to drop a database.\n\nMySQL said: %@",
- @"drop database error informative message"),
- [connection getLastErrorMessage]]);
- return NO;
- }
- return YES;
-
-}
-
-- (void)dealloc {
- [dbInfo dealloc];
-}
-
-@end \ No newline at end of file
diff --git a/Source/SPExtendedTableInfo.m b/Source/SPExtendedTableInfo.m
index f272a3e5..d58e731e 100644
--- a/Source/SPExtendedTableInfo.m
+++ b/Source/SPExtendedTableInfo.m
@@ -238,7 +238,7 @@
[tableCreateSyntaxTextView setString:@""];
NSString *createViewSyntax = [[[tableDataInstance tableCreateSyntax] createViewSyntaxPrettifier] stringByAppendingString:@";"];
-
+
if (createViewSyntax) {
[tableCreateSyntaxTextView shouldChangeTextInRange:NSMakeRange(0, 0) replacementString:createViewSyntax];
[tableCreateSyntaxTextView insertText:createViewSyntax];
@@ -282,7 +282,7 @@
NSArray *collations = [databaseDataInstance getDatabaseCollationsForEncoding:[tableDataInstance tableEncoding]];
if (([engines count] > 0) && ([statusFields objectForKey:@"Engine"])) {
-
+
// Populate type popup button
for (NSDictionary *engine in engines)
{
@@ -353,7 +353,7 @@
[tableCommentsTextView setString:[statusFields objectForKey:@"Comment"]];
[tableCommentsTextView didChangeText];
[tableCommentsTextView setEditable:enableInteraction];
-
+
// Set create syntax
[tableCreateSyntaxTextView setEditable:YES];
[tableCreateSyntaxTextView shouldChangeTextInRange:NSMakeRange(0, [[tableCommentsTextView string] length]) replacementString:@""];
@@ -436,7 +436,7 @@
- (void)textDidEndEditing:(NSNotification *)notification
{
id object = [notification object];
-
+
if ((object == tableCommentsTextView) && ([object isEditable]) && ([selectedTable length] > 0)) {
NSString *currentComment = [[tableDataInstance statusValueForKey:@"Comment"] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
diff --git a/Source/SPFieldMapperController.m b/Source/SPFieldMapperController.m
index a3d17f1c..ae935b44 100644
--- a/Source/SPFieldMapperController.m
+++ b/Source/SPFieldMapperController.m
@@ -82,13 +82,8 @@
{
// Set source path
- if([sourcePath hasPrefix:SPImportClipboardTempFileNamePrefix]) {
- [fileSourcePath setURL:[NSURL fileURLWithPath:NSLocalizedString(@"Clipboard", @"Clipboard")]];
- } else {
- [fileSourcePath setURL:[NSURL fileURLWithPath:sourcePath]];
- }
+ [fileSourcePath setURL:[NSURL fileURLWithPath:sourcePath]];
[fileSourcePath setDoubleAction:@selector(goBackToFileChooser:)];
-
[onupdateTextView setDelegate:theDelegate];
windowMinWidth = [[self window] minSize].width;
windowMinHeigth = [[self window] minSize].height;
@@ -546,11 +541,7 @@
- (IBAction)goBackToFileChooser:(id)sender
{
[NSApp endSheet:[self window] returnCode:[sender tag]];
- if([sourcePath hasPrefix:SPImportClipboardTempFileNamePrefix]) {
- [theDelegate importFromClipboard];
- } else {
- [theDelegate importFile];
- }
+ [theDelegate importFile];
}
#pragma mark -
diff --git a/Source/SPFileHandle.h b/Source/SPFileHandle.h
deleted file mode 100644
index 05e05dd5..00000000
--- a/Source/SPFileHandle.h
+++ /dev/null
@@ -1,102 +0,0 @@
-//
-// $Id$
-//
-// SPFileHandle.h
-// sequel-pro
-//
-// Created by Rowan Beentje on April 5, 2010
-// Copyright (c) 2010 Rowan Beentje. All rights reserved.
-//
-// This program is free software; you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation; either version 2 of the License, or
-// (at your option) any later version.
-//
-// This program is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU General Public License
-// along with this program; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//
-// More info at <http://code.google.com/p/sequel-pro/>
-
-/**
- * Provides a class which aims to duplicate some of the most-used functionality
- * of NSFileHandle, while also transparently supporting GZip-compressed content
- * on reading; also supports GZip compression when writing.
- */
-
-#import <Cocoa/Cocoa.h>
-
-@interface SPFileHandle : NSObject {
- void *wrappedFile;
- char *wrappedFilePath;
-
- NSMutableData *buffer;
- NSUInteger bufferDataLength;
- NSUInteger bufferPosition;
- BOOL endOfFile;
- pthread_mutex_t bufferLock;
- NSThread *processingThread;
-
- int fileMode;
- BOOL dataWritten;
- BOOL allDataWritten;
- BOOL fileIsClosed;
- BOOL useGzip;
-}
-
-
-#pragma mark -
-#pragma mark Class methods
-
-+ (id) fileHandleForReadingAtPath:(NSString *)path;
-+ (id) fileHandleForWritingAtPath:(NSString *)path;
-+ (id) fileHandleForPath:(NSString *)path mode:(int)mode;
-
-#pragma mark -
-#pragma mark Initialisation
-
-// Returns a file handle initialised with a file
-- (id) initWithFile:(void *)theFile fromPath:(const char *)path mode:(int)mode;
-
-
-#pragma mark -
-#pragma mark Data reading
-
-// Reads data up to a specified number of bytes from the file
-- (NSMutableData *) readDataOfLength:(NSUInteger)length;
-
-// Returns the data to the end of the file
-- (NSMutableData *) readDataToEndOfFile;
-
-// Returns the on-disk (raw) length of data read so far - can be used in progress bars
-- (NSUInteger) realDataReadLength;
-
-#pragma mark -
-#pragma mark Data writing
-
-// Set whether data should be written as gzipped data (defaults to NO on a fresh object)
-- (void) setShouldWriteWithGzipCompression:(BOOL)useGzip;
-
-// Write the provided data to the file
-- (void) writeData:(NSData *)data;
-
-// Ensures any buffers are written to disk
-- (void) synchronizeFile;
-
-// Prevents further access to the file
-- (void) closeFile;
-
-
-#pragma mark -
-#pragma mark File information
-
-// Returns whether gzip compression is enabled on the file
-- (BOOL) isCompressed;
-
-
-@end
diff --git a/Source/SPFileHandle.m b/Source/SPFileHandle.m
deleted file mode 100644
index bceae2aa..00000000
--- a/Source/SPFileHandle.m
+++ /dev/null
@@ -1,343 +0,0 @@
-//
-// $Id$
-//
-// SPFileHandle.m
-// sequel-pro
-//
-// Created by Rowan Beentje on April 5, 2010
-// Copyright (c) 2010 Rowan Beentje. All rights reserved.
-//
-// This program is free software; you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation; either version 2 of the License, or
-// (at your option) any later version.
-//
-// This program is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU General Public License
-// along with this program; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//
-// More info at <http://code.google.com/p/sequel-pro/>
-
-#import "SPFileHandle.h"
-#import "zlib.1.2.4.h"
-#import "pthread.h"
-
-// Define the maximum size of the background write buffer before the writing thread
-// waits until some has been written out. This can affect speed and memory usage.
-#define SPFH_MAX_WRITE_BUFFER_SIZE 1048576
-
-@interface SPFileHandle (PrivateAPI)
-- (void) _writeBufferToData;
-@end
-
-
-@implementation SPFileHandle
-
-#pragma mark -
-#pragma mark Setup and teardown
-
-/**
- * Initialises and returns a SPFileHandle with a specified file (FILE or gzFile).
- * "mode" indicates the file interaction mode - currently only read-only
- * or write-only are supported.
- * On reading, theFile should always be a gzFile; on writing, theFile is a FILE
- * when compression is disabled, or a gzFile when enbled.
- */
-- (id) initWithFile:(void *)theFile fromPath:(const char *)path mode:(int)mode
-{
- if (self = [super init]) {
- dataWritten = NO;
- allDataWritten = YES;
- fileIsClosed = NO;
-
- wrappedFile = theFile;
- wrappedFilePath = malloc(strlen(path) + 1);
- strcpy(wrappedFilePath, path);
-
- // Check and set the mode
- fileMode = mode;
- if (fileMode != O_RDONLY && fileMode != O_WRONLY) {
- [NSException raise:NSInvalidArgumentException format:@"SPFileHandle only supports read-only and write-only file modes"];
- }
-
- // Instantiate the buffer
- pthread_mutex_init(&bufferLock, NULL);
- buffer = [[NSMutableData alloc] init];
- bufferDataLength = 0;
- bufferPosition = 0;
- endOfFile = NO;
-
- // If in read mode, set up the buffer
- if (fileMode == O_RDONLY) {
- gzbuffer(wrappedFile, 131072);
- useGzip = !gzdirect(wrappedFile);
- processingThread = nil;
-
- // In write mode, set up a thread to handle writing in the background
- } else if (fileMode == O_WRONLY) {
- useGzip = NO;
- processingThread = [[NSThread alloc] initWithTarget:self selector:@selector(_writeBufferToData) object:nil];
- [processingThread start];
- }
- }
-
- return self;
-}
-
-- (void) dealloc
-{
- [self closeFile];
- if (processingThread) [processingThread release];
- free(wrappedFilePath);
- [buffer release];
- pthread_mutex_destroy(&bufferLock);
- [super dealloc];
-}
-
-#pragma mark -
-#pragma mark Class methods
-
-/**
- * Retrieve and return a SPFileHandle for reading a file at the supplied
- * path. Returns nil if the file could not be found or opened.
- */
-+ (id) fileHandleForReadingAtPath:(NSString *)path
-{
- return [self fileHandleForPath:path mode:O_RDONLY];
-}
-
-/**
- * Retrieve and return a SPFileHandle for writing a file at the supplied
- * path. Returns nil if the file could not be found or opened.
- */
-+ (id) fileHandleForWritingAtPath:(NSString *)path
-{
- return [self fileHandleForPath:path mode:O_WRONLY];
-}
-
-/**
- * Retrieve and return a SPFileHandle for a file at the specified path,
- * using the supplied file status flag. Returns nil if the file could
- * not be found or opened.
- */
-+ (id) fileHandleForPath:(NSString *)path mode:(int)mode
-{
-
- // Retrieves the path in a filesystem-appropriate format and encoding
- const char *pathRepresentation = [path fileSystemRepresentation];
- if (!pathRepresentation) return nil;
-
- // Open the file to get a file descriptor, returning on failure
- FILE *theFile;
- const char *theMode;
- if (mode == O_WRONLY) {
- theMode = "wb";
- theFile = fopen(pathRepresentation, theMode);
- } else {
- theMode = "rb";
- theFile = gzopen(pathRepresentation, theMode);
- }
- if (theFile == NULL) return nil;
-
- // Return an autoreleased file handle
- return [[[self alloc] initWithFile:theFile fromPath:pathRepresentation mode:mode] autorelease];
-}
-
-
-#pragma mark -
-#pragma mark Data reading
-
-/**
- * Reads data up to a specified number of uncompressed bytes from the file.
- */
-- (NSMutableData *) readDataOfLength:(NSUInteger)length
-{
- void *theData = malloc(length);
- long theDataLength = gzread(wrappedFile, theData, length);
- return [NSMutableData dataWithBytesNoCopy:theData length:theDataLength freeWhenDone:YES];
-}
-
-/**
- * Returns all the data to the end of the file.
- */
-- (NSMutableData *) readDataToEndOfFile
-{
- return [self readDataOfLength:NSUIntegerMax];
-}
-
-/**
- * Returns the on-disk (raw/uncompressed) length of data read so far.
- * This includes any compression headers within the data, and can be used
- * for progress bars when processing files.
- */
-- (NSUInteger) realDataReadLength
-{
- if (fileMode == O_WRONLY) return 0;
- return gzoffset(wrappedFile);
-}
-
-#pragma mark -
-#pragma mark Data writing
-
-/**
- * Set whether data should be written as gzipped data, defaulting
- * to NO on a fresh object. If this is called after data has been
- * written, an exception is thrown.
- */
-- (void) setShouldWriteWithGzipCompression:(BOOL)shouldUseGzip
-{
- if (shouldUseGzip == useGzip) return;
-
- if (dataWritten) [NSException raise:NSInternalInconsistencyException format:@"Cannot change compression settings when data has already been written"];
-
- if (shouldUseGzip) {
- fclose(wrappedFile);
- wrappedFile = gzopen(wrappedFilePath, "wb");
- gzbuffer(wrappedFile, 131072);
- } else {
- gzclose(wrappedFile);
- wrappedFile = fopen(wrappedFilePath, "wb");
- }
- useGzip = shouldUseGzip;
-}
-
-
-/**
- * Write the supplied data to the file. The data may not be written to the
- * disk at once (see synchronizeFile).
- */
-- (void) writeData:(NSData *)data
-{
-
- // Throw an exception if the file is closed
- if (fileIsClosed) [NSException raise:NSInternalInconsistencyException format:@"Cannot write to a file handle after it has been closed"];
-
- // Add the data to the buffer
- if ([data length]) {
- pthread_mutex_lock(&bufferLock);
- [buffer appendData:data];
- allDataWritten = NO;
- bufferDataLength += [data length];
- }
-
- // If the buffer is large, wait for some to be written out
- while (bufferDataLength > SPFH_MAX_WRITE_BUFFER_SIZE) {
- pthread_mutex_unlock(&bufferLock);
- usleep(100);
- pthread_mutex_lock(&bufferLock);
- }
- pthread_mutex_unlock(&bufferLock);
-}
-
-/**
- * Blocks until all data has been written to disk.
- */
-- (void) synchronizeFile
-{
- pthread_mutex_lock(&bufferLock);
- while (!allDataWritten) {
- pthread_mutex_unlock(&bufferLock);
- usleep(100);
- pthread_mutex_lock(&bufferLock);
- }
- pthread_mutex_unlock(&bufferLock);
-}
-
-/**
- * Ensure all data is written out, close any file handles, and prevent any
- * more data from being written to the file.
- */
-- (void) closeFile
-{
- if (!fileIsClosed) {
- [self synchronizeFile];
- if (useGzip || fileMode == O_RDONLY) {
- gzclose(wrappedFile);
- } else {
- fclose(wrappedFile);
- }
- if (processingThread) {
- if ([processingThread isExecuting]) {
- [processingThread cancel];
- while ([processingThread isExecuting]) usleep(100);
- }
- }
- fileIsClosed = YES;
- }
-}
-
-
-#pragma mark -
-#pragma mark File information
-
-/**
- * Returns whether gzip compression is enabled on the file.
- */
-- (BOOL) isCompressed
-{
- return useGzip;
-}
-
-@end
-
-@implementation SPFileHandle (PrivateAPI)
-
-/**
- * A method to be called on a background thread, allowing write data to build
- * up in a buffer and write to disk in chunks as the buffer fills. This allows
- * background compression of the data when using Gzip compression.
- */
-- (void) _writeBufferToData
-{
- NSAutoreleasePool *writePool = [[NSAutoreleasePool alloc] init];
-
- // Process the buffer in a loop into the file, until cancelled
- while (!fileIsClosed && ![processingThread isCancelled]) {
-
- // Check whether any data in the buffer needs to be written out - using thread locks for safety
- pthread_mutex_lock(&bufferLock);
- if (!bufferDataLength) {
- pthread_mutex_unlock(&bufferLock);
- usleep(1000);
- continue;
- }
-
- // Copy the data into a local buffer
- NSData *dataToBeWritten = [NSData dataWithData:buffer];
- [buffer setLength:0];
- bufferDataLength = 0;
- pthread_mutex_unlock(&bufferLock);
-
- // Write out the data
- long bufferLengthWrittenOut;
- if (useGzip) {
- bufferLengthWrittenOut = gzwrite(wrappedFile, [dataToBeWritten bytes], [dataToBeWritten length]);
- } else {
- bufferLengthWrittenOut = fwrite([dataToBeWritten bytes], 1, [dataToBeWritten length], wrappedFile);
- }
-
- // Restore data to the buffer if it wasn't written out
- pthread_mutex_lock(&bufferLock);
- if (bufferLengthWrittenOut < [dataToBeWritten length]) {
- if ([buffer length]) {
- long dataLengthToRestore = [dataToBeWritten length] - bufferLengthWrittenOut;
- [buffer replaceBytesInRange:NSMakeRange(0, 0) withBytes:[[dataToBeWritten subdataWithRange:NSMakeRange(bufferLengthWrittenOut, dataLengthToRestore)] bytes] length:dataLengthToRestore];
- bufferDataLength += dataLengthToRestore;
- }
-
- // Otherwise, mark all data as written if it has been - allows synching to hard disk.
- } else if (![buffer length]) {
- allDataWritten = YES;
- }
- pthread_mutex_unlock(&bufferLock);
- }
-
- [writePool drain];
-}
-
-@end
diff --git a/Source/SPHistoryController.m b/Source/SPHistoryController.m
index 567ebd7a..a1d9de58 100644
--- a/Source/SPHistoryController.m
+++ b/Source/SPHistoryController.m
@@ -57,10 +57,10 @@
tableContentInstance = [theDocument valueForKey:@"tableContentInstance"];
tablesListInstance = [theDocument valueForKey:@"tablesListInstance"];
toolbarItemVisible = NO;
- [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(toolbarWillAddItem:) name:NSToolbarWillAddItemNotification object:[theDocument valueForKey:@"mainToolbar"]];
- [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(toolbarDidRemoveItem:) name:NSToolbarDidRemoveItemNotification object:[theDocument valueForKey:@"mainToolbar"]];
- [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(startDocumentTask:) name:SPDocumentTaskStartNotification object:theDocument];
- [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(endDocumentTask:) name:SPDocumentTaskEndNotification object:theDocument];
+ [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(toolbarWillAddItem:) name:NSToolbarWillAddItemNotification object:[theDocument valueForKey:@"mainToolbar"]];
+ [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(toolbarDidRemoveItem:) name:NSToolbarDidRemoveItemNotification object:[theDocument valueForKey:@"mainToolbar"]];
+ [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(startDocumentTask:) name:SPDocumentTaskStartNotification object:theDocument];
+ [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(endDocumentTask:) name:SPDocumentTaskEndNotification object:theDocument];
}
- (void) dealloc
@@ -80,9 +80,9 @@
- (void) updateToolbarItem
{
- // If the toolbar item isn't visible, don't perform any actions - as manipulating
- // items not on the toolbar can cause crashes.
- if (!toolbarItemVisible) return;
+ // If the toolbar item isn't visible, don't perform any actions - as manipulating
+ // items not on the toolbar can cause crashes.
+ if (!toolbarItemVisible) return;
BOOL backEnabled = NO;
BOOL forwardEnabled = NO;
@@ -92,7 +92,7 @@
// Set the active state of the segments if appropriate
if ([history count] && historyPosition > 0) backEnabled = YES;
if ([history count] && historyPosition + 1 < [history count]) forwardEnabled = YES;
-
+
[historyControl setEnabled:backEnabled forSegment:0];
[historyControl setEnabled:forwardEnabled forSegment:1];
@@ -196,13 +196,13 @@
*/
- (void) setupInterface
{
- NSArray *toolbarItems = [[theDocument valueForKey:@"mainToolbar"] items];
- for (NSToolbarItem *toolbarItem in toolbarItems) {
- if ([[toolbarItem itemIdentifier] isEqualToString:SPMainToolbarHistoryNavigation]) {
- toolbarItemVisible = YES;
- break;
- }
- }
+ NSArray *toolbarItems = [[theDocument valueForKey:@"mainToolbar"] items];
+ for (NSToolbarItem *toolbarItem in toolbarItems) {
+ if ([[toolbarItem itemIdentifier] isEqualToString:SPMainToolbarHistoryNavigation]) {
+ toolbarItemVisible = YES;
+ break;
+ }
+ }
}
/**
@@ -210,7 +210,7 @@
*/
- (void) startDocumentTask:(NSNotification *)aNotification
{
- if (toolbarItemVisible) [historyControl setEnabled:NO];
+ if (toolbarItemVisible) [historyControl setEnabled:NO];
}
/**
@@ -218,7 +218,7 @@
*/
- (void) endDocumentTask:(NSNotification *)aNotification
{
- if (toolbarItemVisible) [historyControl setEnabled:YES];
+ if (toolbarItemVisible) [historyControl setEnabled:YES];
}
/**
@@ -227,10 +227,10 @@
* can cause crashes.
*/
- (void) toolbarWillAddItem:(NSNotification *)aNotification {
- if ([[[[aNotification userInfo] objectForKey:@"item"] itemIdentifier] isEqualToString:SPMainToolbarHistoryNavigation]) {
- toolbarItemVisible = YES;
- [self performSelector:@selector(updateToolbarItem) withObject:nil afterDelay:0.1];
- }
+ if ([[[[aNotification userInfo] objectForKey:@"item"] itemIdentifier] isEqualToString:SPMainToolbarHistoryNavigation]) {
+ toolbarItemVisible = YES;
+ [self performSelector:@selector(updateToolbarItem) withObject:nil afterDelay:0.1];
+ }
}
/**
@@ -239,9 +239,9 @@
* can cause crashes.
*/
- (void) toolbarDidRemoveItem:(NSNotification *)aNotification {
- if ([[[[aNotification userInfo] objectForKey:@"item"] itemIdentifier] isEqualToString:SPMainToolbarHistoryNavigation]) {
- toolbarItemVisible = NO;
- }
+ if ([[[[aNotification userInfo] objectForKey:@"item"] itemIdentifier] isEqualToString:SPMainToolbarHistoryNavigation]) {
+ toolbarItemVisible = NO;
+ }
}
#pragma mark -
diff --git a/Source/SPLogger.h b/Source/SPLogger.h
index 4d394b83..ac9b9a04 100644
--- a/Source/SPLogger.h
+++ b/Source/SPLogger.h
@@ -27,53 +27,13 @@
@interface SPLogger : NSObject
{
- /**
- * Dump leaks on termination flag.
- */
- BOOL dumpLeaksOnTermination;
-
- /**
- * Remove old leak dumps on termination flag.
- */
- BOOL removeOldLeakDumpsOnTermination;
-
- /**
- * Log file initialized successfully flag.
- */
BOOL initializedSuccessfully;
-
- /**
- * Log file handle.
- */
NSFileHandle *logFileHandle;
}
-/**
- * Returns the shared logger.
- *
- * @return The logger instance
- */
+ (SPLogger *)logger;
-@property(readwrite, assign) BOOL dumpLeaksOnTermination;
-@property(readwrite, assign) BOOL removeOldLeakDumpsOnTermination;
-
-/**
- * Dumps the result of running leaks to the file '/tmp/sp.leaks.<pid>.tmp'.
- *
- * Note, that to enable useful output, make sure the following environment variables are set to YES:
- *
- * MallocStackLogging
- * MallocStackLoggingNoCompact
- *
- * Also note that the application may take a while to terminate if it has been running for a significant
- * period of time or has been handling large amounts of data.
- */
-- (void)dumpLeaks;
-
-/**
- * Logs the supplied string to the log file.
- */
-- (void)log:(NSString *)theString, ...;
+- (void) outputTimeString;
+- (void) log:(NSString *)theString, ...;
@end
diff --git a/Source/SPLogger.m b/Source/SPLogger.m
index 83c5b49c..d492fe32 100644
--- a/Source/SPLogger.m
+++ b/Source/SPLogger.m
@@ -25,21 +25,8 @@
#import "SPLogger.h"
-#include <pwd.h>
-#include <stdio.h>
-#include <dirent.h>
-#include <sys/dir.h>
-#include <sys/types.h>
-
static SPLogger *logger = nil;
-@interface SPLogger (PrivateAPI)
-
-- (void)_initLogFile;
-- (void)_outputTimeString;
-
-@end
-
/**
* This is a small class intended to aid in user issue debugging; by including
* the header file, and using [[SPLogger logger] log:@"String with format", ...]
@@ -53,9 +40,6 @@ static SPLogger *logger = nil;
@implementation SPLogger
-@synthesize dumpLeaksOnTermination;
-@synthesize removeOldLeakDumpsOnTermination;
-
/*
* Returns the shared logger object.
*/
@@ -93,10 +77,41 @@ static SPLogger *logger = nil;
- (id)init
{
if ((self = [super init])) {
+ NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDesktopDirectory, NSUserDomainMask, YES);
+ NSString *logFilePath = [NSString stringWithFormat:@"%@/Sequel Pro Debug Log.txt", [paths objectAtIndex:0]];
+
initializedSuccessfully = YES;
- [self setDumpLeaksOnTermination:NO];
- [self setRemoveOldLeakDumpsOnTermination:YES];
+ // Check if the debug file exists, and is writable
+ if ( [[NSFileManager defaultManager] fileExistsAtPath:logFilePath] ) {
+ if ( ![[NSFileManager defaultManager] isWritableFileAtPath:logFilePath] ) {
+ initializedSuccessfully = NO;
+ NSRunAlertPanel(@"Logging error", @"Log file exists but is not writeable; no debug log will be generated!", @"OK", nil, nil);
+ }
+
+ // Otherwise try creating one
+ } else {
+ if ( ![[NSFileManager defaultManager] createFileAtPath:logFilePath contents:[NSData data] attributes:nil] ) {
+ initializedSuccessfully = NO;
+ NSRunAlertPanel(@"Logging error", @"Could not create log file for writing; no debug log will be generated!", @"OK", nil, nil);
+ }
+ }
+
+ // Get a file handle to the file if possible
+ if (initializedSuccessfully) {
+ logFileHandle = [NSFileHandle fileHandleForWritingAtPath:logFilePath];
+ if (!logFileHandle) {
+ initializedSuccessfully = NO;
+ NSRunAlertPanel(@"Logging error", @"Could not open log file for writing; no debug log will be generated!", @"OK", nil, nil);
+ } else {
+ [logFileHandle retain];
+ [logFileHandle seekToEndOfFile];
+ NSString *bundleName = [[NSFileManager defaultManager] displayNameAtPath:[[NSBundle mainBundle] bundlePath]];
+ NSMutableString *logStart = [NSMutableString stringWithString:@"\n\n\n==========================================================================\n\n"];
+ [logStart appendString:[NSString stringWithFormat:@"%@ (r%ld)\n", bundleName, (long)[[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] integerValue]]];
+ [logFileHandle writeData:[logStart dataUsingEncoding:NSUTF8StringEncoding]];
+ }
+ }
}
return self;
@@ -105,11 +120,9 @@ static SPLogger *logger = nil;
#pragma mark -
#pragma mark Logging functions
-- (void)log:(NSString *)theString, ...
+- (void) log:(NSString *)theString, ...
{
if (!initializedSuccessfully) return;
-
- if (!logFileHandle) [self _initLogFile];
// Extract any supplied arguments and build the formatted log string
va_list arguments;
@@ -118,138 +131,16 @@ static SPLogger *logger = nil;
va_end(arguments);
// Write the log line, forcing an immediate write to disk to ensure logging
- [logFileHandle writeData:[[NSString stringWithFormat:@"%@ %@\n", [[NSDate date] descriptionWithCalendarFormat:@"%H:%M:%S" timeZone:nil locale:[[NSUserDefaults standardUserDefaults] dictionaryRepresentation]], logString] dataUsingEncoding:NSUTF8StringEncoding]];
+ [logFileHandle writeData:[[NSString stringWithFormat:@"%@ %@\n", [[NSDate date] descriptionWithCalendarFormat:@"%H:%M:%S" timeZone:nil locale:[[NSUserDefaults standardUserDefaults] dictionaryRepresentation]], logString] dataUsingEncoding:NSUTF8StringEncoding]];
[logFileHandle synchronizeFile];
[logString release];
}
-- (void)dumpLeaks
-{
- if ([self dumpLeaksOnTermination]) {
-
- char *lgn;
- struct passwd *pw;
- boolean_t hdir = FALSE;
-
- // Determine where to write the log to
- if ((lgn = getlogin()) == NULL || (pw = getpwnam(lgn)) == NULL) {
- fprintf(stderr, "Unable to get user info, falling back to /tmp\n");
- }
- else {
- hdir = TRUE;
- }
-
- // If required remove old logs
- if ([self removeOldLeakDumpsOnTermination]) {
-
- int cnt, cnt2, i;
- int isSPLeaksLog();
- struct direct **files;
-
- cnt = scandir("/tmp", &files, isSPLeaksLog, NULL);
-
- char fpath[32], fpath2[32], fpath3[64];
-
- for (i = 0; i < cnt; i++)
- {
- snprintf(fpath, sizeof(fpath), "/tmp/%s", files[i]->d_name);
-
- if (remove(fpath) != 0) {
- printf("Unable to remove Sequel Pro leaks log '%s'\n", files[i]->d_name);
- }
- }
-
- free(&files);
-
- if (hdir) {
- snprintf(fpath2, sizeof(fpath2), "%s/Desktop", pw->pw_dir);
-
- cnt2 = scandir(fpath2, &files, isSPLeaksLog, NULL);
-
- for (i = 0; i < cnt2; i++)
- {
- snprintf(fpath3, sizeof(fpath3), "%s/%s", fpath2, files[i]->d_name);
-
- if (remove(fpath3) != 0) {
- printf("Unable to remove Sequel Pro leaks log '%s'\n", files[i]->d_name);
- }
- }
- }
- }
-
- size_t len;
- FILE *fp, *fp2;
- char cmd[32], file[64], buf[512];
-
- snprintf(cmd, sizeof(cmd), "/usr/bin/leaks %d", getpid());
- snprintf(file, sizeof(file), (hdir) ? "%s/Desktop/sp.leaks.%d.log" : "%s/sp.leaks.%d.log", (hdir) ? pw->pw_dir : "/tmp", getpid());
-
- // Write new leaks log
- if ((fp = popen(cmd, "r")) && (fp2 = fopen(file, "w"))) {
-
- while (len = fread(buf, 1, sizeof(buf), fp))
- {
- fwrite(buf, 1, len, fp2);
- }
-
- pclose(fp);
- }
- }
-}
-
-int isSPLeaksLog(struct direct *entry)
-{
- return (strstr(entry->d_name, "sp.leaks") != NULL);
-}
-
-- (void)_initLogFile
-{
- NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDesktopDirectory, NSUserDomainMask, YES);
- NSString *logFilePath = [NSString stringWithFormat:@"%@/Sequel Pro Debug Log.log", [paths objectAtIndex:0]];
-
- NSFileManager *fileManager = [NSFileManager defaultManager];
-
- // Check if the debug file exists, and is writable
- if ([fileManager fileExistsAtPath:logFilePath]) {
- if (![fileManager isWritableFileAtPath:logFilePath]) {
- initializedSuccessfully = NO;
- NSRunAlertPanel(@"Logging error", @"Log file exists but is not writeable; no debug log will be generated!", @"OK", nil, nil);
- }
- // Otherwise try creating one
- }
- else {
- if (![fileManager createFileAtPath:logFilePath contents:[NSData data] attributes:nil]) {
- initializedSuccessfully = NO;
- NSRunAlertPanel(@"Logging error", @"Could not create log file for writing; no debug log will be generated!", @"OK", nil, nil);
- }
- }
-
- // Get a file handle to the file if possible
- if (initializedSuccessfully) {
- logFileHandle = [NSFileHandle fileHandleForWritingAtPath:logFilePath];
-
- if (!logFileHandle) {
- initializedSuccessfully = NO;
- NSRunAlertPanel(@"Logging error", @"Could not open log file for writing; no debug log will be generated!", @"OK", nil, nil);
- }
- else {
- [logFileHandle retain];
- [logFileHandle seekToEndOfFile];
-
- NSString *bundleName = [fileManager displayNameAtPath:[[NSBundle mainBundle] bundlePath]];
- NSMutableString *logStart = [NSMutableString stringWithString:@"\n\n\n==========================================================================\n\n"];
-
- [logStart appendString:[NSString stringWithFormat:@"%@ (r%ld)\n", bundleName, (long)[[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] integerValue]]];
- [logFileHandle writeData:[logStart dataUsingEncoding:NSUTF8StringEncoding]];
- }
- }
-}
-
-- (void)_outputTimeString
+- (void) outputTimeString
{
if (!initializedSuccessfully) return;
-
+
[logFileHandle writeData:[[NSString stringWithFormat:@"Launched at %@\n\n", [[NSDate date] description]] dataUsingEncoding:NSUTF8StringEncoding]];
}
diff --git a/Source/SPNarrowDownCompletion.m b/Source/SPNarrowDownCompletion.m
index 668e01c1..1ac2118c 100644
--- a/Source/SPNarrowDownCompletion.m
+++ b/Source/SPNarrowDownCompletion.m
@@ -75,6 +75,7 @@
};
unichar keyCode = 0;
+
if([anEvent type] == NSKeyDown && [[anEvent characters] length] == 1)
keyCode = [[anEvent characters] characterAtIndex:0];
@@ -90,6 +91,7 @@
} else {
[self selectRowIndexes:[NSIndexSet indexSetWithIndex:row] byExtendingSelection:NO];
}
+
[self scrollRowToVisible:row];
return YES;
}
@@ -153,7 +155,7 @@
[mutablePrefix release];
[textualInputCharacters release];
[originalFilterString release];
- if(syncArrowImages) [syncArrowImages release];
+ if (syncArrowImages) [syncArrowImages release];
if(suggestions) [suggestions release];
if (filtered) [filtered release];
@@ -408,13 +410,12 @@
}
return @"";
} else if([[aTableColumn identifier] isEqualToString:@"name"]) {
- if(isQueryingDatabaseStructure && rowIndex == 0)
+ if(isQueryingDatabaseStructure && rowIndex == 0)
return NSLocalizedString(@"fetching database structure in progress", @"fetching database structure in progress");
return [[filtered objectAtIndex:rowIndex] objectForKey:@"display"];
-
} else if ([[aTableColumn identifier] isEqualToString:@"list"] || [[aTableColumn identifier] isEqualToString:@"type"]) {
- if(isQueryingDatabaseStructure && rowIndex == 0)
+ if(isQueryingDatabaseStructure && rowIndex == 0)
return NSLocalizedString(@"fetching database structure data in progress", @"fetching database structure data in progress");
if(dictMode) {
@@ -435,7 +436,7 @@
}
} else if ([[aTableColumn identifier] isEqualToString:@"path"]) {
- if(isQueryingDatabaseStructure && rowIndex == 0)
+ if(isQueryingDatabaseStructure && rowIndex == 0)
return NSLocalizedString(@"fetching database structure in progress", @"fetching database structure in progress");
if(dictMode) {
@@ -608,7 +609,7 @@
{
NSMutableArray* newFiltered = [[NSMutableArray alloc] initWithCapacity:5];
-
+
if([mutablePrefix length] > 0)
{
if(dictMode) {
@@ -768,10 +769,10 @@
if(!event)
continue;
-
+
// Exit if closeMe has been set in the meantime
if(closeMe) return;
-
+
NSEventType t = [event type];
if([theTableView SP_NarrowDownCompletion_canHandleEvent:event])
{
@@ -787,15 +788,15 @@
if (([event modifierFlags] & (NSShiftKeyMask|NSControlKeyMask|NSAlternateKeyMask|NSCommandKeyMask)) == NSAlternateKeyMask || [[event characters] length] == 0)
{
if(autoCompletionMode) {
- if(commonPrefixWasInsertedByAutoComplete) {
- [theView setSelectedRange:theCharRange];
- [theView insertText:originalFilterString];
- [theView setCompletionIsOpen:NO];
- [self close];
- [NSApp sendEvent:event];
- break;
- }
- }
+ if(commonPrefixWasInsertedByAutoComplete) {
+ [theView setSelectedRange:theCharRange];
+ [theView insertText:originalFilterString];
+ [theView setCompletionIsOpen:NO];
+ [self close];
+ [NSApp sendEvent:event];
+ break;
+ }
+ }
[NSApp sendEvent: event];
if(commaInsertionMode)
@@ -819,14 +820,14 @@
[self filter];
} else {
if(autoCompletionMode) {
- if(commonPrefixWasInsertedByAutoComplete) {
- [theView setSelectedRange:theCharRange];
- [theView insertText:originalFilterString];
- }
- [theView setCompletionIsOpen:NO];
- [self close];
- break;
- }
+ if(commonPrefixWasInsertedByAutoComplete) {
+ [theView setSelectedRange:theCharRange];
+ [theView insertText:originalFilterString];
+ }
+ [theView setCompletionIsOpen:NO];
+ [self close];
+ break;
+ }
if(cursorMovedLeft) [theView performSelector:@selector(moveRight:)];
break;
}
@@ -838,13 +839,13 @@
else if(key == NSBackspaceCharacter || key == NSDeleteCharacter)
{
if(autoCompletionMode) {
- if(commonPrefixWasInsertedByAutoComplete) {
- [theView setSelectedRange:theCharRange];
- [theView insertText:originalFilterString];
- }
- [NSApp sendEvent:event];
- break;
- }
+ if(commonPrefixWasInsertedByAutoComplete) {
+ [theView setSelectedRange:theCharRange];
+ [theView insertText:originalFilterString];
+ }
+ [NSApp sendEvent:event];
+ break;
+ }
[NSApp sendEvent:event];
if([mutablePrefix length] == 0 || commaInsertionMode)
break;
@@ -858,16 +859,16 @@
else if([textualInputCharacters characterIsMember:key])
{
- if(autoCompletionMode) {
- [theView setCompletionIsOpen:NO];
- [self close];
- if(commonPrefixWasInsertedByAutoComplete) {
- [theView setSelectedRange:theCharRange];
- [theView insertText:originalFilterString];
- }
- [NSApp sendEvent:event];
- return;
- }
+ if(autoCompletionMode) {
+ [theView setCompletionIsOpen:NO];
+ [self close];
+ if(commonPrefixWasInsertedByAutoComplete) {
+ [theView setSelectedRange:theCharRange];
+ [theView insertText:originalFilterString];
+ }
+ [NSApp sendEvent:event];
+ return;
+ }
[NSApp sendEvent:event];
@@ -897,11 +898,11 @@
} else {
if(!NSPointInRect([NSEvent mouseLocation], [self frame])) {
if(autoCompletionMode) {
- if(commonPrefixWasInsertedByAutoComplete) {
- [theView setSelectedRange:theCharRange];
- [theView insertText:originalFilterString];
- }
- }
+ if(commonPrefixWasInsertedByAutoComplete) {
+ [theView setSelectedRange:theCharRange];
+ [theView insertText:originalFilterString];
+ }
+ }
if(cursorMovedLeft) [theView performSelector:@selector(moveRight:)];
[NSApp sendEvent:event];
break;
diff --git a/Source/SPNotLoaded.h b/Source/SPNotLoaded.h
index 25c4810c..611a3f91 100644
--- a/Source/SPNotLoaded.h
+++ b/Source/SPNotLoaded.h
@@ -36,4 +36,4 @@
- (BOOL) isSPNotLoaded;
-@end
+@end \ No newline at end of file
diff --git a/Source/SPPreferenceController.m b/Source/SPPreferenceController.m
index e27c9b05..080a319f 100644
--- a/Source/SPPreferenceController.m
+++ b/Source/SPPreferenceController.m
@@ -346,11 +346,11 @@
- (IBAction)removeFavorite:(id)sender
{
if ([favoritesTableView numberOfSelectedRows] == 1) {
- NSAlert *alert = [NSAlert alertWithMessageText:[NSString stringWithFormat:NSLocalizedString(@"Delete favorite '%@'?", @"delete database message"), [favoritesController valueForKeyPath:@"selection.name"]]
- defaultButton:NSLocalizedString(@"Delete", @"delete button")
- alternateButton:NSLocalizedString(@"Cancel", @"cancel button")
- otherButton:nil
- informativeTextWithFormat:[NSString stringWithFormat:NSLocalizedString(@"Are you sure you want to delete the favorite '%@'? This operation cannot be undone.", @"delete database informative message"), [favoritesController valueForKeyPath:@"selection.name"]]];
+ NSAlert *alert = [NSAlert alertWithMessageText:[NSString stringWithFormat:NSLocalizedString(@"Remove favorite '%@'?", @"remove database message"), [favoritesController valueForKeyPath:@"selection.name"]]
+ defaultButton:NSLocalizedString(@"Remove", @"remove button")
+ alternateButton:NSLocalizedString(@"Cancel", @"cancel button")
+ otherButton:nil
+ informativeTextWithFormat:[NSString stringWithFormat:NSLocalizedString(@"Are you sure you want to remove the favorite '%@'? This operation cannot be undone.", @"remove database informative message"), [favoritesController valueForKeyPath:@"selection.name"]]];
NSArray *buttons = [alert buttons];
@@ -995,49 +995,49 @@
- (void)sheetDidEnd:(id)sheet returnCode:(NSInteger)returnCode contextInfo:(NSString *)contextInfo
{
- // Order out current sheet to suppress overlapping of sheets
- if ([sheet respondsToSelector:@selector(orderOut:)])
+ // Order out current sheet to suppress overlapping of sheets
+ if ([sheet respondsToSelector:@selector(orderOut:)])
[sheet orderOut:nil];
- else if ([sheet respondsToSelector:@selector(window)])
- [[sheet window] orderOut:nil];
-
- // Remove the current database
- if ([contextInfo isEqualToString:@"removeFavorite"]) {
- if (returnCode == NSAlertDefaultReturn) {
-
- // Get selected favorite's details
- NSString *name = [favoritesController valueForKeyPath:@"selection.name"];
- NSString *user = [favoritesController valueForKeyPath:@"selection.user"];
- NSString *host = [favoritesController valueForKeyPath:@"selection.host"];
- NSString *database = [favoritesController valueForKeyPath:@"selection.database"];
- NSString *sshUser = [favoritesController valueForKeyPath:@"selection.sshUser"];
- NSString *sshHost = [favoritesController valueForKeyPath:@"selection.sshHost"];
- NSString *favoriteid = [favoritesController valueForKeyPath:@"selection.id"];
- NSInteger type = [[favoritesController valueForKeyPath:@"selection.type"] integerValue];
-
- // Remove passwords from the Keychain
- [keychain deletePasswordForName:[keychain nameForFavoriteName:name id:favoriteid]
- account:[keychain accountForUser:user host:((type == SPSocketConnection)?@"localhost":host) database:database]];
- [keychain deletePasswordForName:[keychain nameForSSHForFavoriteName:name id:favoriteid]
- account:[keychain accountForSSHUser:sshUser sshHost:sshHost]];
-
- // Reset last used favorite
- if ([favoritesTableView selectedRow] == [prefs integerForKey:SPLastFavoriteIndex]) {
- [prefs setInteger:0 forKey:SPLastFavoriteIndex];
- }
-
- // Reset default favorite
- if ([favoritesTableView selectedRow] == [prefs integerForKey:SPDefaultFavorite]) {
- [prefs setInteger:[prefs integerForKey:SPLastFavoriteIndex] forKey:SPDefaultFavorite];
- }
-
- [favoritesController removeObjectAtArrangedObjectIndex:[favoritesTableView selectedRow]];
-
- [favoritesTableView reloadData];
-
- [self updateDefaultFavoritePopup];
- }
- }
+ else if ([sheet respondsToSelector:@selector(window)])
+ [[sheet window] orderOut:nil];
+
+ // Remove the current database
+ if ([contextInfo isEqualToString:@"removeFavorite"]) {
+ if (returnCode == NSAlertDefaultReturn) {
+
+ // Get selected favorite's details
+ NSString *name = [favoritesController valueForKeyPath:@"selection.name"];
+ NSString *user = [favoritesController valueForKeyPath:@"selection.user"];
+ NSString *host = [favoritesController valueForKeyPath:@"selection.host"];
+ NSString *database = [favoritesController valueForKeyPath:@"selection.database"];
+ NSString *sshUser = [favoritesController valueForKeyPath:@"selection.sshUser"];
+ NSString *sshHost = [favoritesController valueForKeyPath:@"selection.sshHost"];
+ NSString *favoriteid = [favoritesController valueForKeyPath:@"selection.id"];
+ NSInteger type = [[favoritesController valueForKeyPath:@"selection.type"] integerValue];
+
+ // Remove passwords from the Keychain
+ [keychain deletePasswordForName:[keychain nameForFavoriteName:name id:favoriteid]
+ account:[keychain accountForUser:user host:((type == SPSocketConnection)?@"localhost":host) database:database]];
+ [keychain deletePasswordForName:[keychain nameForSSHForFavoriteName:name id:favoriteid]
+ account:[keychain accountForSSHUser:sshUser sshHost:sshHost]];
+
+ // Reset last used favorite
+ if ([favoritesTableView selectedRow] == [prefs integerForKey:SPLastFavoriteIndex]) {
+ [prefs setInteger:0 forKey:SPLastFavoriteIndex];
+ }
+
+ // Reset default favorite
+ if ([favoritesTableView selectedRow] == [prefs integerForKey:SPDefaultFavorite]) {
+ [prefs setInteger:[prefs integerForKey:SPLastFavoriteIndex] forKey:SPDefaultFavorite];
+ }
+
+ [favoritesController removeObjectAtArrangedObjectIndex:[favoritesTableView selectedRow]];
+
+ [favoritesTableView reloadData];
+
+ [self updateDefaultFavoritePopup];
+ }
+ }
}
- (void)setGrowlEnabled:(BOOL)value
@@ -1083,9 +1083,9 @@
// Add item to switch to edit favorites pane
[[defaultFavoritePopup menu] addItem:[NSMenuItem separatorItem]];
- [defaultFavoritePopup addItemWithTitle:NSLocalizedString(@"Edit Favorites…", @"edit favorites menu item")];
- [[[defaultFavoritePopup menu] itemWithTitle:NSLocalizedString(@"Edit Favorites…", @"edit favorites menu item")] setAction:@selector(displayFavoritePreferences:)];
- [[[defaultFavoritePopup menu] itemWithTitle:NSLocalizedString(@"Edit Favorites…", @"edit favorites menu item")] setTarget:self];
+ [defaultFavoritePopup addItemWithTitle:@"Edit Favorites…"];
+ [[[defaultFavoritePopup menu] itemWithTitle:@"Edit Favorites…"] setAction:@selector(displayFavoritePreferences:)];
+ [[[defaultFavoritePopup menu] itemWithTitle:@"Edit Favorites…"] setTarget:self];
// Select the default favorite from prefs
if (![prefs boolForKey:SPSelectLastFavoriteUsed]) {
diff --git a/Source/SPProcessListController.h b/Source/SPProcessListController.h
index be095d40..5283c417 100644
--- a/Source/SPProcessListController.h
+++ b/Source/SPProcessListController.h
@@ -32,36 +32,26 @@
BOOL showFullProcessList;
- NSTimer *autoRefreshTimer;
-
NSUserDefaults *prefs;
NSMutableArray *processes, *processesFiltered;
- IBOutlet NSWindow *customIntervalWindow;
- IBOutlet NSTextField *customIntervalTextField;
- IBOutlet NSButton *customIntervalButton;
IBOutlet NSTableView *processListTableView;
IBOutlet NSTextField *processesCountTextField;
IBOutlet NSSearchField *filterProcessesSearchField;
IBOutlet NSProgressIndicator *refreshProgressIndicator;
IBOutlet NSButton *saveProcessesButton;
IBOutlet NSButton *refreshProcessesButton;
- IBOutlet NSButton *autoRefreshButton;
- IBOutlet NSMenuItem *autoRefreshIntervalMenuItem;
}
@property (readwrite, assign) MCPConnection *connection;
- (IBAction)copy:(id)sender;
-- (IBAction)closeSheet:(id)sender;
- (IBAction)refreshProcessList:(id)sender;
- (IBAction)saveServerProcesses:(id)sender;
- (IBAction)killProcessQuery:(id)sender;
- (IBAction)killProcessConnection:(id)sender;
- (IBAction)toggleShowProcessID:(id)sender;
-- (IBAction)toggleProcessListAutoRefresh:(id)sender;
-- (IBAction)setAutoRefreshInterval:(id)sender;
-- (IBAction)setCustomAutoRefreshInterval:(id)sender;
+- (IBAction)toggeleShowFullProcessList:(id)sender;
- (void)displayProcessListWindow;
diff --git a/Source/SPProcessListController.m b/Source/SPProcessListController.m
index 07c67247..0d4c653d 100644
--- a/Source/SPProcessListController.m
+++ b/Source/SPProcessListController.m
@@ -33,13 +33,7 @@
@interface SPProcessListController (PrivateAPI)
-- (void)_processListRefreshed;
-- (void)_startAutoRefreshTimer;
-- (void)_killAutoRefreshTimer;
-- (void)_fireAutoRefresh:(NSTimer *)timer;
-- (void)_updateSelectedAutoRefreshIntervalInterface;
-- (void)_startAutoRefreshTimerWithInterval:(NSTimeInterval)interval;
-- (void)_getDatabaseProcessListInBackground:(id)object;
+- (void)_getDatabaseProcessList;
- (void)_killProcessQueryWithId:(NSUInteger)processId;
- (void)_killProcessConnectionWithId:(NSUInteger)processId;
- (void)_updateServerProcessesFilterForFilterString:(NSString *)filterString;
@@ -50,20 +44,18 @@
@synthesize connection;
-#pragma mark -
-#pragma mark Initialisation
-
/**
* Initialisation
*/
- (id)init
{
if ((self = [super initWithWindowNibName:@"DatabaseProcessList"])) {
-
- autoRefreshTimer = nil;
processes = [[NSMutableArray alloc] init];
prefs = [NSUserDefaults standardUserDefaults];
+
+ // Default the process list comment to SHOW FULL PROCESSLIST
+ showFullProcessList = [prefs boolForKey:SPProcessListShowFullProcessList];
}
return self;
@@ -96,15 +88,6 @@
[prefs addObserver:self forKeyPath:SPUseMonospacedFonts options:NSKeyValueObservingOptionNew context:NULL];
}
-/**
- * Interface loading
- */
-- (void)windowDidLoad
-{
- // Update the selected auto refresh interval
- [self _updateSelectedAutoRefreshIntervalInterface];
-}
-
#pragma mark -
#pragma mark IBAction methods
@@ -153,27 +136,16 @@
}
/**
- * Close the current sheet
+ * Close the process list sheet.
*/
-- (IBAction)closeSheet:(id)sender
+- (void)close
{
- [NSApp endSheet:[sender window] returnCode:[sender tag]];
- [[sender window] orderOut:self];
-}
-
-/**
- * If required start the auto refresh timer.
- */
-- (void)showWindow:(id)sender
-{
- // If the auto refresh option is enable start the timer
- if ([prefs boolForKey:SPProcessListEnableAutoRefresh]) {
-
- // Start the auto refresh time but by pass the interface updates
- [self _startAutoRefreshTimer];
+ // If the filtered array is allocated and it's not a reference to the processes array get rid of it
+ if ((processesFiltered) && (processesFiltered != processes)) {
+ [processesFiltered release], processesFiltered = nil;
}
- [super showWindow:sender];
+ [super close];
}
/**
@@ -193,9 +165,24 @@
[refreshProcessesButton setEnabled:NO];
[saveProcessesButton setEnabled:NO];
[filterProcessesSearchField setEnabled:NO];
-
- // Get the processes list on a background thread
- [NSThread detachNewThreadSelector:@selector(_getDatabaseProcessListInBackground:) toTarget:self withObject:nil];
+
+ [self _getDatabaseProcessList];
+
+ // Reapply any filters is required
+ if ([[filterProcessesSearchField stringValue] length] > 0) {
+ [self _updateServerProcessesFilterForFilterString:[filterProcessesSearchField stringValue]];
+ }
+
+ [processListTableView reloadData];
+
+ // Enable controls
+ [filterProcessesSearchField setEnabled:YES];
+ [saveProcessesButton setEnabled:YES];
+ [refreshProcessesButton setEnabled:YES];
+
+ // Stop progress Indicator
+ [refreshProgressIndicator stopAnimation:self];
+ [refreshProgressIndicator setHidden:YES];
}
/**
@@ -269,7 +256,7 @@
}
/**
- * Toggles the display of the process ID table column.
+ *
*/
- (IBAction)toggleShowProcessID:(id)sender
{
@@ -277,38 +264,13 @@
}
/**
- * Toggles whether or not auto refresh is enabled.
- */
-- (IBAction)toggleProcessListAutoRefresh:(id)sender
-{
- BOOL enable = [sender state];
-
- // Enable/Disable the refresh button
- [refreshProcessesButton setEnabled:(!enable)];
-
- (enable) ? [self _startAutoRefreshTimer] : [self _killAutoRefreshTimer];
-}
-
-/**
- * Changes the auto refresh time interval based on the selected item
- */
-- (IBAction)setAutoRefreshInterval:(id)sender
-{
- [self _startAutoRefreshTimerWithInterval:[sender tag]];
-}
-
-/**
*
*/
-- (IBAction)setCustomAutoRefreshInterval:(id)sender
+- (IBAction)toggeleShowFullProcessList:(id)sender
{
- [customIntervalTextField setStringValue:[prefs stringForKey:SPProcessListAutoRrefreshInterval]];
-
- [NSApp beginSheet:customIntervalWindow
- modalForWindow:[self window]
- modalDelegate:self
- didEndSelector:@selector(sheetDidEnd:returnCode:contextInfo:)
- contextInfo:nil];
+ showFullProcessList = (!showFullProcessList);
+
+ [self refreshProcessList:self];
}
#pragma mark -
@@ -333,29 +295,19 @@
- (void)sheetDidEnd:(id)sheet returnCode:(NSInteger)returnCode contextInfo:(NSString *)contextInfo
{
// Order out current sheet to suppress overlapping of sheets
- if ([sheet respondsToSelector:@selector(orderOut:)]) {
+ if ([sheet respondsToSelector:@selector(orderOut:)])
[sheet orderOut:nil];
- }
- else if ([sheet respondsToSelector:@selector(window)]) {
+ else if ([sheet respondsToSelector:@selector(window)])
[[sheet window] orderOut:nil];
- }
if (returnCode == NSAlertDefaultReturn) {
+ NSUInteger processId = [[[processes objectAtIndex:[processListTableView selectedRow]] valueForKey:@"Id"] integerValue];
- if (sheet == customIntervalWindow) {
- NSLog(@"Set custom value to: %d", [customIntervalTextField integerValue]);
-
- [self _startAutoRefreshTimerWithInterval:[customIntervalTextField integerValue]];
+ if ([contextInfo isEqualToString:SPKillProcessQueryMode]) {
+ [self _killProcessQueryWithId:processId];
}
- else {
- NSUInteger processId = [[[processes objectAtIndex:[processListTableView selectedRow]] valueForKey:@"Id"] integerValue];
-
- if ([contextInfo isEqualToString:SPKillProcessQueryMode]) {
- [self _killProcessQueryWithId:processId];
- }
- else if ([contextInfo isEqualToString:SPKillProcessConnectionMode]) {
- [self _killProcessConnectionWithId:processId];
- }
+ else if ([contextInfo isEqualToString:SPKillProcessConnectionMode]) {
+ [self _killProcessConnectionWithId:processId];
}
}
}
@@ -405,10 +357,6 @@
return ([processListTableView numberOfSelectedRows] == 1);
}
- if ((action == @selector(setAutoRefreshInterval:)) || (action == @selector(setCustomAutoRefreshInterval:))) {
- return [prefs boolForKey:SPProcessListEnableAutoRefresh];
- }
-
return YES;
}
@@ -460,7 +408,7 @@
- (id)tableView:(NSTableView *)tableView objectValueForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row
{
id object = (row < [processesFiltered count]) ? [[processesFiltered objectAtIndex:row] valueForKey:[tableColumn identifier]] : @"";
-
+
return (![object isNSNull]) ? object : [prefs stringForKey:SPNullValue];
}
@@ -477,26 +425,6 @@
if (object == filterProcessesSearchField) {
[self _updateServerProcessesFilterForFilterString:[object stringValue]];
}
- else if (object == customIntervalTextField) {
- [customIntervalButton setEnabled:(([[customIntervalTextField stringValue] length] > 0) && ([customIntervalTextField integerValue] > 0))];
- }
-}
-
-#pragma mark -
-#pragma mark Window delegate methods
-
-/**
- * Kill the auto refresh timer if it's running.
- */
-- (void)windowWillClose:(NSNotification *)notification
-{
- // If the filtered array is allocated and it's not a reference to the processes array get rid of it
- if ((processesFiltered) && (processesFiltered != processes)) {
- [processesFiltered release], processesFiltered = nil;
- }
-
- // Kill the auto refresh timer if running
- [self _killAutoRefreshTimer];
}
#pragma mark -
@@ -510,139 +438,33 @@
[processes release], processes = nil;
- if (autoRefreshTimer) [autoRefreshTimer release], autoRefreshTimer = nil;
-
[super dealloc];
}
-#pragma mark -
-#pragma mark Private API
-
-/**
- * Called by the background thread on the main thread once it has completed getting the list of processes.
- */
-- (void)_processListRefreshed
-{
- // Reapply any filters is required
- if ([[filterProcessesSearchField stringValue] length] > 0) {
- [self _updateServerProcessesFilterForFilterString:[filterProcessesSearchField stringValue]];
- }
-
- [processListTableView reloadData];
-
- // Enable controls
- [filterProcessesSearchField setEnabled:YES];
- [saveProcessesButton setEnabled:YES];
- [refreshProcessesButton setEnabled:(![autoRefreshButton state])];
-
- // Stop progress Indicator
- [refreshProgressIndicator stopAnimation:self];
- [refreshProgressIndicator setHidden:YES];
-}
+@end
-/**
- * Starts the auto refresh timer.
- */
-- (void)_startAutoRefreshTimer
-{
- autoRefreshTimer = [[NSTimer scheduledTimerWithTimeInterval:[prefs doubleForKey:SPProcessListAutoRrefreshInterval] target:self selector:@selector(_fireAutoRefresh:) userInfo:nil repeats:YES] retain];
-}
+@implementation SPProcessListController (PrivateAPI)
/**
- * Kills the auto refresh timer.
+ * Gets the current process list form the database;
*/
-- (void)_killAutoRefreshTimer
+- (void)_getDatabaseProcessList
{
- // If the auto refresh timer is running, kill it
- if (autoRefreshTimer && [autoRefreshTimer isValid]) {
- [autoRefreshTimer invalidate];
- [autoRefreshTimer release], autoRefreshTimer = nil;
- }
-}
-
-/**
- * Refreshes the process list when called by the auto refesh timer.
- */
-- (void)_fireAutoRefresh:(NSTimer *)timer
-{
- [self refreshProcessList:self];
-}
-
-/**
- *
- */
-- (void)_updateSelectedAutoRefreshIntervalInterface
-{
- BOOL found = NO;
- NSUInteger interval = [prefs integerForKey:SPProcessListAutoRrefreshInterval];
-
- NSArray *items = [[autoRefreshIntervalMenuItem submenu] itemArray];
-
- // Uncheck all items
- for (NSMenuItem *item in items)
- {
- [item setState:NSOffState];
- }
+ NSUInteger i = 0;
- // Check the selected item
- for (NSMenuItem *item in items)
- {
- if (interval == [item tag]) {
- found = YES;
- [item setState:NSOnState];
- break;
- }
- }
+ // Get processes
+ MCPResult *processList = [connection queryString:(showFullProcessList) ? @"SHOW FULL PROCESSLIST" : @"SHOW PROCESSLIST"];
- // If a match wasn't found then a custom value is set
- if (!found) [[items objectAtIndex:([items count] - 1)] setState:NSOnState];
-}
-
-/**
- * Starts the auto refresh time with the supplied time interval.
- */
-- (void)_startAutoRefreshTimerWithInterval:(NSTimeInterval)interval
-{
- [prefs setDouble:interval forKey:SPProcessListAutoRrefreshInterval];
+ [processList setReturnDataAsStrings:YES];
- // Update the interface
- [self _updateSelectedAutoRefreshIntervalInterface];
+ if ([processList numOfRows]) [processList dataSeek:0];
- // Kill the timer and restart it with the new interval
- [self _killAutoRefreshTimer];
- [self _startAutoRefreshTimer];
-}
+ [processes removeAllObjects];
-/**
- * Gets a list of current database processed on a background thread.
- */
-- (void)_getDatabaseProcessListInBackground:(id)object;
-{
- NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
-
- NSUInteger i = 0;
-
- // Get processes
- if ([connection isConnected]) {
-
- MCPResult *processList = [connection listProcesses];
-
- [processList setReturnDataAsStrings:YES];
-
- if ([processList numOfRows]) [processList dataSeek:0];
-
- [processes removeAllObjects];
-
- for (i = 0; i < [processList numOfRows]; i++)
- {
- [processes addObject:[processList fetchRowAsDictionary]];
- }
+ for (i = 0; i < [processList numOfRows]; i++)
+ {
+ [processes addObject:[processList fetchRowAsDictionary]];
}
-
- // Update the UI on the main thread
- [self performSelectorOnMainThread:@selector(_processListRefreshed) withObject:nil waitUntilDone:NO];
-
- [pool release];
}
/**
@@ -714,13 +536,13 @@
// Perform filtering
for (NSDictionary *process in processes)
{
- if (([[process objectForKey:@"Id"] rangeOfString:filterString options:NSCaseInsensitiveSearch].location != NSNotFound) ||
- ([[process objectForKey:@"User"] rangeOfString:filterString options:NSCaseInsensitiveSearch].location != NSNotFound) ||
- ([[process objectForKey:@"Host"] rangeOfString:filterString options:NSCaseInsensitiveSearch].location != NSNotFound) ||
- ((![[process objectForKey:@"db"] isNSNull]) && ([[process objectForKey:@"db"] rangeOfString:filterString options:NSCaseInsensitiveSearch].location != NSNotFound)) ||
+ if (([[process objectForKey:@"Id"] rangeOfString:filterString options:NSCaseInsensitiveSearch].location != NSNotFound) ||
+ ([[process objectForKey:@"User"] rangeOfString:filterString options:NSCaseInsensitiveSearch].location != NSNotFound) ||
+ ([[process objectForKey:@"Host"] rangeOfString:filterString options:NSCaseInsensitiveSearch].location != NSNotFound) ||
+ ((![[process objectForKey:@"db"] isNSNull]) && ([[process objectForKey:@"db"] rangeOfString:filterString options:NSCaseInsensitiveSearch].location != NSNotFound)) ||
([[process objectForKey:@"Command"] rangeOfString:filterString options:NSCaseInsensitiveSearch].location != NSNotFound) ||
- ([[process objectForKey:@"Time"] rangeOfString:filterString options:NSCaseInsensitiveSearch].location != NSNotFound) ||
- ((![[process objectForKey:@"State"] isNSNull]) && ([[process objectForKey:@"State"] rangeOfString:filterString options:NSCaseInsensitiveSearch].location != NSNotFound)) ||
+ ([[process objectForKey:@"Time"] rangeOfString:filterString options:NSCaseInsensitiveSearch].location != NSNotFound) ||
+ ((![[process objectForKey:@"State"] isNSNull]) && ([[process objectForKey:@"State"] rangeOfString:filterString options:NSCaseInsensitiveSearch].location != NSNotFound)) ||
((![[process objectForKey:@"Info"] isNSNull]) && ([[process objectForKey:@"Info"] rangeOfString:filterString options:NSCaseInsensitiveSearch].location != NSNotFound)))
{
[processesFiltered addObject:process];
diff --git a/Source/SPQueryController.m b/Source/SPQueryController.m
index c8906477..b6a64636 100644
--- a/Source/SPQueryController.m
+++ b/Source/SPQueryController.m
@@ -778,7 +778,7 @@ static SPQueryController *sharedQueryController = nil;
{
messagesVisibleSet = nil;
[NSObject cancelPreviousPerformRequestsWithTarget:self];
-
+
[dateFormatter release], dateFormatter = nil;
[messagesFullSet release], messagesFullSet = nil;
@@ -948,9 +948,9 @@ static SPQueryController *sharedQueryController = nil;
if (!error) {
messageTemp = [messageTemp stringByAppendingString:@";"];
}
-
+
SPConsoleMessage *consoleMessage = [SPConsoleMessage consoleMessageWithMessage:messageTemp date:[NSDate date] connection:connection];
-
+
[consoleMessage setIsError:error];
[messagesFullSet addObject:consoleMessage];
diff --git a/Source/SPSQLParser.m b/Source/SPSQLParser.m
index f8112767..fab0ab7f 100644
--- a/Source/SPSQLParser.m
+++ b/Source/SPSQLParser.m
@@ -915,4 +915,4 @@ TO_BUFFER_STATE to_scan_string (const char *);
[super dealloc];
}
-@end
+@end \ No newline at end of file
diff --git a/Source/SPTableCopy.h b/Source/SPTableCopy.h
deleted file mode 100644
index 37ed452a..00000000
--- a/Source/SPTableCopy.h
+++ /dev/null
@@ -1,61 +0,0 @@
-//
-// $Id$
-//
-// SPTableCopy.h
-// sequel-pro
-//
-// Created by David Rekowski on Apr 13, 2010
-//
-// This program is free software; you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation; either version 2 of the License, or
-// (at your option) any later version.
-//
-// This program is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU General Public License
-// along with this program; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//
-// More info at <http://code.google.com/p/sequel-pro/>
-
-#import "SPDBActionCommons.h"
-
-/**
- * The SPTableCopy class povides functionality to copy tables between databases.
- */
-@interface SPTableCopy : SPDBActionCommons {
-}
-
-/**
- * This method copies a table structure from one db to another.
- *
- * @param name name of the table in the source database
- * @param sourceDB name of the source database
- * @param targetDB name of the target database
- */
-- (BOOL)copyTable:(NSString *)name from: (NSString *)sourceDB to: (NSString *)targetDB;
-
-/**
- * This method moves a table from one db to another.
- *
- * @param name name of the table in the source database
- * @param sourceDB name of the source database
- * @param targetDB name of the target database
- */
-- (BOOL)moveTable:(NSString *)name from: (NSString *)sourceDB to: (NSString *)targetDB;
-
-/**
- * This method copies a table including its data from one db to another.
- *
- * @param name name of the table in the source database
- * @param sourceDB name of the source database
- * @param targetDB name of the target database
- * @param copyWithContent whether to copy the content too, otherwise only structure
- */
-- (BOOL)copyTable:(NSString *)tableName from: (NSString *)sourceDB to: (NSString *)targetDB withContent:(BOOL)copyWithContent;
-
-@end
diff --git a/Source/SPTableCopy.m b/Source/SPTableCopy.m
deleted file mode 100644
index ab485b60..00000000
--- a/Source/SPTableCopy.m
+++ /dev/null
@@ -1,139 +0,0 @@
-//
-// $Id$
-//
-// SPTableCopy.m
-// sequel-pro
-//
-// Created by David Rekowski on Apr 13, 2010
-//
-// This program is free software; you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation; either version 2 of the License, or
-// (at your option) any later version.
-//
-// This program is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU General Public License
-// along with this program; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//
-// More info at <http://code.google.com/p/sequel-pro/>
-
-#import "SPDBActionCommons.h"
-#import "SPTableCopy.h"
-
-@implementation SPTableCopy
-
-- (NSString *)getCreateTableStatementFor: (NSString *)tableName inDB: (NSString *)sourceDB {
- NSString *showCreateTableStatment = [NSString stringWithFormat:@"SHOW CREATE TABLE %@.%@",
- [sourceDB backtickQuotedString],
- [tableName backtickQuotedString]
- ];
- MCPResult *theResult = [connection queryString:showCreateTableStatment];
-
- if ([connection queryErrored]) {
- SPBeginAlertSheet(NSLocalizedString(@"Failed to show create table statement", @"show create table error message"),
- NSLocalizedString(@"OK", @"OK button"), nil, nil, messageWindow, self, nil, nil, nil,
- [NSString stringWithFormat:NSLocalizedString(@"An error occured while trying to retrieve the create table statement for a table.\n\nMySQL said: %@",
- @"show create table error informative message"),
- [connection getLastErrorMessage]]);
- }
- if ([theResult numOfRows] != 0) {
- return [[theResult fetchRowAsArray] objectAtIndex:1];
- }
- return @"";
-}
-
-- (BOOL)copyTable:(NSString *)tableName from: (NSString *)sourceDB to: (NSString *)targetDB {
-
- NSString *createTableResult = [self getCreateTableStatementFor:tableName inDB:sourceDB];
- NSMutableString *createTableStatement = [[NSMutableString alloc] initWithString:createTableResult];
-
- // adding the target DB name and the separator dot after "CREATE TABLE ".
- [createTableStatement insertString:@"." atIndex:13];
- [createTableStatement insertString:[targetDB backtickQuotedString] atIndex:13];
- /*
- // this only works with MySQL >= 4.1
- NSString *copyStatement = [NSString stringWithFormat:@"CREATE TABLE %@.%@ LIKE %@.%@",
- [targetDB backtickQuotedString],
- [tableName backtickQuotedString],
- [sourceDB backtickQuotedString],
- [tableName backtickQuotedString]
- ];
- DLog(@"Copying table %@ from %@ to %@", tableName, sourceDB, targetDB);
- DLog(@"Copying table: %@", copyStatement);
- [connection queryString:copyStatement];
- */
-
- [connection queryString:createTableStatement];
- [createTableStatement release];
-
-
- if ([connection queryErrored]) {
- SPBeginAlertSheet(NSLocalizedString(@"Failed to copy table", @"copy table error message"),
- NSLocalizedString(@"OK", @"OK button"), nil, nil, messageWindow, self, nil, nil, nil,
- [NSString stringWithFormat:NSLocalizedString(@"An error occured while trying to copy a table.\n\nMySQL said: %@",
- @"copy table error informative message"),
- [connection getLastErrorMessage]]);
- return NO;
- }
- return YES;
-}
-
-- (BOOL)copyTable:(NSString *)tableName from: (NSString *)sourceDB to: (NSString *)targetDB withContent:(BOOL)copyWithContent{
- // copy the table structure
- BOOL structureCopyResult = [self copyTable:tableName from:sourceDB to:targetDB];
-
- // optionally copy the table data using an insert select
- if (copyWithContent == YES) {
- NSString *copyDataStatement = [NSString stringWithFormat:@"INSERT INTO %@.%@ SELECT * FROM %@.%@",
- [targetDB backtickQuotedString],
- [tableName backtickQuotedString],
- [sourceDB backtickQuotedString],
- [tableName backtickQuotedString]
- ];
- [connection queryString:copyDataStatement];
-
- if ([connection queryErrored]) {
- SPBeginAlertSheet(NSLocalizedString(@"Failed to copy table data", @"copy table data error message"),
- NSLocalizedString(@"OK", @"OK button"), nil, nil, [self getTableWindow], self, nil, nil, nil,
- [NSString stringWithFormat:NSLocalizedString(@"An error occured while trying to copy a table's data.\n\nMySQL said: %@",
- @"copy table data error informative message"),
- [connection getLastErrorMessage]]);
- return NO;
- }
- return YES;
-
- }
- return structureCopyResult;
-}
-
-- (BOOL)moveTable:(NSString *)tableName from: (NSString *)sourceDB to: (NSString *)targetDB {
-
- NSString *moveStatement = [NSString stringWithFormat:@"RENAME TABLE %@.%@ TO %@.%@",
- [sourceDB backtickQuotedString],
- [tableName backtickQuotedString],
- [targetDB backtickQuotedString],
- [tableName backtickQuotedString]
- ];
- // moving the table
- DLog(@"Moving table %@ from %@ to %@", tableName, sourceDB, targetDB);
- DLog(@"Moving table: %@", moveStatement);
- [connection queryString:moveStatement];
-
- if ([connection queryErrored]) {
- SPBeginAlertSheet(NSLocalizedString(@"Failed to move table", @"move table error message"),
- NSLocalizedString(@"OK", @"OK button"), nil, nil, [self getTableWindow], self, nil, nil, nil,
- [NSString stringWithFormat:NSLocalizedString(@"An error occured while trying to move a table.\n\nMySQL said: %@",
- @"move table error informative message"),
- [connection getLastErrorMessage]]);
- return NO;
- }
- return YES;
-}
-
-
-@end
diff --git a/Source/SPTableData.h b/Source/SPTableData.h
index 88b0a78f..a63f31dc 100644
--- a/Source/SPTableData.h
+++ b/Source/SPTableData.h
@@ -64,7 +64,6 @@
- (BOOL) updateInformationForCurrentView;
- (NSDictionary *) informationForView:(NSString *)viewName;
- (BOOL) updateStatusInformationForCurrentTable;
-- (BOOL) updateTriggersForCurrentTable;
- (NSDictionary *) parseFieldDefinitionStringParts:(NSArray *)definitionParts;
- (NSArray *) primaryKeyColumnNames;
diff --git a/Source/SPTableData.m b/Source/SPTableData.m
index ab1857f6..51d490d9 100644
--- a/Source/SPTableData.m
+++ b/Source/SPTableData.m
@@ -42,8 +42,8 @@
columnNames = [[NSMutableArray alloc] init];
constraints = [[NSMutableArray alloc] init];
status = [[NSMutableDictionary alloc] init];
-
- triggers = nil;
+ triggers = [[NSMutableArray alloc] init];
+
tableEncoding = nil;
tableCreateSyntax = nil;
mySQLConnection = nil;
@@ -121,19 +121,6 @@
- (NSArray *) triggers
{
-
- // If triggers is nil, the triggers need to be loaded - if a table is selected on MySQL >= 5.0.2
- if (!triggers) {
- if ([tableListInstance tableType] == SPTableTypeTable
- && [mySQLConnection serverMajorVersion] >= 5
- && [mySQLConnection serverMinorVersion] >= 0)
- {
- [self updateTriggersForCurrentTable];
- } else {
- return [NSArray array];
- }
- }
-
return (NSArray *)triggers;
}
@@ -247,11 +234,6 @@
[columnNames removeAllObjects];
[status removeAllObjects];
- if (triggers != nil) {
- [triggers release];
- triggers = nil;
- }
-
if (tableEncoding != nil) {
[tableEncoding release];
tableEncoding = nil;
@@ -626,12 +608,39 @@
[createTableParser release];
[fieldParser release];
+ // Triggers
+ theResult = [mySQLConnection queryString:[NSString stringWithFormat:@"/*!50003 SHOW TRIGGERS WHERE `Table` = %@ */",
+ [tableName tickQuotedString]]];
+ [theResult setReturnDataAsStrings:YES];
+
+ // Check for any errors, but only display them if a connection still exists
+ if ([mySQLConnection queryErrored]) {
+ if ([mySQLConnection isConnected]) {
+ SPBeginAlertSheet(NSLocalizedString(@"Error retrieving table information", @"error retrieving table information message"), NSLocalizedString(@"OK", @"OK button"),
+ nil, nil, [NSApp mainWindow], self, nil, nil, nil,
+ [NSString stringWithFormat:NSLocalizedString(@"An error occurred while retrieving the information for table '%@'. Please try again.\n\nMySQL said: %@", @"error retrieving table information informative message"),
+ tableName, [mySQLConnection getLastErrorMessage]]);
+ }
+ [tableColumns release];
+ if (encodingString) [encodingString release];
+
+ return nil;
+ }
+
+ [triggers removeAllObjects];
+ if( [theResult numOfRows] ) {
+ for(i=0; i<[theResult numOfRows]; i++){
+ [triggers addObject:[theResult fetchRowAsDictionary]];
+ }
+ }
+
// this will be 'Table' or 'View'
[tableData setObject:[resultFieldNames objectAtIndex:0] forKey:@"type"];
[tableData setObject:[NSString stringWithString:encodingString] forKey:@"encoding"];
[tableData setObject:[NSArray arrayWithArray:tableColumns] forKey:@"columns"];
[tableData setObject:[NSArray arrayWithArray:constraints] forKey:@"constraints"];
+ [tableData setObject:[NSArray arrayWithArray:triggers] forKey:@"triggers"];
[encodingString release];
[tableColumns release];
@@ -869,36 +878,6 @@
return TRUE;
}
-/**
- * Retrieve the triggers for the current table and add to local cache for reuse.
- */
-- (BOOL) updateTriggersForCurrentTable
-{
- MCPResult *theResult = [mySQLConnection queryString:[NSString stringWithFormat:@"/*!50003 SHOW TRIGGERS WHERE `Table` = %@ */",
- [[tableListInstance tableName] tickQuotedString]]];
- [theResult setReturnDataAsStrings:YES];
-
- // Check for any errors, but only display them if a connection still exists
- if ([mySQLConnection queryErrored]) {
- if ([mySQLConnection isConnected]) {
- SPBeginAlertSheet(NSLocalizedString(@"Error retrieving trigger information", @"error retrieving trigger information message"), NSLocalizedString(@"OK", @"OK button"),
- nil, nil, [NSApp mainWindow], self, nil, nil, nil,
- [NSString stringWithFormat:NSLocalizedString(@"An error occurred while retrieving the trigger information for table '%@'. Please try again.\n\nMySQL said: %@", @"error retrieving table information informative message"),
- [tableListInstance tableName], [mySQLConnection getLastErrorMessage]]);
- if (triggers) [triggers release], triggers = nil;
- }
-
- return NO;
- }
-
- if (triggers) [triggers release];
- triggers = [[NSMutableArray alloc] init];
- for (int i=0; i<[theResult numOfRows]; i++) {
- [triggers addObject:[theResult fetchRowAsDictionary]];
- }
-
- return YES;
-}
/*
* Parse an array of field definition parts - not including name but including type and optionally unsigned/zerofill/null
@@ -1143,9 +1122,9 @@
[columns release];
[columnNames release];
[constraints release];
+ [triggers release];
[status release];
- if (triggers) [triggers release];
if (tableEncoding) [tableEncoding release];
if (tableCreateSyntax) [tableCreateSyntax release];
if (mySQLConnection) [mySQLConnection release];
diff --git a/Source/SPTableRelations.m b/Source/SPTableRelations.m
index 7baa8702..01fec02e 100644
--- a/Source/SPTableRelations.m
+++ b/Source/SPTableRelations.m
@@ -403,10 +403,10 @@
if ([connection queryErrored]) {
- SPBeginAlertSheet(NSLocalizedString(@"Unable to delete relation", @"error deleting relation message"),
+ SPBeginAlertSheet(NSLocalizedString(@"Unable to remove relation", @"error removing relation message"),
NSLocalizedString(@"OK", @"OK button"),
nil, nil, [NSApp mainWindow], nil, nil, nil, nil,
- [NSString stringWithFormat:NSLocalizedString(@"The selected relation couldn't be deleted.\n\nMySQL said: %@", @"error deleting relation informative message"), [connection getLastErrorMessage]]);
+ [NSString stringWithFormat:NSLocalizedString(@"The selected relation couldn't be removed.\n\nMySQL said: %@", @"error removing relation informative message"), [connection getLastErrorMessage]]);
// Abort loop
break;
@@ -498,7 +498,7 @@
[constraint objectForKey:@"ref_table"], @"fk_table",
[constraint objectForKey:@"ref_columns"], @"fk_columns",
([constraint objectForKey:@"update"] ? [constraint objectForKey:@"update"] : @""), @"on_update",
- ([constraint objectForKey:@"delete"] ? [constraint objectForKey:@"delete"] : @""), @"on_delete",
+ ([constraint objectForKey:@"delete"] ? [constraint objectForKey:@"delete"] : @""), @"on_delete",
nil]];
}
diff --git a/Source/SPTableTriggers.h b/Source/SPTableTriggers.h
index 8e97908a..d492253b 100644
--- a/Source/SPTableTriggers.h
+++ b/Source/SPTableTriggers.h
@@ -57,8 +57,6 @@
@property (readwrite, assign) MCPConnection *connection;
-- (void)loadTriggers;
-
// IB action methods
- (IBAction)addTrigger:(id)sender;
- (IBAction)removeTrigger:(id)sender;
diff --git a/Source/SPTableTriggers.m b/Source/SPTableTriggers.m
index c202e9c9..5c4f13ad 100644
--- a/Source/SPTableTriggers.m
+++ b/Source/SPTableTriggers.m
@@ -77,7 +77,12 @@
selector:@selector(triggerStatementTextDidChange:)
name:NSTextStorageDidProcessEditingNotification
object:[triggerStatementTextView textStorage]];
-
+
+ [[NSNotificationCenter defaultCenter] addObserver:self
+ selector:@selector(tableSelectionChanged:)
+ name:SPTableChangedNotification
+ object:tableDocumentInstance];
+
// Add observers for document task activity
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(startDocumentTaskForTab:)
@@ -89,46 +94,6 @@
object:tableDocumentInstance];
}
-/**
- * Called whenever the user selects the triggers tab for the first time,
- * or switches between tables with the triggers tab active.
- */
-- (void)loadTriggers
-{
- BOOL enableInteraction = ((![[tableDocumentInstance selectedToolbarItemIdentifier] isEqualToString:SPMainToolbarTableTriggers]) || (![tableDocumentInstance isWorking]));
-
- // Disable all interface elements by default
- [addTriggerButton setEnabled:NO];
- [refreshTriggersButton setEnabled:NO];
- [triggersTableView setEnabled:NO];
- [labelTextField setStringValue:@""];
-
- // Show a warning if the version of MySQL is too low to support triggers
- if ([connection serverMajorVersion] < 5
- || ([connection serverMajorVersion] == 5
- && [connection serverMinorVersion] == 0
- && [connection serverReleaseVersion] < 2))
- {
- [labelTextField setStringValue:NSLocalizedString(@"This version of MySQL does not support triggers. Support for triggers was added in MySQL 5.0.2", @"triggers not supported label")];
- return;
- }
-
- // If no item is selected, or the item selected is not a table, return.
- if (![tablesListInstance tableName] || [tablesListInstance tableType] != SPTableTypeTable)
- return;
-
- // Update the text label
- [labelTextField setStringValue:[NSString stringWithFormat:NSLocalizedString(@"Triggers for table: %@", @"triggers for table label"), [tablesListInstance tableName]]];
-
- // Enable interface elements
- [addTriggerButton setEnabled:enableInteraction];
- [refreshTriggersButton setEnabled:enableInteraction];
- [triggersTableView setEnabled:YES];
-
- // Ensure trigger data is loaded
- [self _refreshTriggerDataForcingCacheRefresh:NO];
-}
-
#pragma mark -
#pragma mark IB action methods
@@ -220,6 +185,49 @@
[self _refreshTriggerDataForcingCacheRefresh:YES];
}
+/**
+ * Called whenever the user selects a different table.
+ */
+- (void)tableSelectionChanged:(NSNotification *)notification
+{
+ BOOL enableInteraction = ((![[tableDocumentInstance selectedToolbarItemIdentifier] isEqualToString:SPMainToolbarTableTriggers]) || (![tableDocumentInstance isWorking]));
+
+ // To begin enable all interface elements
+ [addTriggerButton setEnabled:enableInteraction];
+ [refreshTriggersButton setEnabled:enableInteraction];
+ [triggersTableView setEnabled:YES];
+
+ if (([connection serverMajorVersion] >= 5) &&
+ ([connection serverMinorVersion] >= 0) &&
+ ([connection serverReleaseVersion] >= 2)) {
+
+ // Update the text label
+ [labelTextField setStringValue:[NSString stringWithFormat:NSLocalizedString(@"Triggers for table: %@", @"triggers for table label"), [tablesListInstance tableName]]];
+
+ [addTriggerButton setEnabled:enableInteraction];
+ [refreshTriggersButton setEnabled:enableInteraction];
+ [triggersTableView setEnabled:YES];
+
+ [self _refreshTriggerDataForcingCacheRefresh:NO];
+ }
+ else {
+ [addTriggerButton setEnabled:NO];
+ [refreshTriggersButton setEnabled:NO];
+ [triggersTableView setEnabled:NO];
+
+ [labelTextField setStringValue:NSLocalizedString(@"This version of MySQL does not support triggers. Support for triggers was added in MySQL 5.0.2", @"triggers not supported label")];
+ }
+
+ // If a proc or function is selected disable everything.
+ if (([tablesListInstance tableType] == SPTableTypeProc) || ([tablesListInstance tableType] == SPTableTypeFunc)) {
+ [addTriggerButton setEnabled:NO];
+ [refreshTriggersButton setEnabled:NO];
+ [triggersTableView setEnabled:NO];
+
+ [labelTextField setStringValue:@""];
+ }
+}
+
#pragma mark -
#pragma mark Tableview datasource methods
@@ -320,10 +328,10 @@
if ([connection queryErrored]) {
- SPBeginAlertSheet(NSLocalizedString(@"Unable to delete trigger", @"error deleting trigger message"),
+ SPBeginAlertSheet(NSLocalizedString(@"Unable to remove trigger", @"error removing trigger message"),
NSLocalizedString(@"OK", @"OK button"),
nil, nil, [NSApp mainWindow], nil, nil, nil, nil,
- [NSString stringWithFormat:NSLocalizedString(@"The selected trigger couldn't be deleted.\n\nMySQL said: %@", @"error deleting trigger informative message"), [connection getLastErrorMessage]]);
+ [NSString stringWithFormat:NSLocalizedString(@"The selected trigger couldn't be removed.\n\nMySQL said: %@", @"error removing trigger informative message"), [connection getLastErrorMessage]]);
// Abort loop
break;
@@ -471,10 +479,7 @@
if ([tablesListInstance tableType] == SPTableTypeTable) {
- if (clearAllCaches) {
- [tableDataInstance resetAllData];
- [tableDataInstance updateTriggersForCurrentTable];
- }
+ if (clearAllCaches) [tableDataInstance updateInformationForCurrentTable];
NSArray *triggers = [tableDataInstance triggers];
diff --git a/Source/SPUserManager.h b/Source/SPUserManager.h
index e6eedf50..27590274 100644
--- a/Source/SPUserManager.h
+++ b/Source/SPUserManager.h
@@ -27,7 +27,7 @@
@class BWAnchoredButtonBar;
-@interface SPUserManager : NSWindowController
+@interface SPUserManager : NSWindowController
{
NSPersistentStoreCoordinator *persistentStoreCoordinator;
NSManagedObjectModel *managedObjectModel;
diff --git a/Source/SPUserManager.m b/Source/SPUserManager.m
index 6594d75f..90cc426d 100644
--- a/Source/SPUserManager.m
+++ b/Source/SPUserManager.m
@@ -181,7 +181,7 @@
* it's data from the SPUser Entity objects in the current managedObjectContext.
*/
- (void)_initializeTree:(NSArray *)items
-{
+{
// Go through each item that contains a dictionary of key-value pairs
// for each user currently in the database.
for(NSInteger i = 0; i < [items count]; i++)
@@ -269,14 +269,14 @@
{
// Initialize Databases
[schemas removeAllObjects];
-
+
MCPResult *results = [self.mySqlConnection listDBs];
if ([results numOfRows]) {
[results dataSeek:0];
}
- for (NSInteger i = 0; i < [results numOfRows]; i++) {
+ for (int i = 0; i < [results numOfRows]; i++) {
[schemas addObject:[results fetchRowAsDictionary]];
}
@@ -333,7 +333,7 @@
// Assumes that the child has already been initialized with values from the
// global user table.
// Select rows from the db table that contains schema privs for each user/host
- NSString *queryString = [NSString stringWithFormat:@"SELECT * from `mysql`.`db` d WHERE d.user = %@ and d.host = %@",
+ NSString *queryString = [NSString stringWithFormat:@"SELECT * from `mysql`.`db` d WHERE d.user = %@ and d.host = %@",
[[[child parent] valueForKey:@"user"] tickQuotedString], [[child valueForKey:@"host"] tickQuotedString]];
MCPResult *queryResults = [self.mySqlConnection queryString:queryString];
if ([queryResults numOfRows] > 0)
@@ -342,7 +342,7 @@
[queryResults dataSeek:0];
}
- for (NSInteger i = 0; i < [queryResults numOfRows]; i++) {
+ for (int i = 0; i < [queryResults numOfRows]; i++) {
NSDictionary *rowDict = [queryResults fetchRowAsDictionary];
NSManagedObject *dbPriv = [NSEntityDescription insertNewObjectForEntityForName:@"Privileges"
inManagedObjectContext:[self managedObjectContext]];
@@ -643,6 +643,7 @@
NSArray *children = [[[treeController selectedObjects] objectAtIndex:0]
valueForKey:@"children"];
+
// On all the children - host entries - set the username to be deleted,
// for later query contruction.
for(NSManagedObject *child in children)
@@ -761,17 +762,17 @@
[treeController fetch:nil];
// After the reset, ensure all original password and user values are up-to-date.
- NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"SPUser"
- inManagedObjectContext:self.managedObjectContext];
- NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
- [request setEntity:entityDescription];
- NSArray *userArray = [self.managedObjectContext executeFetchRequest:request error:nil];
- for (NSManagedObject *user in userArray) {
- if (![user parent]) {
- [user setValue:[user valueForKey:@"user"] forKey:@"originaluser"];
- [user setValue:[user valueForKey:@"password"] forKey:@"originalpassword"];
- }
- }
+ NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"SPUser"
+ inManagedObjectContext:self.managedObjectContext];
+ NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
+ [request setEntity:entityDescription];
+ NSArray *userArray = [self.managedObjectContext executeFetchRequest:request error:nil];
+ for (NSManagedObject *user in userArray) {
+ if (![user parent]) {
+ [user setValue:[user valueForKey:@"user"] forKey:@"originaluser"];
+ [user setValue:[user valueForKey:@"password"] forKey:@"originalpassword"];
+ }
+ }
}
- (void)_setSchemaPrivValues:(NSArray *)objects enabled:(BOOL)enabled
@@ -975,7 +976,7 @@
- (BOOL)deleteUsers:(NSArray *)deletedUsers
{
NSMutableString *droppedUsers = [NSMutableString string];
-
+
for (NSManagedObject *user in deletedUsers)
{
if (![[[user entity] name] isEqualToString:@"Privileges"] && [user valueForKey:@"host"] != nil)
@@ -986,7 +987,7 @@
}
}
-
+
droppedUsers = [[droppedUsers substringToIndex:[droppedUsers length]-2] mutableCopy];
[self.mySqlConnection queryString:[NSString stringWithFormat:@"DROP USER %@", droppedUsers]];
[droppedUsers release];
@@ -1351,9 +1352,9 @@
- (void)tabView:(NSTabView *)usersTabView willSelectTabViewItem:(NSTabViewItem *)tabViewItem
{
- if ([[tabViewItem identifier] isEqualToString:@"Schema Privileges"]) {
- [self _initializeSchemaPrivs];
- }
+ if ([[tabViewItem identifier] isEqualToString:@"Schema Privileges"]) {
+ [self _initializeSchemaPrivs];
+ }
}
#pragma mark -
diff --git a/Source/TableContent.m b/Source/TableContent.m
index b78a6423..90fbe5d1 100644
--- a/Source/TableContent.m
+++ b/Source/TableContent.m
@@ -546,9 +546,13 @@
*/
- (void) loadTableValues
{
+
// If no table is selected, return
if (!selectedTable) return;
+ // Wrap the values load in an autorelease pool to ensure full and timely release
+ NSAutoreleasePool *loadPool = [[NSAutoreleasePool alloc] init];
+
NSMutableString *queryString;
NSString *queryStringBeforeLimit = nil;
NSString *filterString;
@@ -669,6 +673,8 @@
// Trigger a full reload if required
if (fullTableReloadRequired) [self reloadTable:self];
+
+ [loadPool drain];
}
/*
@@ -760,13 +766,9 @@
pthread_mutex_unlock(&tableValuesLock);
}
- // Ensure the table is aware of changes
- if ([NSThread isMainThread]) {
- [tableContentView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
- } else {
- [tableContentView performSelectorOnMainThread:@selector(noteNumberOfRowsChanged) withObject:nil waitUntilDone:YES];
- [tableContentView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:NO];
- }
+ // Ensure the table is aware of changes, especially for non-threaded loads
+ [tableContentView performSelectorOnMainThread:@selector(noteNumberOfRowsChanged) withObject:nil waitUntilDone:YES];
+ [tableContentView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:NO];
// Clean up the autorelease pool and reset the progress indicator
[dataLoadingPool drain];
@@ -1351,11 +1353,11 @@
[tempRow replaceObjectAtIndex:i withObject:[dbDataRow objectAtIndex:i]];
}
}
-
+
//insert the copied row
[tableValues insertRowContents:tempRow atIndex:[tableContentView selectedRow]+1];
tableRowsCount++;
-
+
//select row and go in edit mode
[tableContentView reloadData];
[tableContentView selectRowIndexes:[NSIndexSet indexSetWithIndex:[tableContentView selectedRow]+1] byExtendingSelection:NO];
@@ -1372,13 +1374,12 @@
- (IBAction)removeRow:(id)sender
{
// Check whether a save of the current row is required.
- // if (![self saveRowOnDeselect])
+ //if (![self saveRowOnDeselect])
// return;
// cancel editing (maybe this is not the ideal method -- see xcode docs for that method)
[tableWindow endEditingFor:nil];
-
if (![tableContentView numberOfSelectedRows])
return;
@@ -1972,13 +1973,14 @@
*/
- (BOOL)saveRowOnDeselect
{
- // Save any edits which have been made but not saved to the table yet.
- [tableWindow endEditingFor:nil];
// If no rows are currently being edited, or a save is in progress, return success at once.
if (!isEditingRow || isSavingRow) return YES;
isSavingRow = YES;
+ // Save any edits which have been made but not saved to the table yet.
+ [tableWindow endEditingFor:nil];
+
// Attempt to save the row, and return YES if the save succeeded.
if ([self addRowToDB]) {
isSavingRow = NO;
@@ -2164,17 +2166,16 @@
currentlyEditingRow = -1;
}
[tableContentView reloadData];
- } else if ( [contextInfo isEqualToString:@"removeallrows"] ) {
+ } else if ( [contextInfo isEqualToString:@"removeallrows"] ) {
if ( returnCode == NSAlertDefaultReturn ) {
//check if the user is currently editing a row
if (isEditingRow) {
//cancel the edit
isEditingRow = NO;
// in case the delete fails, make sure we at least stay in a somewhat consistent state
- [tableValues replaceRowAtIndex:currentlyEditingRow withRowContents:oldRow];
- currentlyEditingRow = -1;
+ [tableValues replaceRowAtIndex:currentlyEditingRow withRowContents:oldRow];
+ currentlyEditingRow = -1;
}
-
[mySQLConnection queryString:[NSString stringWithFormat:@"DELETE FROM %@", [selectedTable backtickQuotedString]]];
if ( ![mySQLConnection queryErrored] ) {
@@ -2187,7 +2188,7 @@
} else {
[self performSelector:@selector(showErrorSheetWith:)
withObject:[NSArray arrayWithObjects:NSLocalizedString(@"Error", @"error"),
- [NSString stringWithFormat:NSLocalizedString(@"Couldn't delete rows.\n\nMySQL said: %@", @"message when deleteing all rows failed"),
+ [NSString stringWithFormat:NSLocalizedString(@"Couldn't remove rows.\n\nMySQL said: %@", @"message of panel when field cannot be removed"),
[mySQLConnection getLastErrorMessage]],
nil]
afterDelay:0.3];
@@ -2197,40 +2198,40 @@
if ( returnCode == NSAlertDefaultReturn ) {
[selectedRows addIndexes:[tableContentView selectedRowIndexes]];
- //check if the user is currently editing a row
- if (isEditingRow) {
- //make sure that only one row is selected. This should never happen
- if ([selectedRows count]!=1) {
- NSLog(@"Expected only one selected row, but found %d",[selectedRows count]);
- }
- // this code is pretty much taken from the escape key handler
- if ( isEditingNewRow ) {
- // since the user is currently editing a new row, we don't actually have to delete any rows from the database
- // we just have to remove the row from the view (and the store)
- isEditingRow = NO;
- isEditingNewRow = NO;
- tableRowsCount--;
- [tableValues removeRowAtIndex:currentlyEditingRow];
- currentlyEditingRow = -1;
- [self updateCountText];
- [tableContentView reloadData];
-
- //deselect the row
- [tableContentView selectRowIndexes:[NSIndexSet indexSet] byExtendingSelection:NO];
-
- // we also don't have to reload the table, since no query went to the database
- return;
- } else {
- //cancel the edit
- isEditingRow = NO;
- // in case the delete fails, make sure we at least stay in a somewhat consistent state
- [tableValues replaceRowAtIndex:currentlyEditingRow withRowContents:oldRow];
- currentlyEditingRow = -1;
- }
-
- }
+ //check if the user is currently editing a row
+ if (isEditingRow) {
+ //make sure that only one row is selected. This should never happen
+ if ([selectedRows count]!=1) {
+ NSLog(@"Expected only one selected row, but found %d",[selectedRows count]);
+ }
+ // this code is pretty much taken from the escape key handler
+ if ( isEditingNewRow ) {
+ // since the user is currently editing a new row, we don't actually have to delete any rows from the database
+ // we just have to remove the row from the view (and the store)
+ isEditingRow = NO;
+ isEditingNewRow = NO;
+ tableRowsCount--;
+ [tableValues removeRowAtIndex:currentlyEditingRow];
+ currentlyEditingRow = -1;
+ [self updateCountText];
+ [tableContentView reloadData];
+
+ //deselect the row
+ [tableContentView selectRowIndexes:[NSIndexSet indexSet] byExtendingSelection:NO];
+
+ // we also don't have to reload the table, since no query went to the database
+ return;
+ } else {
+ //cancel the edit
+ isEditingRow = NO;
+ // in case the delete fails, make sure we at least stay in a somewhat consistent state
+ [tableValues replaceRowAtIndex:currentlyEditingRow withRowContents:oldRow];
+ currentlyEditingRow = -1;
+ }
+
+ }
[tableContentView selectRowIndexes:[NSIndexSet indexSet] byExtendingSelection:NO];
-
+
errors = 0;
// Disable updating of the Console Log window for large number of queries
@@ -2334,7 +2335,7 @@
// Remember affected rows for error checking
affectedRows += [mySQLConnection affectedRows];
}
-
+
errors = (affectedRows > 0) ? [selectedRows count] - affectedRows : [selectedRows count];
} else {
// if table has more than one PRIMARY KEY
@@ -2390,32 +2391,32 @@
// Remember affected rows for error checking
affectedRows += [mySQLConnection affectedRows];
}
-
+
errors = (affectedRows > 0) ? [selectedRows count] - affectedRows : [selectedRows count];
}
-
+
// Restore Console Log window's updating bahaviour
[[SPQueryController sharedQueryController] setAllowConsoleUpdate:consoleUpdateStatus];
-
+
if (errors) {
NSArray *message;
//TODO: The following three messages are NOT localisable!
if (errors < 0) {
message = [NSArray arrayWithObjects:NSLocalizedString(@"Warning", @"warning"),
- [NSString stringWithFormat:NSLocalizedString(@"%ld row%@ more %@ deleted! Please check the Console and inform the Sequel Pro team!", @"message of panel when more rows were deleted"), (long)(errors*-1), ((errors*-1)>1)?@"s":@"", (errors>1)?@"were":@"was"],
+ [NSString stringWithFormat:NSLocalizedString(@"%ld row%@ more %@ removed! Please check the Console and inform the Sequel Pro team!", @"message of panel when more rows were deleted"), (long)(errors*-1), ((errors*-1)>1)?@"s":@"", (errors>1)?@"were":@"was"],
nil];
- }
+ }
else {
if (primaryKeyFieldNames == nil)
message = [NSArray arrayWithObjects:NSLocalizedString(@"Warning", @"warning"),
- [NSString stringWithFormat:NSLocalizedString(@"%ld row%@ ha%@ not been deleted. Reload the table to be sure that the rows exist and use a primary key for your table.", @"message of panel when not all selected fields have been deleted"), (long)errors, (errors>1)?@"s":@"", (errors>1)?@"ve":@"s"],
+ [NSString stringWithFormat:NSLocalizedString(@"%ld row%@ ha%@ not been removed. Reload the table to be sure that the rows exist and use a primary key for your table.", @"message of panel when not all selected fields have been deleted"), (long)errors, (errors>1)?@"s":@"", (errors>1)?@"ve":@"s"],
nil];
else
message = [NSArray arrayWithObjects:NSLocalizedString(@"Warning", @"warning"),
- [NSString stringWithFormat:NSLocalizedString(@"%ld row%@ ha%@ not been deleted. Reload the table to be sure that the rows exist and check the Console for possible errors inside the primary key%@ for your table.", @"message of panel when not all selected fields have been deleted by using primary keys"), (long)errors, (errors>1)?@"s":@"", (errors>1)?@"ve":@"s", (errors>1)?@"s":@""],
+ [NSString stringWithFormat:NSLocalizedString(@"%ld row%@ ha%@ not been removed. Reload the table to be sure that the rows exist and check the Console for possible errors inside the primary key%@ for your table.", @"message of panel when not all selected fields have been deleted by using primary keys"), (long)errors, (errors>1)?@"s":@"", (errors>1)?@"ve":@"s", (errors>1)?@"s":@""],
nil];
}
-
+
[self performSelector:@selector(showErrorSheetWith:)
withObject:message
afterDelay:0.3];
@@ -2437,7 +2438,6 @@
// The user clicked cancel in the "sure you wanna delete" message
// restore editing or whatever
}
-
}
}
@@ -3186,7 +3186,7 @@
#pragma mark Other methods
/*
- * Trap the enter, escape, tab and arrow keys, overriding default behaviour and continuing/ending editing,
+ * Trap the enter and escape keys, overriding default behaviour and continuing/ending editing,
* only within the current row.
*/
- (BOOL)control:(NSControl *)control textView:(NSTextView *)textView doCommandBySelector:(SEL)command
@@ -3197,8 +3197,9 @@
row = [tableContentView editedRow];
column = [tableContentView editedColumn];
- // Trap tab key
- if ( [textView methodForSelector:command] == [textView methodForSelector:@selector(insertTab:)] )
+ // Trap enter and tab keys
+ if ( [textView methodForSelector:command] == [textView methodForSelector:@selector(insertNewline:)] ||
+ [textView methodForSelector:command] == [textView methodForSelector:@selector(insertTab:)] )
{
[[control window] makeFirstResponder:control];
@@ -3227,49 +3228,7 @@
}
return TRUE;
}
-
- // Trap enter key
- else if ( [textView methodForSelector:command] == [textView methodForSelector:@selector(insertNewline:)] )
- {
- [[control window] makeFirstResponder:control];
- [self addRowToDB];
- return TRUE;
- }
-
- // Trap down arrow key
- else if ( [textView methodForSelector:command] == [textView methodForSelector:@selector(moveDown:)] )
- {
- NSUInteger newRow = row+1;
- if (newRow>=tableRowsCount) return TRUE; //check if we're already at the end of the list
-
- [[control window] makeFirstResponder:control];
- [self addRowToDB];
-
- if (newRow>=tableRowsCount) return TRUE; //check again. addRowToDB could reload the table and change the number of rows
- if (column>=[tableValues columnCount]) return TRUE; //the column count could change too
-
- [tableContentView selectRowIndexes:[NSIndexSet indexSetWithIndex:newRow] byExtendingSelection:NO];
- [tableContentView editColumn:column row:newRow withEvent:nil select:YES];
- return TRUE;
- }
-
- // Trap up arrow key
- else if ( [textView methodForSelector:command] == [textView methodForSelector:@selector(moveUp:)] )
- {
- if (row==0) return TRUE; //already at the beginning of the list
- NSUInteger newRow = row-1;
-
- [[control window] makeFirstResponder:control];
- [self addRowToDB];
-
- if (newRow>=tableRowsCount) return TRUE; // addRowToDB could reload the table and change the number of rows
- if (column>=[tableValues columnCount]) return TRUE; //the column count could change too
-
- [tableContentView selectRowIndexes:[NSIndexSet indexSetWithIndex:newRow] byExtendingSelection:NO];
- [tableContentView editColumn:column row:newRow withEvent:nil select:YES];
- return TRUE;
- }
-
+
// Trap the escape key
else if ( [[control window] methodForSelector:command] == [[control window] methodForSelector:@selector(_cancelKey:)] ||
[textView methodForSelector:command] == [textView methodForSelector:@selector(complete:)] )
diff --git a/Source/TableDocument.h b/Source/TableDocument.h
index b3cbb6e7..4b151615 100644
--- a/Source/TableDocument.h
+++ b/Source/TableDocument.h
@@ -65,8 +65,6 @@
IBOutlet id titleStringView;
IBOutlet id databaseSheet;
- IBOutlet id databaseCopySheet;
- IBOutlet id databaseRenameSheet;
IBOutlet id queryProgressBar;
IBOutlet NSBox *taskProgressLayer;
@@ -79,16 +77,6 @@
IBOutlet id databaseNameField;
IBOutlet id databaseEncodingButton;
IBOutlet id addDatabaseButton;
-
- IBOutlet id databaseCopyNameField;
- IBOutlet id copyDatabaseDataButton;
- IBOutlet id copyDatabaseMessageField;
- IBOutlet id copyDatabaseButton;
-
- IBOutlet id databaseRenameNameField;
- IBOutlet id renameDatabaseMessageField;
- IBOutlet id renameDatabaseButton;
-
IBOutlet id chooseDatabaseButton;
IBOutlet id historyControl;
IBOutlet NSTabView *tableTabView;
@@ -186,7 +174,6 @@
- (void)initWithConnectionFile:(NSString *)path;
// Connection callback and methods
- (void)setConnection:(MCPConnection *)theConnection;
-- (MCPConnection *) getConnection;
- (void)setShouldAutomaticallyConnect:(BOOL)shouldAutomaticallyConnect;
- (BOOL)shouldAutomaticallyConnect;
- (void)setKeychainID:(NSString *)theID;
@@ -197,8 +184,6 @@
- (void)selectDatabase:(NSString *)aDatabase item:(NSString *)anItem;
- (IBAction)addDatabase:(id)sender;
- (IBAction)removeDatabase:(id)sender;
-- (IBAction)copyDatabase:(id)sender;
-- (IBAction)renameDatabase:(id)sender;
- (IBAction)showMySQLHelp:(id)sender;
- (IBAction)showServerVariables:(id)sender;
- (IBAction)showServerProcesses:(id)sender;
@@ -291,7 +276,6 @@
- (BOOL)validateMenuItem:(NSMenuItem *)anItem;
- (IBAction)saveConnectionSheet:(id)sender;
- (IBAction)import:(id)sender;
-- (IBAction)importFromClipboard:(id)sender;
- (IBAction)export:(id)sender;
- (IBAction)exportTable:(id)sender;
- (IBAction)exportMultipleTables:(id)sender;
diff --git a/Source/TableDocument.m b/Source/TableDocument.m
index 3f94aa01..cc1a5bc5 100644
--- a/Source/TableDocument.m
+++ b/Source/TableDocument.m
@@ -56,16 +56,10 @@
#import "SPAlertSheets.h"
#import "SPConstants.h"
#import "SPMainThreadTrampoline.h"
-#import "SPLogger.h"
-#import "SPDatabaseCopy.h"
-#import "SPTableCopy.h"
-#import "SPDatabaseRename.h"
@interface TableDocument (PrivateAPI)
- (void)_addDatabase;
-- (void)_copyDatabase;
-- (void)_renameDatabase;
- (void)_removeDatabase;
- (void)_selectDatabaseAndItem:(NSDictionary *)selectionDetails;
@@ -118,7 +112,7 @@
statusValues = nil;
printThread = nil;
}
-
+
return self;
}
@@ -247,7 +241,7 @@
[tableWindow addChildWindow:taskProgressWindow ordered:NSWindowAbove];
[taskProgressWindow setReleasedWhenClosed:YES];
[taskProgressWindow setContentView:taskProgressLayer];
- [self centerTaskWindow];
+ [self centerTaskWindow];
}
/**
@@ -758,13 +752,9 @@
break;
}
}
-}
-- (MCPConnection *) getConnection {
- return mySQLConnection;
}
-
/**
* Set whether the connection controller should automatically start
* connecting; called by maincontroller, but only for first window.
@@ -921,9 +911,9 @@
- (IBAction)addDatabase:(id)sender
{
if (![tablesListInstance selectionShouldChangeInTableView:nil]) return;
-
+
[databaseNameField setStringValue:@""];
-
+
[NSApp beginSheet:databaseSheet
modalForWindow:tableWindow
modalDelegate:self
@@ -931,41 +921,6 @@
contextInfo:@"addDatabase"];
}
-
-/**
- * opens the copy database sheet and copies the databsae
- */
-- (IBAction)copyDatabase:(id)sender
-{
- if (![tablesListInstance selectionShouldChangeInTableView:nil]) return;
-
- [databaseCopyNameField setStringValue:selectedDatabase];
- [copyDatabaseMessageField setStringValue:[NSString stringWithFormat:NSLocalizedString(@"Duplicate database '%@' to:", @"duplicate database message"), selectedDatabase]];
-
- [NSApp beginSheet:databaseCopySheet
- modalForWindow:tableWindow
- modalDelegate:self
- didEndSelector:@selector(sheetDidEnd:returnCode:contextInfo:)
- contextInfo:@"copyDatabase"];
-}
-
-/**
- * opens the rename database sheet and renames the databsae
- */
-- (IBAction)renameDatabase:(id)sender
-{
- if (![tablesListInstance selectionShouldChangeInTableView:nil]) return;
-
- [databaseRenameNameField setStringValue:selectedDatabase];
- [renameDatabaseMessageField setStringValue:[NSString stringWithFormat:NSLocalizedString(@"Rename database '%@' to:", @"rename database message"), selectedDatabase]];
-
- [NSApp beginSheet:databaseRenameSheet
- modalForWindow:tableWindow
- modalDelegate:self
- didEndSelector:@selector(sheetDidEnd:returnCode:contextInfo:)
- contextInfo:@"renameDatabase"];
-}
-
/**
* opens sheet to ask user if he really wants to delete the db
*/
@@ -1049,8 +1004,6 @@
*
* if contextInfo == removeDatabase -> Remove the selected database
* if contextInfo == addDatabase -> Add a new database
- * if contextInfo == copyDatabase -> Duplicate the selected database
- * if contextInfo == renameDatabase -> Rename the selected database
*/
- (void)sheetDidEnd:(id)sheet returnCode:(NSInteger)returnCode contextInfo:(NSString *)contextInfo
{
@@ -1082,16 +1035,6 @@
else
[chooseDatabaseButton selectItemAtIndex:0];
}
- }
- else if ([contextInfo isEqualToString:@"copyDatabase"]) {
- if (returnCode == NSOKButton) {
- [self _copyDatabase];
- }
- }
- else if ([contextInfo isEqualToString:@"renameDatabase"]) {
- if (returnCode == NSOKButton) {
- [self _renameDatabase];
- }
}
// Close error status sheet for OPTIMIZE, CHECK, REPAIR etc.
else if ([contextInfo isEqualToString:@"statusError"]) {
@@ -1282,6 +1225,7 @@
[taskCancelButton setHidden:YES];
// Set flags and prevent further UI interaction in this window
+ [historyControl setEnabled:NO];
databaseListIsSelectable = NO;
[[NSNotificationCenter defaultCenter] postNotificationName:SPDocumentTaskStartNotification object:self];
[mainToolbar validateVisibleItems];
@@ -1397,6 +1341,7 @@
[taskProgressIndicator setIndeterminate:YES];
// Re-enable window interface
+ [historyControl setEnabled:YES];
databaseListIsSelectable = YES;
[[NSNotificationCenter defaultCenter] postNotificationName:SPDocumentTaskEndNotification object:self];
[mainToolbar validateVisibleItems];
@@ -2464,22 +2409,22 @@
*/
- (BOOL)couldCommitCurrentViewActions
{
- [tableWindow endEditingFor:nil];
- switch ([tableTabView indexOfTabViewItem:[tableTabView selectedTabViewItem]]) {
+ [tableWindow endEditingFor:nil];
+ switch ([tableTabView indexOfTabViewItem:[tableTabView selectedTabViewItem]]) {
- // Table structure view
- case 0:
- return [tableSourceInstance saveRowOnDeselect];
+ // Table structure view
+ case 0:
+ return [tableSourceInstance saveRowOnDeselect];
- // Table content view
- case 1:
- return [tableContentInstance saveRowOnDeselect];
+ // Table content view
+ case 1:
+ return [tableContentInstance saveRowOnDeselect];
- default:
- break;
- }
+ default:
+ break;
+ }
- return YES;
+ return YES;
}
#pragma mark -
@@ -2629,10 +2574,6 @@
}
[tablesListInstance selectionShouldChangeInTableView:nil];
-
- // Note that this call does not need to be removed in release builds as leaks analysis output is only
- // dumped if [[SPLogger logger] setDumpLeaksOnTermination]; has been called first.
- [[SPLogger logger] dumpLeaks];
}
#pragma mark -
@@ -3114,14 +3055,6 @@
/**
* Passes the request to the tableDump object
*/
-- (IBAction)importFromClipboard:(id)sender
-{
- [tableDumpInstance importFromClipboard];
-}
-
-/**
- * Passes the request to the tableDump object
- */
- (IBAction)export:(id)sender
{
if ([sender tag] == -1) {
@@ -3179,19 +3112,11 @@
if ([menuItem action] == @selector(import:) ||
[menuItem action] == @selector(export:) ||
[menuItem action] == @selector(exportMultipleTables:) ||
- [menuItem action] == @selector(removeDatabase:) ||
- [menuItem action] == @selector(copyDatabase:) ||
- [menuItem action] == @selector(renameDatabase:))
+ [menuItem action] == @selector(removeDatabase:))
{
return ([self database] != nil);
}
-
- if ([menuItem action] == @selector(importFromClipboard:))
- {
- return ([self database] && [[NSPasteboard generalPasteboard] availableTypeFromArray:[NSArray arrayWithObjects:NSStringPboardType, nil]]) ? YES : NO;
-
- }
-
+
// Change "Save Query/Queries" menu item title dynamically
// and disable it if no query in the editor
if ([menuItem action] == @selector(saveConnectionSheet:) && [menuItem tag] == 0) {
@@ -3392,7 +3317,7 @@
if (![self couldCommitCurrentViewActions]) {
[mainToolbar setSelectedItemIdentifier:*SPViewModeToMainToolbarMap[[prefs integerForKey:SPLastViewMode]]];
return;
- }
+ }
[tableTabView selectTabViewItemAtIndex:5];
[mainToolbar setSelectedItemIdentifier:SPMainToolbarTableTriggers];
@@ -3498,9 +3423,6 @@
// update the toolbar item size
[self updateChooseDatabaseToolbarItemWidth];
-
- // The history controller needs to track toolbar item state - trigger setup.
- [spHistoryControllerInstance setupInterface];
}
/**
@@ -3940,13 +3862,7 @@
id object = [notification object];
if (object == databaseNameField) {
- [addDatabaseButton setEnabled:([[databaseNameField stringValue] length] > 0 && ![allDatabases containsObject: [databaseNameField stringValue]])];
- }
- else if (object == databaseCopyNameField) {
- [copyDatabaseButton setEnabled:([[databaseCopyNameField stringValue] length] > 0 && ![allDatabases containsObject: [databaseCopyNameField stringValue]])];
- }
- else if (object == databaseRenameNameField) {
- [renameDatabaseButton setEnabled:([[databaseRenameNameField stringValue] length] > 0 && ![allDatabases containsObject: [databaseRenameNameField stringValue]])];
+ [addDatabaseButton setEnabled:([[databaseNameField stringValue] length] > 0)];
}
else if (object == saveConnectionEncryptString) {
[saveConnectionEncryptString setStringValue:[saveConnectionEncryptString stringValue]];
@@ -4129,7 +4045,7 @@
[allSystemDatabases release];
[printWebView release];
[taskProgressWindow close];
-
+
if (connectionController) [connectionController release];
if (processListController) [processListController release];
if (serverVariablesController) [serverVariablesController release];
@@ -4151,45 +4067,6 @@
@implementation TableDocument (PrivateAPI)
-- (void)_copyDatabase {
- if ([[databaseCopyNameField stringValue] isEqualToString:@""]) {
- SPBeginAlertSheet(NSLocalizedString(@"Error", @"error"), NSLocalizedString(@"OK", @"OK button"), nil, nil, tableWindow, self, nil, nil, nil, NSLocalizedString(@"Database must have a name.", @"message of panel when no db name is given"));
- return;
- }
- SPDatabaseCopy *dbActionCopy = [[SPDatabaseCopy alloc] init];
- [dbActionCopy setConnection: [self getConnection]];
- [dbActionCopy setMessageWindow: tableWindow];
-
- BOOL copyWithContent = [copyDatabaseDataButton state] == NSOnState;
-
- if ([dbActionCopy copyDatabaseFrom: [self database]
- to: [databaseCopyNameField stringValue]
- withContent: copyWithContent]) {
- [selectedDatabase release];
- selectedDatabase = [[NSString alloc] initWithString:[databaseCopyNameField stringValue]];
- }
- [dbActionCopy release];
- [self setDatabases: self];
-}
-
-- (void)_renameDatabase {
- if ([[databaseRenameNameField stringValue] isEqualToString:@""]) {
- SPBeginAlertSheet(NSLocalizedString(@"Error", @"error"), NSLocalizedString(@"OK", @"OK button"), nil, nil, tableWindow, self, nil, nil, nil, NSLocalizedString(@"Database must have a name.", @"message of panel when no db name is given"));
- return;
- }
- SPDatabaseRename *dbActionRename = [[SPDatabaseRename alloc] init];
- [dbActionRename setConnection: [self getConnection]];
- [dbActionRename setMessageWindow: tableWindow];
-
- if ([dbActionRename renameDatabaseFrom: [self database]
- to: [databaseRenameNameField stringValue]]) {
- [selectedDatabase release];
- selectedDatabase = [[NSString alloc] initWithString:[databaseRenameNameField stringValue]];
- }
- [dbActionRename release];
- [self setDatabases: self];
-}
-
/**
* Adds a new database.
*/
@@ -4253,7 +4130,7 @@
// An error occurred
[self performSelector:@selector(showErrorSheetWith:)
withObject:[NSArray arrayWithObjects:NSLocalizedString(@"Error", @"error"),
- [NSString stringWithFormat:NSLocalizedString(@"Couldn't delete the database.\nMySQL said: %@", @"message of panel when deleting db failed"),
+ [NSString stringWithFormat:NSLocalizedString(@"Couldn't remove database.\nMySQL said: %@", @"message of panel when removing db failed"),
[mySQLConnection getLastErrorMessage]],
nil]
afterDelay:0.3];
diff --git a/Source/TableDump.h b/Source/TableDump.h
index e506a6d2..6a6a34b0 100644
--- a/Source/TableDump.h
+++ b/Source/TableDump.h
@@ -27,7 +27,7 @@
#import <Cocoa/Cocoa.h>
#import <MCPKit/MCPKit.h>
-@class SPFieldMapperController, SPFileHandle;
+@class SPFieldMapperController;
@interface TableDump : NSObject
{
@@ -74,16 +74,11 @@
IBOutlet id importLinesTerminatedField;
IBOutlet id importFieldMapperSheetWindow;
- IBOutlet id importFromClipboardSheet;
- IBOutlet NSTextView *importFromClipboardTextView;
- IBOutlet id importFromClipboardAccessoryView;
-
IBOutlet id addDropTableSwitch;
IBOutlet id addCreateTableSwitch;
IBOutlet id addTableContentSwitch;
IBOutlet id addErrorsSwitch;
IBOutlet id sqlFullStreamingSwitch;
- IBOutlet id sqlCompressionSwitch;
IBOutlet id csvFullStreamingSwitch;
IBOutlet id multiCSVFullStreamingSwitch;
IBOutlet id multiXMLFullStreamingSwitch;
@@ -122,8 +117,6 @@
NSUInteger exportMode;
NSUserDefaults *prefs;
BOOL progressCancelled;
-
- NSSavePanel *currentExportPanel;
}
// IBAction methods
@@ -140,32 +133,31 @@
// Import methods
- (void)importFile;
-- (void)importFromClipboard;
- (void)importSQLFile:(NSString *)filename;
- (void)startSQLImportProcessWithFile:(NSString *)filename;
- (void)importCSVFile:(NSString *)filename;
- (IBAction)changeFormat:(id)sender;
-- (void)openPanelDidEnd:(id)sheet returnCode:(NSInteger)returnCode contextInfo:(NSString *)contextInfo;
+- (void)openPanelDidEnd:(NSOpenPanel *)sheet returnCode:(NSInteger)returnCode contextInfo:(NSString *)contextInfo;
- (BOOL) buildFieldMappingArrayWithData:(NSArray *)importData isPreview:(BOOL)dataIsPreviewData ofSoureFile:(NSString*)filename;
- (NSString *) mappedValueStringForRowArray:(NSArray *)csvRowArray;
- (NSString *) mappedUpdateSetStatementStringForRowArray:(NSArray *)csvRowArray;
// Export methods
-- (BOOL)dumpSelectedTablesAsSqlToFileHandle:(SPFileHandle *)fileHandle;
-- (BOOL)dumpSchemaAsDotToFileHandle:(SPFileHandle *)fileHandle;
+- (BOOL)dumpSelectedTablesAsSqlToFileHandle:(NSFileHandle *)fileHandle;
+- (BOOL)dumpSchemaAsDotToFileHandle:(NSFileHandle *)fileHandle;
- (BOOL)writeCsvForArray:(NSArray *)array orStreamingResult:(MCPStreamingResult *)streamingResult
- toFileHandle:(SPFileHandle *)fileHandle
+ toFileHandle:(NSFileHandle *)fileHandle
outputFieldNames:(BOOL)firstLine terminatedBy:(NSString *)terminated
enclosedBy:(NSString *)enclosed escapedBy:(NSString *)escaped
lineEnds:(NSString *)lineEnds withNumericColumns:(NSArray *)tableColumnNumericStatus totalRows:(NSInteger)totalRows silently:(BOOL)silently;
- (BOOL)writeXmlForArray:(NSArray *)array orStreamingResult:(MCPStreamingResult *)streamingResult
- toFileHandle:(SPFileHandle *)fileHandle
+ toFileHandle:(NSFileHandle *)fileHandle
tableName:(NSString *)table withHeader:(BOOL)header totalRows:(NSInteger)totalRows silently:(BOOL)silently;
- (NSString *)htmlEscapeString:(NSString *)string;
- (NSString *)createViewPlaceholderSyntaxForView:(NSString *)viewName;
-- (BOOL)exportTables:(NSArray *)selectedTables toFileHandle:(SPFileHandle *)fileHandle usingFormat:(NSString *)type usingMulti:(BOOL)multi;
-- (BOOL)exportSelectedTablesToFileHandle:(SPFileHandle *)fileHandle usingFormat:(NSString *)type;
+- (BOOL)exportTables:(NSArray *)selectedTables toFileHandle:(NSFileHandle *)fileHandle usingFormat:(NSString *)type usingMulti:(BOOL)multi;
+- (BOOL)exportSelectedTablesToFileHandle:(NSFileHandle *)fileHandle usingFormat:(NSString *)type;
// New Export methods
- (IBAction)switchTab:(id)sender;
@@ -177,6 +169,5 @@
// Import/export delegate notifications
- (void)panelSelectionDidChange:(id)sender;
-- (IBAction)updateExportCompressionSetting:(id)sender;
@end
diff --git a/Source/TableDump.m b/Source/TableDump.m
index 004a8e61..50d380f0 100644
--- a/Source/TableDump.m
+++ b/Source/TableDump.m
@@ -41,7 +41,6 @@
#import "SPFieldMapperController.h"
#import "SPMainThreadTrampoline.h"
#import "SPNotLoaded.h"
-#import "SPFileHandle.h"
@implementation TableDump
@@ -157,9 +156,9 @@
{
NSString *file;
NSString *contextInfo;
- currentExportPanel = [NSSavePanel savePanel];
- [currentExportPanel setAllowsOtherFileTypes:YES];
- [currentExportPanel setExtensionHidden:NO];
+ NSSavePanel *savePanel = [NSSavePanel savePanel];
+ [savePanel setAllowsOtherFileTypes:YES];
+ [savePanel setExtensionHidden:NO];
NSString *currentDate = [[NSDate date] descriptionWithCalendarFormat:@"%Y-%m-%d" timeZone:nil locale:nil];
switch ( tag ) {
@@ -167,14 +166,9 @@
// export dump
exportMode = SPExportingSQL;
[self reloadTables:self];
- [sqlCompressionSwitch setState:[prefs boolForKey:SPSQLExportUseCompression]?NSOnState:NSOffState];
- if ([prefs boolForKey:SPSQLExportUseCompression]) {
- [currentExportPanel setAllowedFileTypes:[NSArray arrayWithObjects:@"sql.gz", @"gz", nil]];
- } else {
- [currentExportPanel setAllowedFileTypes:[NSArray arrayWithObjects:@"sql", nil]];
- }
- file = [NSString stringWithFormat:@"%@_%@.%@", [tableDocumentInstance database], currentDate, [currentExportPanel requiredFileType]];
- [currentExportPanel setAccessoryView:exportDumpView];
+ file = [NSString stringWithFormat:@"%@_%@.sql", [tableDocumentInstance database], currentDate];
+ [savePanel setRequiredFileType:@"sql"];
+ [savePanel setAccessoryView:exportDumpView];
contextInfo = @"exportDump";
break;
@@ -182,7 +176,7 @@
case 6:
exportMode = SPExportingCSV;
file = [NSString stringWithFormat:@"%@.csv", [tableDocumentInstance table]];
- [currentExportPanel setAccessoryView:exportCSVView];
+ [savePanel setAccessoryView:exportCSVView];
[csvFullStreamingSwitch setEnabled:YES];
contextInfo = @"exportTableContentAsCSV";
break;
@@ -198,7 +192,7 @@
case 8:
exportMode = SPExportingCSV;
file = [NSString stringWithFormat:@"%@ view.csv", [tableDocumentInstance table]];
- [currentExportPanel setAccessoryView:exportCSVView];
+ [savePanel setAccessoryView:exportCSVView];
[csvFullStreamingSwitch setEnabled:NO];
contextInfo = @"exportBrowseViewAsCSV";
break;
@@ -214,7 +208,7 @@
case 10:
exportMode = SPExportingCSV;
file = @"customresult.csv";
- [currentExportPanel setAccessoryView:exportCSVView];
+ [savePanel setAccessoryView:exportCSVView];
[csvFullStreamingSwitch setEnabled:NO];
contextInfo = @"exportCustomResultAsCSV";
break;
@@ -231,7 +225,7 @@
exportMode = SPExportingCSV;
[self reloadTables:self];
file = [NSString stringWithFormat:@"%@.csv", [tableDocumentInstance database]];
- [currentExportPanel setAccessoryView:exportMultipleCSVView];
+ [savePanel setAccessoryView:exportMultipleCSVView];
contextInfo = @"exportMultipleTablesAsCSV";
break;
@@ -240,7 +234,7 @@
exportMode = SPExportingXML;
[self reloadTables:self];
file = [NSString stringWithFormat:@"%@.xml", [tableDocumentInstance database]];
- [currentExportPanel setAccessoryView:exportMultipleXMLView];
+ [savePanel setAccessoryView:exportMultipleXMLView];
contextInfo = @"exportMultipleTablesAsXML";
break;
@@ -249,7 +243,7 @@
exportMode = SPExportingDOT;
[self reloadTables:self];
file = [NSString stringWithString:[tableDocumentInstance database]];
- [currentExportPanel setRequiredFileType:@"dot"];
+ [savePanel setRequiredFileType:@"dot"];
contextInfo = @"exportDot";
break;
@@ -259,24 +253,12 @@
break;
}
- [currentExportPanel setDelegate:self];
+ [savePanel setDelegate:self];
// Open the savePanel
- [currentExportPanel beginSheetForDirectory:[prefs objectForKey:@"savePath"]
- file:file modalForWindow:tableWindow modalDelegate:self
- didEndSelector:@selector(savePanelDidEnd:returnCode:contextInfo:) contextInfo:contextInfo];
-
-
- // Wait for the SavePanel and check for '.sql.gz' extension; if so - select only the path name without any extensions
- while(![currentExportPanel isVisible]) { usleep(100); }
- if([[currentExportPanel firstResponder] isKindOfClass:[NSTextView class]]) {
- NSTextView *filenameTextView = (NSTextView *)[currentExportPanel firstResponder];
- if([filenameTextView selectedRange].length > 4 && [[filenameTextView string] hasSuffix:@".sql.gz"]) {
- NSRange selRange = [filenameTextView selectedRange];
- selRange.length -= 4;
- [filenameTextView setSelectedRange:selRange];
- }
- }
+ [savePanel beginSheetForDirectory:[prefs objectForKey:@"savePath"]
+ file:file modalForWindow:tableWindow modalDelegate:self
+ didEndSelector:@selector(savePanelDidEnd:returnCode:contextInfo:) contextInfo:contextInfo];
}
/**
@@ -311,7 +293,7 @@
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSString *exportActionName = [exportAction objectForKey:@"action"];
NSString *exportFile = [exportAction objectForKey:@"filename"];
- SPFileHandle *fileHandle = nil;
+ NSFileHandle *fileHandle = nil;
BOOL success;
// Start the notification timer to allow notifications to be shown even if frontmost for long queries
@@ -323,14 +305,17 @@
// Error if the file already exists and is not writable, and get a fileHandle to it.
if ( [[NSFileManager defaultManager] fileExistsAtPath:exportFile] ) {
if ( ![[NSFileManager defaultManager] isWritableFileAtPath:exportFile]
- || !(fileHandle = [SPFileHandle fileHandleForWritingAtPath:exportFile]) ) {
+ || !(fileHandle = [NSFileHandle fileHandleForWritingAtPath:exportFile]) ) {
SPBeginAlertSheet(NSLocalizedString(@"Error", @"error"), NSLocalizedString(@"OK", @"OK button"), nil, nil, tableWindow, self, nil, nil, nil,
NSLocalizedString(@"Couldn't replace the file. Be sure that you have the necessary privileges.", @"message of panel when file cannot be replaced"));
[pool release];
return;
}
- // Otherwise attempt to create a file
+ // Truncate the file to zero bytes
+ [fileHandle truncateFileAtOffset:0];
+
+ // Otherwise attempt to create a file
} else {
if ( ![[NSFileManager defaultManager] createFileAtPath:exportFile contents:[NSData data] attributes:nil] ) {
SPBeginAlertSheet(NSLocalizedString(@"Error", @"error"), NSLocalizedString(@"OK", @"OK button"), nil, nil, tableWindow, self, nil, nil, nil,
@@ -340,7 +325,7 @@
}
// Retrieve a filehandle for the file, attempting to delete it on failure.
- fileHandle = [SPFileHandle fileHandleForWritingAtPath:exportFile];
+ fileHandle = [NSFileHandle fileHandleForWritingAtPath:exportFile];
if ( !fileHandle ) {
[[NSFileManager defaultManager] removeFileAtPath:exportFile handler:nil];
SPBeginAlertSheet(NSLocalizedString(@"Error", @"error"), NSLocalizedString(@"OK", @"OK button"), nil, nil, tableWindow, self, nil, nil, nil,
@@ -352,7 +337,6 @@
// Export the tables selected in the MySQL export sheet to a file
if ( [exportActionName isEqualToString:@"exportDump"] ) {
- [fileHandle setShouldWriteWithGzipCompression:([sqlCompressionSwitch state] == NSOnState)];
success = [self dumpSelectedTablesAsSqlToFileHandle:fileHandle];
// Export the full resultset for the currently selected table to a file in CSV format
@@ -489,51 +473,6 @@
#pragma mark -
#pragma mark Import methods
-- (void)importFromClipboard
-/*
- invoked when user clicks on an ImportFromClipboard menuItem
- */
-{
- // Load accessory nib each time
- if(![NSBundle loadNibNamed:@"ImportAccessory" owner:self]) {
- NSBeep();
- NSLog(@"ImportAccessory accessory dialog could not be loaded.");
- return;
- }
-
- // clipboard textview with no wrapping
- const CGFloat LargeNumberForText = 1.0e7;
- [[importFromClipboardTextView textContainer] setContainerSize:NSMakeSize(LargeNumberForText, LargeNumberForText)];
- [[importFromClipboardTextView textContainer] setWidthTracksTextView:NO];
- [[importFromClipboardTextView textContainer] setHeightTracksTextView:NO];
- [importFromClipboardTextView setAutoresizingMask:NSViewNotSizable];
- [importFromClipboardTextView setMaxSize:NSMakeSize(LargeNumberForText, LargeNumberForText)];
- [importFromClipboardTextView setHorizontallyResizable:YES];
- [importFromClipboardTextView setVerticallyResizable:YES];
- [importFromClipboardTextView setFont:[NSFont fontWithName:@"Monaco" size:11.0f]];
-
- if([[[NSPasteboard generalPasteboard] stringForType:NSStringPboardType] length] > 4000)
- [importFromClipboardTextView setString:[[[[NSPasteboard generalPasteboard] stringForType:NSStringPboardType] substringToIndex:4000] stringByAppendingString:@"\n…"]];
- else
- [importFromClipboardTextView setString:[[NSPasteboard generalPasteboard] stringForType:NSStringPboardType]];
-
- // Preset the accessory view with prefs defaults
- [importFieldsTerminatedField setStringValue:[prefs objectForKey:SPCSVImportFieldTerminator]];
- [importLinesTerminatedField setStringValue:[prefs objectForKey:SPCSVImportLineTerminator]];
- [importFieldsEscapedField setStringValue:[prefs objectForKey:SPCSVImportFieldEscapeCharacter]];
- [importFieldsEnclosedField setStringValue:[prefs objectForKey:SPCSVImportFieldEnclosedBy]];
- [importFieldNamesSwitch setState:[[prefs objectForKey:SPCSVImportFirstLineIsHeader] boolValue]];
- [importFromClipboardAccessoryView addSubview:importCSVView];
-
- [NSApp beginSheet:importFromClipboardSheet
- modalForWindow:tableWindow
- modalDelegate:self
- didEndSelector:@selector(openPanelDidEnd:returnCode:contextInfo:)
- contextInfo:@"importFromClipboard"];
-
- // NSString );
-}
-
- (void)importFile
/*
invoked when user clicks on an import menuItem
@@ -594,7 +533,7 @@
- (void) importSQLFile:(NSString *)filename
{
NSAutoreleasePool *importPool;
- SPFileHandle *sqlFileHandle;
+ NSFileHandle *sqlFileHandle;
NSMutableData *sqlDataBuffer;
const unsigned char *sqlDataBufferBytes;
NSData *fileChunk;
@@ -609,7 +548,6 @@
NSInteger dataBufferLength = 0;
NSInteger dataBufferPosition = 0;
NSInteger dataBufferLastQueryEndPosition = 0;
- BOOL fileIsCompressed;
BOOL importSQLAsUTF8 = YES;
BOOL allDataRead = NO;
NSStringEncoding sqlEncoding = NSUTF8StringEncoding;
@@ -619,17 +557,14 @@
[[SPGrowlController sharedGrowlController] setVisibilityForNotificationName:@"Import Finished"];
// Open a filehandle for the SQL file
- sqlFileHandle = [SPFileHandle fileHandleForReadingAtPath:filename];
+ sqlFileHandle = [NSFileHandle fileHandleForReadingAtPath:filename];
if (!sqlFileHandle) {
SPBeginAlertSheet(NSLocalizedString(@"Import Error title", @"Import Error"),
NSLocalizedString(@"OK button label", @"OK button"),
nil, nil, tableWindow, self, nil, nil, nil,
NSLocalizedString(@"SQL file open error", @"The SQL file you selected could not be found or read."));
- if([filename hasPrefix:SPImportClipboardTempFileNamePrefix])
- [[NSFileManager defaultManager] removeItemAtPath:filename error:nil];
return;
}
- fileIsCompressed = [sqlFileHandle isCompressed];
// Grab the file length
fileTotalLength = [[[[NSFileManager defaultManager] attributesOfItemAtPath:filename error:NULL] objectForKey:NSFileSize] longLongValue];
@@ -673,8 +608,6 @@
[sqlDataBuffer release];
[importPool drain];
[tableDocumentInstance setQueryMode:SPInterfaceQueryMode];
- if([filename hasPrefix:SPImportClipboardTempFileNamePrefix])
- [[NSFileManager defaultManager] removeItemAtPath:filename error:nil];
return;
}
@@ -723,8 +656,6 @@
[sqlDataBuffer release];
[importPool drain];
[tableDocumentInstance setQueryMode:SPInterfaceQueryMode];
- if([filename hasPrefix:SPImportClipboardTempFileNamePrefix])
- [[NSFileManager defaultManager] removeItemAtPath:filename error:nil];
return;
}
}
@@ -748,11 +679,7 @@
}
// Before entering the following loop, check that we actually have a connection. If not, bail.
- if (![mySQLConnection isConnected]) {
- if([filename hasPrefix:SPImportClipboardTempFileNamePrefix])
- [[NSFileManager defaultManager] removeItemAtPath:filename error:nil];
- return;
- }
+ if (![mySQLConnection isConnected]) return;
// Extract and process any complete SQL queries that can be found in the strings parsed so far
while (query = [sqlParser trimAndReturnStringToCharacter:';' trimmingInclusively:YES returningInclusively:NO]) {
@@ -775,15 +702,9 @@
queriesPerformed++;
// Update the progress bar
- if (fileIsCompressed) {
- [singleProgressBar setDoubleValue:[sqlFileHandle realDataReadLength]];
- [singleProgressText setStringValue:[NSString stringWithFormat:NSLocalizedString(@"Imported %@ of SQL", @"SQL import progress text where total size is unknown"),
- [NSString stringForByteSize:fileProcessedLength]]];
- } else {
- [singleProgressBar setDoubleValue:fileProcessedLength];
- [singleProgressText setStringValue:[NSString stringWithFormat:NSLocalizedString(@"Imported %@ of %@", @"SQL import progress text"),
- [NSString stringForByteSize:fileProcessedLength], [NSString stringForByteSize:fileTotalLength]]];
- }
+ [singleProgressBar setDoubleValue:fileProcessedLength];
+ [singleProgressText setStringValue:[NSString stringWithFormat:NSLocalizedString(@"Imported %@ of %@", @"SQL import progress text"),
+ [NSString stringForByteSize:fileProcessedLength], [NSString stringForByteSize:fileTotalLength]]];
}
// If all the data has been read, break out of the processing loop
@@ -815,8 +736,6 @@
[sqlDataBuffer release];
[importPool drain];
[tableDocumentInstance setQueryMode:SPInterfaceQueryMode];
- if([filename hasPrefix:SPImportClipboardTempFileNamePrefix])
- [[NSFileManager defaultManager] removeItemAtPath:filename error:nil];
// Close progress sheet
[self closeAndStopProgressSheet];
@@ -872,9 +791,7 @@
NSInteger i;
BOOL allDataRead = NO;
BOOL insertBaseStringHasEntries;
-
NSStringEncoding csvEncoding = [MCPConnection encodingForMySQLEncoding:[[tableDocumentInstance connectionEncoding] UTF8String]];
-
fieldMappingArray = nil;
fieldMappingGlobalValueArray = nil;
@@ -888,8 +805,6 @@
NSLocalizedString(@"OK button label", @"OK button"),
nil, nil, tableWindow, self, nil, nil, nil,
NSLocalizedString(@"CSV file open error", @"The CSV file you selected could not be found or read."));
- if([filename hasPrefix:SPImportClipboardTempFileNamePrefix])
- [[NSFileManager defaultManager] removeItemAtPath:filename error:nil];
return;
}
@@ -953,16 +868,14 @@
[parsedRows release];
[parsePositions release];
if(csvImportTailString) [csvImportTailString release], csvImportTailString = nil;
- if(csvImportHeaderString) [csvImportHeaderString release], csvImportHeaderString = nil;
- if(fieldMappingArray) [fieldMappingArray release], fieldMappingArray = nil;
- if(fieldMappingGlobalValueArray) [fieldMappingGlobalValueArray release], fieldMappingGlobalValueArray = nil;
- if(fieldMappingTableColumnNames) [fieldMappingTableColumnNames release], fieldMappingTableColumnNames = nil;
- if(fieldMappingTableDefaultValues) [fieldMappingTableDefaultValues release], fieldMappingTableDefaultValues = nil;
- if(fieldMapperOperator) [fieldMapperOperator release], fieldMapperOperator = nil;
+ if(csvImportHeaderString) [csvImportHeaderString release], csvImportHeaderString = nil;
+ if(fieldMappingArray) [fieldMappingArray release], fieldMappingArray = nil;
+ if(fieldMappingGlobalValueArray) [fieldMappingGlobalValueArray release], fieldMappingGlobalValueArray = nil;
+ if(fieldMappingTableColumnNames) [fieldMappingTableColumnNames release], fieldMappingTableColumnNames = nil;
+ if(fieldMappingTableDefaultValues) [fieldMappingTableDefaultValues release], fieldMappingTableDefaultValues = nil;
+ if(fieldMapperOperator) [fieldMapperOperator release], fieldMapperOperator = nil;
[importPool drain];
[tableDocumentInstance setQueryMode:SPInterfaceQueryMode];
- if([filename hasPrefix:SPImportClipboardTempFileNamePrefix])
- [[NSFileManager defaultManager] removeItemAtPath:filename error:nil];
return;
}
@@ -1002,16 +915,14 @@
[parsedRows release];
[parsePositions release];
if(csvImportTailString) [csvImportTailString release], csvImportTailString = nil;
- if(csvImportHeaderString) [csvImportHeaderString release], csvImportHeaderString = nil;
- if(fieldMappingArray) [fieldMappingArray release], fieldMappingArray = nil;
- if(fieldMappingGlobalValueArray) [fieldMappingGlobalValueArray release], fieldMappingGlobalValueArray = nil;
- if(fieldMappingTableColumnNames) [fieldMappingTableColumnNames release], fieldMappingTableColumnNames = nil;
- if(fieldMappingTableDefaultValues) [fieldMappingTableDefaultValues release], fieldMappingTableDefaultValues = nil;
- if(fieldMapperOperator) [fieldMapperOperator release], fieldMapperOperator = nil;
+ if(csvImportHeaderString) [csvImportHeaderString release], csvImportHeaderString = nil;
+ if(fieldMappingArray) [fieldMappingArray release], fieldMappingArray = nil;
+ if(fieldMappingGlobalValueArray) [fieldMappingGlobalValueArray release], fieldMappingGlobalValueArray = nil;
+ if(fieldMappingTableColumnNames) [fieldMappingTableColumnNames release], fieldMappingTableColumnNames = nil;
+ if(fieldMappingTableDefaultValues) [fieldMappingTableDefaultValues release], fieldMappingTableDefaultValues = nil;
+ if(fieldMapperOperator) [fieldMapperOperator release], fieldMapperOperator = nil;
[importPool drain];
[tableDocumentInstance setQueryMode:SPInterfaceQueryMode];
- if([filename hasPrefix:SPImportClipboardTempFileNamePrefix])
- [[NSFileManager defaultManager] removeItemAtPath:filename error:nil];
return;
}
@@ -1055,16 +966,14 @@
[parsedRows release];
[parsePositions release];
if(csvImportTailString) [csvImportTailString release], csvImportTailString = nil;
- if(csvImportHeaderString) [csvImportHeaderString release], csvImportHeaderString = nil;
- if(fieldMappingArray) [fieldMappingArray release], fieldMappingArray = nil;
- if(fieldMappingGlobalValueArray) [fieldMappingGlobalValueArray release], fieldMappingGlobalValueArray = nil;
- if(fieldMappingTableColumnNames) [fieldMappingTableColumnNames release], fieldMappingTableColumnNames = nil;
- if(fieldMappingTableDefaultValues) [fieldMappingTableDefaultValues release], fieldMappingTableDefaultValues = nil;
- if(fieldMapperOperator) [fieldMapperOperator release], fieldMapperOperator = nil;
+ if(csvImportHeaderString) [csvImportHeaderString release], csvImportHeaderString = nil;
+ if(fieldMappingArray) [fieldMappingArray release], fieldMappingArray = nil;
+ if(fieldMappingGlobalValueArray) [fieldMappingGlobalValueArray release], fieldMappingGlobalValueArray = nil;
+ if(fieldMappingTableColumnNames) [fieldMappingTableColumnNames release], fieldMappingTableColumnNames = nil;
+ if(fieldMappingTableDefaultValues) [fieldMappingTableDefaultValues release], fieldMappingTableDefaultValues = nil;
+ if(fieldMapperOperator) [fieldMapperOperator release], fieldMapperOperator = nil;
[importPool drain];
[tableDocumentInstance setQueryMode:SPInterfaceQueryMode];
- if([filename hasPrefix:SPImportClipboardTempFileNamePrefix])
- [[NSFileManager defaultManager] removeItemAtPath:filename error:nil];
return;
}
@@ -1102,23 +1011,21 @@
// Before entering the following loop, check that we actually have a connection. If not, bail.
if (![mySQLConnection isConnected]) {
[self closeAndStopProgressSheet];
- [csvParser release];
- [csvDataBuffer release];
- [parsedRows release];
- [parsePositions release];
- if(csvImportTailString) [csvImportTailString release], csvImportTailString = nil;
- if(csvImportHeaderString) [csvImportHeaderString release], csvImportHeaderString = nil;
- if(fieldMappingArray) [fieldMappingArray release], fieldMappingArray = nil;
- if(fieldMappingGlobalValueArray) [fieldMappingGlobalValueArray release], fieldMappingGlobalValueArray = nil;
- if(fieldMappingTableColumnNames) [fieldMappingTableColumnNames release], fieldMappingTableColumnNames = nil;
- if(fieldMappingTableDefaultValues) [fieldMappingTableDefaultValues release], fieldMappingTableDefaultValues = nil;
- if(fieldMapperOperator) [fieldMapperOperator release], fieldMapperOperator = nil;
- [importPool drain];
- [tableDocumentInstance setQueryMode:SPInterfaceQueryMode];
- if([filename hasPrefix:SPImportClipboardTempFileNamePrefix])
- [[NSFileManager defaultManager] removeItemAtPath:filename error:nil];
- return;
- }
+ [csvParser release];
+ [csvDataBuffer release];
+ [parsedRows release];
+ [parsePositions release];
+ if(csvImportTailString) [csvImportTailString release], csvImportTailString = nil;
+ if(csvImportHeaderString) [csvImportHeaderString release], csvImportHeaderString = nil;
+ if(fieldMappingArray) [fieldMappingArray release], fieldMappingArray = nil;
+ if(fieldMappingGlobalValueArray) [fieldMappingGlobalValueArray release], fieldMappingGlobalValueArray = nil;
+ if(fieldMappingTableColumnNames) [fieldMappingTableColumnNames release], fieldMappingTableColumnNames = nil;
+ if(fieldMappingTableDefaultValues) [fieldMappingTableDefaultValues release], fieldMappingTableDefaultValues = nil;
+ if(fieldMapperOperator) [fieldMapperOperator release], fieldMapperOperator = nil;
+ [importPool drain];
+ [tableDocumentInstance setQueryMode:SPInterfaceQueryMode];
+ return;
+ }
// If we have more than the csvRowsPerQuery amount, or if we're at the end of the
// available data, construct and run a query.
@@ -1262,8 +1169,6 @@
if(fieldMapperOperator) [fieldMapperOperator release], fieldMapperOperator = nil;
[importPool drain];
[tableDocumentInstance setQueryMode:SPInterfaceQueryMode];
- if([filename hasPrefix:SPImportClipboardTempFileNamePrefix])
- [[NSFileManager defaultManager] removeItemAtPath:filename error:nil];
// Close progress sheet
[self closeAndStopProgressSheet];
@@ -1273,8 +1178,8 @@
[self showErrorSheetWithMessage:errors];
}
- // Import finished Growl notification
- [[SPGrowlController sharedGrowlController] notifyWithTitle:@"Import Finished"
+ // Import finished Growl notification
+ [[SPGrowlController sharedGrowlController] notifyWithTitle:@"Import Finished"
description:[NSString stringWithFormat:NSLocalizedString(@"Finished importing %@",@"description for finished importing growl notification"), [filename lastPathComponent]]
window:tableWindow
notificationName:@"Import Finished"];
@@ -1290,71 +1195,30 @@
}
}
-- (void)openPanelDidEnd:(id)sheet returnCode:(NSInteger)returnCode contextInfo:(NSString *)contextInfo
+- (void)openPanelDidEnd:(NSOpenPanel *)sheet returnCode:(NSInteger)returnCode contextInfo:(NSString *)contextInfo
{
-
- // if contextInfo == nil NSOpenPanel else importFromClipboardPanel
-
// save values to preferences
- if(contextInfo == nil)
- [prefs setObject:[(NSOpenPanel*)sheet directory] forKey:@"openPath"];
- else
- [importFromClipboardTextView setString:@""];
-
+ [prefs setObject:[sheet directory] forKey:@"openPath"];
[prefs setObject:[[importFormatPopup selectedItem] title] forKey:@"importFormatPopupValue"];
- // close NSOpenPanel sheet
- if(contextInfo == nil)
- [sheet orderOut:self];
-
- // check if user canceled
+ // close sheet, and check if user canceled
+ [sheet orderOut:self];
if (returnCode != NSOKButton)
return;
// Reset progress cancelled from any previous runs
progressCancelled = NO;
- NSString *importFileName;
+ if(lastFilename) [lastFilename release]; lastFilename = nil;
+ lastFilename = [[NSString stringWithString:[sheet filename]] retain];
- // File path from NSOpenPanel
- if(contextInfo == nil)
- {
- if(lastFilename) [lastFilename release]; lastFilename = nil;
- lastFilename = [[NSString stringWithString:[(NSOpenPanel*)sheet filename]] retain];
- importFileName = [NSString stringWithString:lastFilename];
- if(lastFilename == nil || ![lastFilename length]) {
- NSBeep();
- return;
- }
- }
-
- // Import from Clipboard
- else
- {
- importFileName = [NSString stringWithFormat:@"%@%@", SPImportClipboardTempFileNamePrefix,
- [[NSDate date] descriptionWithCalendarFormat:@"%H%M%S"
- timeZone:nil
- locale:[[NSUserDefaults standardUserDefaults] dictionaryRepresentation]]];
-
- // Write clipboard content to temp file using the connection encoding
-
- NSStringEncoding encoding;
- if ([[[importFormatPopup selectedItem] title] isEqualToString:@"SQL"])
- encoding = NSUTF8StringEncoding;
- else
- encoding = [MCPConnection encodingForMySQLEncoding:[[tableDocumentInstance connectionEncoding] UTF8String]];
-
- if(![[[NSPasteboard generalPasteboard] stringForType:NSStringPboardType] writeToFile:importFileName atomically:NO encoding:encoding error:nil]) {
- NSBeep();
- NSLog(@"Couldn't write clipboard content to temporary file.");
- return;
- }
+ if(lastFilename == nil || ![lastFilename length]) {
+ NSBeep();
+ return;
}
- if(importFileName == nil) return;
-
// begin import process
- [NSThread detachNewThreadSelector:@selector(importBackgroundProcess:) toTarget:self withObject:importFileName];
+ [NSThread detachNewThreadSelector:@selector(importBackgroundProcess:) toTarget:self withObject:lastFilename];
}
- (void)startSQLImportProcessWithFile:(NSString *)filename
@@ -1618,7 +1482,7 @@
/*
Dump the selected tables to a file handle in SQL format.
*/
-- (BOOL)dumpSelectedTablesAsSqlToFileHandle:(SPFileHandle *)fileHandle
+- (BOOL)dumpSelectedTablesAsSqlToFileHandle:(NSFileHandle *)fileHandle
{
NSInteger i,j,t,rowCount, colCount, lastProgressValue, queryLength;
NSInteger progressBarWidth;
@@ -1921,52 +1785,52 @@
// Release the result set
[streamingResult release];
- }
-
- // Export triggers, if any
- queryResult = [mySQLConnection queryString:[NSString stringWithFormat:@"/*!50003 SHOW TRIGGERS WHERE `Table` = %@ */;",
- [tableName tickQuotedString]]];
- [queryResult setReturnDataAsStrings:YES];
- if ( [queryResult numOfRows] ) {
- [metaString setString:@"\n"];
- [metaString appendString:@"DELIMITER ;;\n"];
- for (int s=0; s<[queryResult numOfRows]; s++) {
- NSDictionary *triggers = [[NSDictionary alloc] initWithDictionary:[queryResult fetchRowAsDictionary]];
+ queryResult = [mySQLConnection queryString:[NSString stringWithFormat:@"/*!50003 SHOW TRIGGERS WHERE `Table` = %@ */;",
+ [tableName tickQuotedString]]];
+ [queryResult setReturnDataAsStrings:YES];
+ if ( [queryResult numOfRows] ) {
+ [metaString setString:@"\n"];
+ [metaString appendString:@"DELIMITER ;;\n"];
- //Definer is user@host but we need to escape it to `user`@`host`
- NSArray *triggersDefiner = [[triggers objectForKey:@"Definer"] componentsSeparatedByString:@"@"];
- NSString *escapedDefiner = [NSString stringWithFormat:@"%@@%@",
- [[triggersDefiner objectAtIndex:0] backtickQuotedString],
- [[triggersDefiner objectAtIndex:1] backtickQuotedString]
- ];
+ for (int s=0; s<[queryResult numOfRows]; s++) {
+ NSDictionary *triggers = [[NSDictionary alloc] initWithDictionary:[queryResult fetchRowAsDictionary]];
+
+ //Definer is user@host but we need to escape it to `user`@`host`
+ NSArray *triggersDefiner = [[triggers objectForKey:@"Definer"] componentsSeparatedByString:@"@"];
+ NSString *escapedDefiner = [NSString stringWithFormat:@"%@@%@",
+ [[triggersDefiner objectAtIndex:0] backtickQuotedString],
+ [[triggersDefiner objectAtIndex:1] backtickQuotedString]
+ ];
+
+ [metaString appendString:[NSString stringWithFormat:@"/*!50003 SET SESSION SQL_MODE=\"%@\" */;;\n",
+ [triggers objectForKey:@"sql_mode"]]];
+ [metaString appendString:@"/*!50003 CREATE */ "];
+ [metaString appendString:[NSString stringWithFormat:@"/*!50017 DEFINER=%@ */ ",
+ escapedDefiner]];
+ [metaString appendString:[NSString stringWithFormat:@"/*!50003 TRIGGER %@ %@ %@ ON %@ FOR EACH ROW %@ */;;\n",
+ [[triggers objectForKey:@"Trigger"] backtickQuotedString],
+ [triggers objectForKey:@"Timing"],
+ [triggers objectForKey:@"Event"],
+ [[triggers objectForKey:@"Table"] backtickQuotedString],
+ [triggers objectForKey:@"Statement"]
+ ]];
+ [triggers release];
+ }
- [metaString appendString:[NSString stringWithFormat:@"/*!50003 SET SESSION SQL_MODE=\"%@\" */;;\n",
- [triggers objectForKey:@"sql_mode"]]];
- [metaString appendString:@"/*!50003 CREATE */ "];
- [metaString appendString:[NSString stringWithFormat:@"/*!50017 DEFINER=%@ */ ",
- escapedDefiner]];
- [metaString appendString:[NSString stringWithFormat:@"/*!50003 TRIGGER %@ %@ %@ ON %@ FOR EACH ROW %@ */;;\n",
- [[triggers objectForKey:@"Trigger"] backtickQuotedString],
- [triggers objectForKey:@"Timing"],
- [triggers objectForKey:@"Event"],
- [[triggers objectForKey:@"Table"] backtickQuotedString],
- [triggers objectForKey:@"Statement"]
- ]];
- [triggers release];
+ [metaString appendString:@"DELIMITER ;\n"];
+ [metaString appendString:@"/*!50003 SET SESSION SQL_MODE=@OLD_SQL_MODE */;\n"];
+ [fileHandle writeData:[metaString dataUsingEncoding:NSUTF8StringEncoding]];
}
- [metaString appendString:@"DELIMITER ;\n"];
- [metaString appendString:@"/*!50003 SET SESSION SQL_MODE=@OLD_SQL_MODE */;\n"];
- [fileHandle writeData:[metaString dataUsingEncoding:NSUTF8StringEncoding]];
- }
-
- if ([mySQLConnection queryErrored]) {
- [errors appendString:[NSString stringWithFormat:@"%@\n", [mySQLConnection getLastErrorMessage]]];
- if ( [addErrorsSwitch state] == NSOnState ) {
- [fileHandle writeData:[[NSString stringWithFormat:@"# Error: %@\n", [mySQLConnection getLastErrorMessage]]
- dataUsingEncoding:NSUTF8StringEncoding]];
+ if ([mySQLConnection queryErrored]) {
+ [errors appendString:[NSString stringWithFormat:@"%@\n", [mySQLConnection getLastErrorMessage]]];
+ if ( [addErrorsSwitch state] == NSOnState ) {
+ [fileHandle writeData:[[NSString stringWithFormat:@"# Error: %@\n", [mySQLConnection getLastErrorMessage]]
+ dataUsingEncoding:NSUTF8StringEncoding]];
+ }
}
+
}
// Add an additional separator between tables
@@ -2147,7 +2011,7 @@
See here for language syntax: http://www.graphviz.org/doc/info/lang.html
(Not the easiest to decode)
*/
-- (BOOL)dumpSchemaAsDotToFileHandle:(SPFileHandle *)fileHandle
+- (BOOL)dumpSchemaAsDotToFileHandle:(NSFileHandle *)fileHandle
{
NSMutableString *metaString = [NSMutableString string];
NSInteger progressBarWidth;
@@ -2292,7 +2156,7 @@
/*
* Takes an array, or a streaming result set, and writes the appropriate data
- * in CSV format to the supplied SPFileHandle.
+ * 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
@@ -2301,7 +2165,7 @@
* for arrays, this must be accurate, but for streaming result sets it is only
* used for drawing the progress bar.
*/
-- (BOOL)writeCsvForArray:(NSArray *)array orStreamingResult:(MCPStreamingResult *)streamingResult toFileHandle:(SPFileHandle *)fileHandle
+- (BOOL)writeCsvForArray:(NSArray *)array orStreamingResult:(MCPStreamingResult *)streamingResult toFileHandle:(NSFileHandle *)fileHandle
outputFieldNames:(BOOL)outputFieldNames
terminatedBy:(NSString *)fieldSeparatorString
enclosedBy:(NSString *)enclosingString
@@ -2546,14 +2410,14 @@
/*
* Takes an array, or streaming result reference, and writes it in XML
- * format to the supplied SPFileHandle. For output, also takes a table
+ * 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 orStreamingResult:(MCPStreamingResult *)streamingResult toFileHandle:(SPFileHandle *)fileHandle tableName:(NSString *)table withHeader:(BOOL)header totalRows:(NSInteger)totalRows 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]];
@@ -2718,7 +2582,7 @@
Processes the selected tables within the multiple table export accessory view and passes them
to be exported.
*/
-- (BOOL)exportSelectedTablesToFileHandle:(SPFileHandle *)fileHandle usingFormat:(NSString *)type
+- (BOOL)exportSelectedTablesToFileHandle:(NSFileHandle *)fileHandle usingFormat:(NSString *)type
{
NSInteger i;
NSMutableArray *selectedTables = [NSMutableArray array];
@@ -2737,7 +2601,7 @@
Walks through the selected tables and exports them to a file handle. The export type must be
"csv" for CSV format, and "xml" for XML format.
*/
-- (BOOL)exportTables:(NSArray *)selectedTables toFileHandle:(SPFileHandle *)fileHandle usingFormat:(NSString *)type usingMulti:(BOOL)multi
+- (BOOL)exportTables:(NSArray *)selectedTables toFileHandle:(NSFileHandle *)fileHandle usingFormat:(NSString *)type usingMulti:(BOOL)multi
{
NSInteger i, j;
MCPResult *queryResult;
@@ -3113,14 +2977,6 @@
// If a single file is selected and the extension is recognised, change the format dropdown automatically
if ( [selectedFilenames count] != 1 ) return;
pathExtension = [[[selectedFilenames objectAtIndex:0] pathExtension] uppercaseString];
-
- // If a file has extension ".gz", indicating gzip, fetch the next extension
- if ([pathExtension isEqualToString:@"GZ"]) {
- NSMutableString *pathString = [NSMutableString stringWithString:[selectedFilenames objectAtIndex:0]];
- [pathString deleteCharactersInRange:NSMakeRange([pathString length]-3, 3)];
- pathExtension = [[pathString pathExtension] uppercaseString];
- }
-
if ([pathExtension isEqualToString:@"SQL"]) {
[importFormatPopup selectItemWithTitle:@"SQL"];
[self changeFormat:self];
@@ -3156,33 +3012,6 @@
}
}
-/**
- * When the compression setting on export is altered, update the filename
- * and if appropriate the required extension.
- */
-- (IBAction)updateExportCompressionSetting:(id)sender
-{
- if (exportMode == SPExportingSQL) {
- if ([sender state] == NSOnState) {
- [currentExportPanel setAllowedFileTypes:[NSArray arrayWithObjects:@"sql.gz", @"gz", nil]];
-
- // if file name text view is the first responder re-select the path name only without '.sql.gz'
- if([[currentExportPanel firstResponder] isKindOfClass:[NSTextView class]]) {
- NSTextView *filenameTextView = (NSTextView *)[currentExportPanel firstResponder];
- if([filenameTextView selectedRange].length > 4 && [[filenameTextView string] hasSuffix:@".sql.gz"]) {
- NSRange selRange = [filenameTextView selectedRange];
- selRange.length -= 4;
- [filenameTextView setSelectedRange:selRange];
- }
- }
-
- } else {
- [currentExportPanel setAllowedFileTypes:[NSArray arrayWithObject:@"sql"]];
- }
- [prefs setBool:([sender state] == NSOnState) forKey:SPSQLExportUseCompression];
- }
-}
-
#pragma mark -
#pragma mark Other
diff --git a/Source/TableSource.m b/Source/TableSource.m
index d6c8fdcf..27314b03 100644
--- a/Source/TableSource.m
+++ b/Source/TableSource.m
@@ -346,9 +346,9 @@
// Check whether a save of the current row is required.
if (![self saveRowOnDeselect]) return;
-
+
NSInteger index = [tableSourceView selectedRow];
-
+
if ((index == -1) || (index > ([tableFields count] - 1))) return;
// Check if the user tries to delete the last defined field in table
@@ -358,7 +358,7 @@
defaultButton:NSLocalizedString(@"OK", @"OK button")
alternateButton:nil
otherButton:nil
- informativeTextWithFormat:NSLocalizedString(@"You cannot delete the last field in a table. Delete the table instead.", @"You cannot delete the last field in a table. Delete the table instead.")];
+ informativeTextWithFormat:NSLocalizedString(@"You cannot delete the last field in a table. Use 'Remove table' (DROP TABLE) instead.", @"You cannot delete the last field in that table. Use 'Remove table' (DROP TABLE) instead")];
[alert setAlertStyle:NSCriticalAlertStyle];
@@ -389,7 +389,7 @@
defaultButton:NSLocalizedString(@"Delete", @"delete button")
alternateButton:NSLocalizedString(@"Cancel", @"cancel button")
otherButton:nil
- informativeTextWithFormat:(hasForeignKey) ? [NSString stringWithFormat:NSLocalizedString(@"This field is part of a foreign key relationship with the table '%@'. This relationship must be removed before the field can be deleted.\n\nAre you sure you want to continue to delete the relationship and the field? This action cannot be undone.", @"delete field and foreign key informative message"), referencedTable] : [NSString stringWithFormat:NSLocalizedString(@"Are you sure you want to delete the field '%@'? This action cannot be undone.", @"delete field informative message"), field]];
+ informativeTextWithFormat:(hasForeignKey) ? [NSString stringWithFormat:NSLocalizedString(@"This field is part of a foreign key relationship with the table '%@'. This relationship must be removed before the field can be deleted.\n\nAre you sure you want to continue to remove the relationship and the field? This action cannot be undone.", @"delete field and foreign key informative message"), referencedTable] : [NSString stringWithFormat:NSLocalizedString(@"Are you sure you want to delete the field '%@'? This action cannot be undone.", @"delete field informative message"), field]];
[alert setAlertStyle:NSCriticalAlertStyle];
@@ -414,11 +414,11 @@
if (![self saveRowOnDeselect]) return;
NSInteger index = [indexView selectedRow];
-
- if ((index == -1) || (index > ([indexes count] - 1))) return;
-
- NSString *keyName = [[indexes objectAtIndex:index] objectForKey:@"Key_name"];
- NSString *columnName = [[indexes objectAtIndex:index] objectForKey:@"Column_name"];
+
+ if ((index == -1) || (index > ([indexes count] - 1))) return;
+
+ NSString *keyName = [[indexes objectAtIndex:index] objectForKey:@"Key_name"];
+ NSString *columnName = [[indexes objectAtIndex:index] objectForKey:@"Column_name"];
BOOL hasForeignKey = NO;
NSString *constraintName = @"";
@@ -441,7 +441,7 @@
defaultButton:NSLocalizedString(@"Delete", @"delete button")
alternateButton:NSLocalizedString(@"Cancel", @"cancel button")
otherButton:nil
- informativeTextWithFormat:(hasForeignKey) ? [NSString stringWithFormat:NSLocalizedString(@"The foreign key relationship '%@' has a dependency on this index. This relationship must be removed before the index can be deleted.\n\nAre you sure you want to continue to delete the relationship and the index? This action cannot be undone.", @"delete index and foreign key informative message"), constraintName] : [NSString stringWithFormat:NSLocalizedString(@"Are you sure you want to delete the index '%@'? This action cannot be undone.", @"delete index informative message"), keyName]];
+ informativeTextWithFormat:(hasForeignKey) ? [NSString stringWithFormat:NSLocalizedString(@"The foreign key relationship '%@' has a dependency on this index. This relationship must be removed before the index can be deleted.\n\nAre you sure you want to continue to remove the relationship and the index? This action cannot be undone.", @"delete index and foreign key informative message"), constraintName] : [NSString stringWithFormat:NSLocalizedString(@"Are you sure you want to delete the index '%@'? This action cannot be undone.", @"delete index informative message"), keyName]];
[alert setAlertStyle:NSCriticalAlertStyle];
@@ -589,20 +589,20 @@ closes the keySheet
return;
if(valueAsString == nil || ![valueAsString length]) {
- // reload data and bail
- [tableDataInstance resetAllData];
- [extendedTableInfoInstance loadTable:selTable];
- [tableInfoInstance tableChanged:nil];
- return;
- }
-
- NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
- [formatter setNumberStyle:NSNumberFormatterDecimalStyle];
- NSNumber *autoIncValue = [formatter numberFromString:valueAsString];
- [formatter release];
-
- [mySQLConnection queryString:[NSString stringWithFormat:@"ALTER TABLE %@ AUTO_INCREMENT = %@", [selTable backtickQuotedString], [autoIncValue stringValue]]];
+ // reload data and bail
+ [tableDataInstance resetAllData];
+ [extendedTableInfoInstance loadTable:selTable];
+ [tableInfoInstance tableChanged:nil];
+ return;
+ }
+
+ NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
+ [formatter setNumberStyle:NSNumberFormatterDecimalStyle];
+ NSNumber *autoIncValue = [formatter numberFromString:valueAsString];
+ [formatter release];
+
+ [mySQLConnection queryString:[NSString stringWithFormat:@"ALTER TABLE %@ AUTO_INCREMENT = %@", [selTable backtickQuotedString], [autoIncValue stringValue]]];
if ([mySQLConnection queryErrored]) {
SPBeginAlertSheet(NSLocalizedString(@"Error", @"error"),
NSLocalizedString(@"OK", @"OK button"),
@@ -611,15 +611,14 @@ closes the keySheet
selTable, [mySQLConnection getLastErrorMessage]]);
}
- // reload data
- [tableDataInstance resetStatusData];
- if([[tableDocumentInstance valueForKeyPath:@"tableTabView"] indexOfTabViewItem:[[tableDocumentInstance valueForKeyPath:@"tableTabView"] selectedTabViewItem]] == 3) {
- [tableDataInstance resetAllData];
- [extendedTableInfoInstance loadTable:selTable];
- }
-
- [tableInfoInstance tableChanged:nil];
+ // reload data
+ [tableDataInstance resetStatusData];
+ if([[tableDocumentInstance valueForKeyPath:@"tableTabView"] indexOfTabViewItem:[[tableDocumentInstance valueForKeyPath:@"tableTabView"] selectedTabViewItem]] == 3) {
+ [tableDataInstance resetAllData];
+ [extendedTableInfoInstance loadTable:selTable];
+ }
+ [tableInfoInstance tableChanged:nil];
}
/**
@@ -937,23 +936,23 @@ closes the keySheet
/**
* A method to show an error sheet after a short delay, so that it can
- * be called from within an endSheet selector. This should be called on
+ * be called from within an endSheet selector. This should be called on
* the main thread.
*/
-(void)showErrorSheetWith:(NSDictionary *)errorDictionary
{
- // If this method has been called directly, invoke a delay. Invoking the delay
- // on the main thread ensures the timer fires on the main thread.
- if (![errorDictionary objectForKey:@"delayed"]) {
- NSMutableDictionary *delayedErrorDictionary = [NSMutableDictionary dictionaryWithDictionary:errorDictionary];
- [delayedErrorDictionary setObject:[NSNumber numberWithBool:YES] forKey:@"delayed"];
- [self performSelector:@selector(showErrorSheetWith:) withObject:delayedErrorDictionary afterDelay:0.3];
- return;
- }
-
- // Display the error sheet
- SPBeginAlertSheet([errorDictionary objectForKey:@"title"], NSLocalizedString(@"OK", @"OK button"),
+ // If this method has been called directly, invoke a delay. Invoking the delay
+ // on the main thread ensures the timer fires on the main thread.
+ if (![errorDictionary objectForKey:@"delayed"]) {
+ NSMutableDictionary *delayedErrorDictionary = [NSMutableDictionary dictionaryWithDictionary:errorDictionary];
+ [delayedErrorDictionary setObject:[NSNumber numberWithBool:YES] forKey:@"delayed"];
+ [self performSelector:@selector(showErrorSheetWith:) withObject:delayedErrorDictionary afterDelay:0.3];
+ return;
+ }
+
+ // Display the error sheet
+ SPBeginAlertSheet([errorDictionary objectForKey:@"title"], NSLocalizedString(@"OK", @"OK button"),
nil, nil, tableWindow, self, nil, nil, nil,
[errorDictionary objectForKey:@"message"]);
}
@@ -1785,8 +1784,8 @@ would result in a position change.
// Check for errors, but only if the query wasn't cancelled
if ([mySQLConnection queryErrored] && ![mySQLConnection queryCancelled]) {
NSMutableDictionary *errorDictionary = [NSMutableDictionary dictionary];
- [errorDictionary setObject:NSLocalizedString(@"Unable to delete relation", @"error deleting relation message") forKey:@"title"];
- [errorDictionary setObject:[NSString stringWithFormat:NSLocalizedString(@"An error occurred while trying to delete the relation '%@'.\n\nMySQL said: %@", @"error deleting relation informative message"), relationName, [mySQLConnection getLastErrorMessage]] forKey:@"message"];
+ [errorDictionary setObject:NSLocalizedString(@"Unable to remove relation", @"error removing relation message") forKey:@"title"];
+ [errorDictionary setObject:[NSString stringWithFormat:NSLocalizedString(@"An error occurred while trying to remove the relation '%@'.\n\nMySQL said: %@", @"error removing relation informative message"), relationName, [mySQLConnection getLastErrorMessage]] forKey:@"message"];
[[self onMainThread] showErrorSheetWith:errorDictionary];
}
}
@@ -1797,9 +1796,10 @@ would result in a position change.
// Check for errors, but only if the query wasn't cancelled
if ([mySQLConnection queryErrored] && ![mySQLConnection queryCancelled]) {
+
NSMutableDictionary *errorDictionary = [NSMutableDictionary dictionary];
[errorDictionary setObject:NSLocalizedString(@"Error", @"error") forKey:@"title"];
- [errorDictionary setObject:[NSString stringWithFormat:NSLocalizedString(@"Couldn't delete field %@.\nMySQL said: %@", @"message of panel when field cannot be deleted"),
+ [errorDictionary setObject:[NSString stringWithFormat:NSLocalizedString(@"Couldn't remove field %@.\nMySQL said: %@", @"message of panel when field cannot be removed"),
[[tableFields objectAtIndex:[tableSourceView selectedRow]] objectForKey:@"Field"],
[mySQLConnection getLastErrorMessage]] forKey:@"message"];
[[self onMainThread] showErrorSheetWith:errorDictionary];
@@ -1850,9 +1850,9 @@ would result in a position change.
// Check for errors, but only if the query wasn't cancelled
if ([mySQLConnection queryErrored] && ![mySQLConnection queryCancelled]) {
NSMutableDictionary *errorDictionary = [NSMutableDictionary dictionary];
- [errorDictionary setObject:NSLocalizedString(@"Unable to delete relation", @"error deleting relation message") forKey:@"title"];
- [errorDictionary setObject:[NSString stringWithFormat:NSLocalizedString(@"An error occurred while trying to delete the relation '%@'.\n\nMySQL said: %@", @"error deleting relation informative message"), constraintName, [mySQLConnection getLastErrorMessage]] forKey:@"message"];
- [[self onMainThread] showErrorSheetWith:errorDictionary];
+ [errorDictionary setObject:NSLocalizedString(@"Unable to remove relation", @"error removing relation message") forKey:@"title"];
+ [errorDictionary setObject:[NSString stringWithFormat:NSLocalizedString(@"An error occurred while trying to remove the relation '%@'.\n\nMySQL said: %@", @"error removing relation informative message"), constraintName, [mySQLConnection getLastErrorMessage]] forKey:@"message"];
+ [[self onMainThread] showErrorSheetWith:errorDictionary];
}
}
@@ -1867,8 +1867,8 @@ would result in a position change.
// Check for errors, but only if the query wasn't cancelled
if ([mySQLConnection queryErrored] && ![mySQLConnection queryCancelled]) {
NSMutableDictionary *errorDictionary = [NSMutableDictionary dictionary];
- [errorDictionary setObject:NSLocalizedString(@"Unable to delete index", @"error deleting index message") forKey:@"title"];
- [errorDictionary setObject:[NSString stringWithFormat:NSLocalizedString(@"An error occured while trying to delete the index.\n\nMySQL said: %@", @"error deleting index informative message"), [mySQLConnection getLastErrorMessage]] forKey:@"message"];
+ [errorDictionary setObject:NSLocalizedString(@"Unable to remove index", @"error removing index message") forKey:@"title"];
+ [errorDictionary setObject:[NSString stringWithFormat:NSLocalizedString(@"An error occured while trying to remove the index.\n\nMySQL said: %@", @"error removing index informative message"), [mySQLConnection getLastErrorMessage]] forKey:@"message"];
[[self onMainThread] showErrorSheetWith:errorDictionary];
}
else {
diff --git a/Source/TablesList.h b/Source/TablesList.h
index 36d3ccaa..f6741369 100644
--- a/Source/TablesList.h
+++ b/Source/TablesList.h
@@ -48,7 +48,6 @@
IBOutlet id extendedTableInfoInstance;
IBOutlet id databaseDataInstance;
IBOutlet id tableInfoInstance;
- IBOutlet id tableTriggersInstance;
IBOutlet SPHistoryController *spHistoryControllerInstance;
IBOutlet id tableWindow;
@@ -82,7 +81,7 @@
IBOutlet NSMenuItem *separatorTableMenuItem;
IBOutlet NSMenuItem *showCreateSyntaxMenuItem;
IBOutlet NSMenuItem *separatorTableMenuItem2;
-
+
MCPConnection *mySQLConnection;
// Table list context menu items
@@ -103,7 +102,7 @@
BOOL tableListIsSelectable;
BOOL tableListContainsViews;
- BOOL structureLoaded, contentLoaded, statusLoaded, triggersLoaded, alertSheetOpened;
+ BOOL structureLoaded, contentLoaded, statusLoaded, alertSheetOpened;
}
// IBAction methods
diff --git a/Source/TablesList.m b/Source/TablesList.m
index 15def773..b9e8270a 100644
--- a/Source/TablesList.m
+++ b/Source/TablesList.m
@@ -253,12 +253,11 @@
// Query the structure of all databases in the background
if(sender == self)
- // Invoked by SP
+ // Invoked by SP
[NSThread detachNewThreadSelector:@selector(queryDbStructureWithUserInfo:) toTarget:mySQLConnection withObject:nil];
else
// User press refresh button ergo force update
[NSThread detachNewThreadSelector:@selector(queryDbStructureWithUserInfo:) toTarget:mySQLConnection withObject:[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], @"forceUpdate", [NSNumber numberWithBool:YES], @"cancelQuerying", nil]];
-
}
@@ -693,35 +692,40 @@
// Restore view states as appropriate
[spHistoryControllerInstance restoreViewStates];
- structureLoaded = NO;
- contentLoaded = NO;
- statusLoaded = NO;
- triggersLoaded = NO;
if( selectedTableType == SPTableTypeView || selectedTableType == SPTableTypeTable) {
if ( [tabView indexOfTabViewItem:[tabView selectedTabViewItem]] == 0 ) {
[tableSourceInstance loadTable:selectedTableName];
structureLoaded = YES;
+ contentLoaded = NO;
+ statusLoaded = NO;
} else if ( [tabView indexOfTabViewItem:[tabView selectedTabViewItem]] == 1 ) {
if(tableEncoding == nil) {
[tableContentInstance loadTable:nil];
} else {
[tableContentInstance loadTable:selectedTableName];
}
+ structureLoaded = NO;
contentLoaded = YES;
+ statusLoaded = NO;
} else if ( [tabView indexOfTabViewItem:[tabView selectedTabViewItem]] == 3 ) {
- [[extendedTableInfoInstance onMainThread] loadTable:selectedTableName];
+ [extendedTableInfoInstance performSelectorOnMainThread:@selector(loadTable:) withObject:selectedTableName waitUntilDone:YES];
+ structureLoaded = NO;
+ contentLoaded = NO;
statusLoaded = YES;
- } else if ( [tabView indexOfTabViewItem:[tabView selectedTabViewItem]] == 5 ) {
- [[tableTriggersInstance onMainThread] loadTriggers];
- triggersLoaded = YES;
+ } else {
+ structureLoaded = NO;
+ contentLoaded = NO;
+ statusLoaded = NO;
}
} else {
// if we are not looking at a table or view, clear these
[tableSourceInstance loadTable:nil];
[tableContentInstance loadTable:nil];
- [[extendedTableInfoInstance onMainThread] loadTable:nil];
- [[tableTriggersInstance onMainThread] loadTriggers];
+ [extendedTableInfoInstance performSelectorOnMainThread:@selector(loadTable:) withObject:nil waitUntilDone:YES];
+ structureLoaded = NO;
+ contentLoaded = NO;
+ statusLoaded = NO;
}
// Update the "Show Create Syntax" window if it's already opened
@@ -751,77 +755,73 @@
// Update the selected table name and type
if (selectedTableName) [selectedTableName release];
-
+
if ([indexes count]) {
selectedTableName = [[NSString alloc] initWithString:@""];
- }
+ }
else {
selectedTableName = nil;
}
-
+
selectedTableType = SPTableTypeNone;
[tableSourceInstance loadTable:nil];
[tableContentInstance loadTable:nil];
[extendedTableInfoInstance loadTable:nil];
- [tableTriggersInstance loadTriggers];
-
+
structureLoaded = NO;
contentLoaded = NO;
statusLoaded = NO;
- triggersLoaded = NO;
// Set gear menu items Remove/Duplicate table/view according to the table types
// if at least one item is selected
if ([indexes count]) {
-
NSUInteger currentIndex = [indexes lastIndex];
BOOL areTableTypeEqual = YES;
NSInteger lastType = [[filteredTableTypes objectAtIndex:currentIndex] integerValue];
-
+
while (currentIndex != NSNotFound)
{
if ([[filteredTableTypes objectAtIndex:currentIndex] integerValue] != lastType) {
areTableTypeEqual = NO;
break;
}
-
+
currentIndex = [indexes indexLessThanIndex:currentIndex];
}
-
if (areTableTypeEqual) {
switch (lastType) {
case SPTableTypeTable:
- [removeTableMenuItem setTitle:NSLocalizedString(@"Delete Tables", @"delete tables menu title")];
+ [removeTableMenuItem setTitle:NSLocalizedString(@"Remove Tables", @"remove tables menu title")];
[truncateTableButton setTitle:NSLocalizedString(@"Truncate Tables", @"truncate tables menu item")];
- [removeTableContextMenuItem setTitle:NSLocalizedString(@"Delete Tables", @"delete tables menu title")];
+ [removeTableContextMenuItem setTitle:NSLocalizedString(@"Remove Tables", @"remove tables menu title")];
[truncateTableContextButton setTitle:NSLocalizedString(@"Truncate Tables", @"truncate tables menu item")];
[truncateTableButton setHidden:NO];
[truncateTableContextButton setHidden:NO];
break;
case SPTableTypeView:
- [removeTableMenuItem setTitle:NSLocalizedString(@"Delete Views", @"delete views menu title")];
- [removeTableContextMenuItem setTitle:NSLocalizedString(@"Delete Views", @"delete views menu title")];
+ [removeTableMenuItem setTitle:NSLocalizedString(@"Remove Views", @"remove views menu title")];
+ [removeTableContextMenuItem setTitle:NSLocalizedString(@"Remove Views", @"remove views menu title")];
[truncateTableButton setHidden:YES];
[truncateTableContextButton setHidden:YES];
break;
case SPTableTypeProc:
- [removeTableMenuItem setTitle:NSLocalizedString(@"Delete Procedures", @"delete procedures menu title")];
- [removeTableContextMenuItem setTitle:NSLocalizedString(@"Delete Procedures", @"delete procedures menu title")];
+ [removeTableMenuItem setTitle:NSLocalizedString(@"Remove Procedures", @"remove procedures menu title")];
+ [removeTableContextMenuItem setTitle:NSLocalizedString(@"Remove Procedures", @"remove procedures menu title")];
[truncateTableButton setHidden:YES];
[truncateTableContextButton setHidden:YES];
break;
case SPTableTypeFunc:
- [removeTableMenuItem setTitle:NSLocalizedString(@"Delete Functions", @"delete functions menu title")];
- [removeTableContextMenuItem setTitle:NSLocalizedString(@"Delete Functions", @"delete functions menu title")];
+ [removeTableMenuItem setTitle:NSLocalizedString(@"Remove Functions", @"remove functions menu title")];
+ [removeTableContextMenuItem setTitle:NSLocalizedString(@"Remove Functions", @"remove functions menu title")];
[truncateTableButton setHidden:YES];
[truncateTableContextButton setHidden:YES];
break;
}
} else {
- [removeTableMenuItem setTitle:NSLocalizedString(@"Delete Items", @"delete items menu title")];
- [removeTableContextMenuItem setTitle:NSLocalizedString(@"Delete Items", @"delete items menu title")];
+ [removeTableMenuItem setTitle:NSLocalizedString(@"Remove Items", @"remove items menu title")];
+ [removeTableContextMenuItem setTitle:NSLocalizedString(@"Remove Items", @"remove items menu title")];
[truncateTableButton setHidden:YES];
[truncateTableContextButton setHidden:YES];
}
@@ -840,7 +840,7 @@
[separatorTableMenuItem setHidden:YES];
[separatorTableMenuItem2 setHidden:YES];
[showCreateSyntaxMenuItem setHidden:YES];
-
+
NSMenu *tableSubMenu = [[[NSApp mainMenu] itemWithTitle:@"Table"] submenu];
[[tableSubMenu itemAtIndex:6] setTitle:NSLocalizedString(@"Check Selected Items", @"check selected items menu item")];
@@ -894,7 +894,7 @@
[separatorTableContextMenuItem setHidden:NO];
[separatorTableMenuItem2 setHidden:NO];
[separatorTableContextMenuItem2 setHidden:NO];
-
+
// Set gear menu items Remove/Duplicate table/view and mainMenu > Table items
// according to the table types
NSMenu *tableSubMenu = [[[NSApp mainMenu] itemWithTitle:@"Table"] submenu];
@@ -922,7 +922,7 @@
[duplicateTableMenuItem setHidden:NO];
[duplicateTableMenuItem setTitle:NSLocalizedString(@"Duplicate View...", @"duplicate view menu title")];
[truncateTableButton setHidden:YES];
- [removeTableMenuItem setTitle:NSLocalizedString(@"Delete View", @"delete view menu title")];
+ [removeTableMenuItem setTitle:NSLocalizedString(@"Remove View", @"remove view menu title")];
[showCreateSyntaxMenuItem setHidden:NO];
[showCreateSyntaxMenuItem setTitle:NSLocalizedString(@"Show Create View Syntax...", @"show create view syntax menu item")];
@@ -931,7 +931,7 @@
[duplicateTableContextMenuItem setHidden:NO];
[duplicateTableContextMenuItem setTitle:NSLocalizedString(@"Duplicate View...", @"duplicate view menu title")];
[truncateTableContextButton setHidden:YES];
- [removeTableContextMenuItem setTitle:NSLocalizedString(@"Delete View", @"delete view menu title")];
+ [removeTableContextMenuItem setTitle:NSLocalizedString(@"Remove View", @"remove view menu title")];
[showCreateSyntaxContextMenuItem setHidden:NO];
[showCreateSyntaxContextMenuItem setTitle:NSLocalizedString(@"Show Create View Syntax...", @"show create view syntax menu item")];
}
@@ -959,7 +959,7 @@
[duplicateTableMenuItem setTitle:NSLocalizedString(@"Duplicate Table...", @"duplicate table menu title")];
[truncateTableButton setHidden:NO];
[truncateTableButton setTitle:NSLocalizedString(@"Truncate Table", @"truncate table menu title")];
- [removeTableMenuItem setTitle:NSLocalizedString(@"Delete Table", @"delete table menu title")];
+ [removeTableMenuItem setTitle:NSLocalizedString(@"Remove Table", @"remove table menu title")];
[showCreateSyntaxMenuItem setHidden:NO];
[showCreateSyntaxMenuItem setTitle:NSLocalizedString(@"Show Create Table Syntax...", @"show create table syntax menu item")];
@@ -969,7 +969,7 @@
[duplicateTableContextMenuItem setTitle:NSLocalizedString(@"Duplicate Table...", @"duplicate table menu title")];
[truncateTableContextButton setHidden:NO];
[truncateTableContextButton setTitle:NSLocalizedString(@"Truncate Table", @"truncate table menu title")];
- [removeTableContextMenuItem setTitle:NSLocalizedString(@"Delete Table", @"delete table menu title")];
+ [removeTableContextMenuItem setTitle:NSLocalizedString(@"Remove Table", @"remove table menu title")];
[showCreateSyntaxContextMenuItem setHidden:NO];
[showCreateSyntaxContextMenuItem setTitle:NSLocalizedString(@"Show Create Table Syntax...", @"show create table syntax menu item")];
}
@@ -990,16 +990,16 @@
[duplicateTableMenuItem setHidden:NO];
[duplicateTableMenuItem setTitle:NSLocalizedString(@"Duplicate Procedure...", @"duplicate proc menu title")];
[truncateTableButton setHidden:YES];
- [removeTableMenuItem setTitle:NSLocalizedString(@"Delete Procedure", @"delete proc menu title")];
+ [removeTableMenuItem setTitle:NSLocalizedString(@"Remove Procedure", @"remove proc menu title")];
[showCreateSyntaxMenuItem setHidden:NO];
[showCreateSyntaxMenuItem setTitle:NSLocalizedString(@"Show Create Procedure Syntax...", @"show create proc syntax menu item")];
-
+
[renameTableContextMenuItem setHidden:NO];
[renameTableContextMenuItem setTitle:NSLocalizedString(@"Rename Procedure...", @"rename proc menu title")];
[duplicateTableContextMenuItem setHidden:NO];
[duplicateTableContextMenuItem setTitle:NSLocalizedString(@"Duplicate Procedure...", @"duplicate proc menu title")];
[truncateTableContextButton setHidden:YES];
- [removeTableContextMenuItem setTitle:NSLocalizedString(@"Delete Procedure", @"delete proc menu title")];
+ [removeTableContextMenuItem setTitle:NSLocalizedString(@"Remove Procedure", @"remove proc menu title")];
[showCreateSyntaxContextMenuItem setHidden:NO];
[showCreateSyntaxContextMenuItem setTitle:NSLocalizedString(@"Show Create Procedure Syntax...", @"show create proc syntax menu item")];
}
@@ -1020,16 +1020,16 @@
[duplicateTableMenuItem setHidden:NO];
[duplicateTableMenuItem setTitle:NSLocalizedString(@"Duplicate Function...", @"duplicate func menu title")];
[truncateTableButton setHidden:YES];
- [removeTableMenuItem setTitle:NSLocalizedString(@"Delete Function", @"delete func menu title")];
+ [removeTableMenuItem setTitle:NSLocalizedString(@"Remove Function", @"remove func menu title")];
[showCreateSyntaxMenuItem setHidden:NO];
[showCreateSyntaxMenuItem setTitle:NSLocalizedString(@"Show Create Function Syntax...", @"show create func syntax menu item")];
-
+
[renameTableContextMenuItem setHidden:NO];
[renameTableContextMenuItem setTitle:NSLocalizedString(@"Rename Function...", @"rename func menu title")];
[duplicateTableContextMenuItem setHidden:NO];
[duplicateTableContextMenuItem setTitle:NSLocalizedString(@"Duplicate Function...", @"duplicate func menu title")];
[truncateTableContextButton setHidden:YES];
- [removeTableContextMenuItem setTitle:NSLocalizedString(@"Delete Function", @"delete func menu title")];
+ [removeTableContextMenuItem setTitle:NSLocalizedString(@"Remove Function", @"remove func menu title")];
[showCreateSyntaxContextMenuItem setHidden:NO];
[showCreateSyntaxContextMenuItem setTitle:NSLocalizedString(@"Show Create Function Syntax...", @"show create func syntax menu item")];
}
@@ -1355,27 +1355,24 @@
// if the 'table' is a view or a table, reload the currently selected view
if (selectedTableType == SPTableTypeTable || selectedTableType == SPTableTypeView)
{
- statusLoaded = NO;
- structureLoaded = NO;
- contentLoaded = NO;
- triggersLoaded = NO;
switch ([tabView indexOfTabViewItem:[tabView selectedTabViewItem]]) {
case 0:
[tableSourceInstance loadTable:newTableName];
structureLoaded = YES;
+ contentLoaded = statusLoaded = NO;
break;
case 1:
[tableContentInstance loadTable:newTableName];
contentLoaded = YES;
+ structureLoaded = statusLoaded = NO;
break;
case 3:
[extendedTableInfoInstance loadTable:newTableName];
statusLoaded = YES;
+ structureLoaded = contentLoaded = NO;
break;
- case 5:
- [tableTriggersInstance loadTriggers];
- triggersLoaded = YES;
- break;
+ default:
+ statusLoaded = structureLoaded = contentLoaded = NO;
}
}
}
@@ -1560,9 +1557,8 @@
{
NSAutoreleasePool *tabLoadPool = [[NSAutoreleasePool alloc] init];
- if ([tablesListView numberOfSelectedRows] == 1
- && ([self tableType] == SPTableTypeTable || [self tableType] == SPTableTypeView) )
- {
+ if ( [tablesListView numberOfSelectedRows] == 1 &&
+ ([self tableType] == SPTableTypeTable || [self tableType] == SPTableTypeView) ) {
if ( ([tabView indexOfTabViewItem:[tabView selectedTabViewItem]] == 0) && !structureLoaded ) {
[tableSourceInstance loadTable:selectedTableName];
@@ -1575,14 +1571,9 @@
}
if ( ([tabView indexOfTabViewItem:[tabView selectedTabViewItem]] == 3) && !statusLoaded ) {
- [[extendedTableInfoInstance onMainThread] loadTable:selectedTableName];
+ [extendedTableInfoInstance performSelectorOnMainThread:@selector(loadTable:) withObject:selectedTableName waitUntilDone:YES];
statusLoaded = YES;
}
-
- if ( ([tabView indexOfTabViewItem:[tabView selectedTabViewItem]] == 5) && !triggersLoaded ) {
- [[tableTriggersInstance onMainThread] loadTriggers];
- triggersLoaded = YES;
- }
}
else {
[tableSourceInstance loadTable:nil];
@@ -1811,7 +1802,6 @@
structureLoaded = NO;
contentLoaded = NO;
statusLoaded = NO;
- triggersLoaded = NO;
isTableListFiltered = NO;
tableListIsSelectable = YES;
tableListContainsViews = NO;
@@ -1937,7 +1927,7 @@
[alert addButtonWithTitle:NSLocalizedString(@"Stop", @"stop button")];
}
[alert setMessageText:NSLocalizedString(@"Error", @"error")];
- [alert setInformativeText:[NSString stringWithFormat:NSLocalizedString(@"Couldn't delete '%@'.\nMySQL said: %@", @"message of panel when an item cannot be deleted"), [tables objectAtIndex:currentIndex], [mySQLConnection getLastErrorMessage]]];
+ [alert setInformativeText:[NSString stringWithFormat:NSLocalizedString(@"Couldn't remove '%@'.\nMySQL said: %@", @"message of panel when an item cannot be removed"), [tables objectAtIndex:currentIndex], [mySQLConnection getLastErrorMessage]]];
[alert setAlertStyle:NSWarningAlertStyle];
if ([indexes indexLessThanIndex:currentIndex] == NSNotFound) {
[alert beginSheetModalForWindow:tableWindow modalDelegate:self didEndSelector:nil contextInfo:nil];
@@ -2360,7 +2350,7 @@
[mySQLConnection queryString: [NSString stringWithFormat: @"DROP %@ %@", stringTableType, [oldTableName backtickQuotedString]]];
if ([mySQLConnection queryErrored]) {
- [NSException raise:@"MySQL Error" format:NSLocalizedString(@"An error occured while renaming. I couldn't delete '%@'.\n\nMySQL said: %@", @"rename precedure/function error - can't delete old procedure"), oldTableName, [mySQLConnection getLastErrorMessage]];
+ [NSException raise:@"MySQL Error" format:NSLocalizedString(@"An error occured while renaming. I couldn't remove '%@'.\n\nMySQL said: %@", @"rename precedure/function error - can't remove old procedure"), oldTableName, [mySQLConnection getLastErrorMessage]];
}
return;
}